欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AsyncTask

程序员文章站 2022-05-04 18:08:06
...
	AsyncTask

package com.example.asyncdemo2;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.bean.MyAdapter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button btn;
private TextView tv;
private List<List<String>> data=new ArrayList<>();
private String murl="https://suggest.taobao.com/sug?code=utf-8&q=%E6%89%8B%E6%9C%BA";
private ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
}

private void initView() {
    btn = (Button) findViewById(R.id.btn);
    tv = (TextView) findViewById(R.id.tv);
    lv = (ListView)findViewById(R.id.lv);

    btn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn:
            new MyTask().execute(murl);

            break;
    }
}

class MyTask extends AsyncTask<String,Void,String>{



    @Override
    protected String doInBackground(String... strings) {
        try {
            String json = HttpUtils.get(murl);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        tv.setText(s);
        Gson gson=new Gson();
        result result = gson.fromJson(s, result.class);
        data = result.getResult();
        Log.d("onPostExecute: zzz",data+"");

        MyAdapter adapter=new MyAdapter(MainActivity.this,data);
        lv.setAdapter(adapter);



    }
}

}

相关标签: 个人