每次点击按钮都运行AsyncTask

时间:2017-01-01 04:40:53

标签: android android-studio android-asynctask

我很难弄清楚如何实现我搜索过的new MyAsyncTask().execute("")因为我有单独的类扩展了Asynctask。我每次点击按钮都要打电话给班级。希望你们能帮助我解决这个问题。

这是我的MainActivity

public class MainActivity extends AppCompatActivity {
String url = "http://192.168.254.103/dbtest/categories.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.start);
    final ListView lv = (ListView) findViewById(R.id.lv);

    final Downloader d = new Downloader(this,url,lv);
       button.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               d.execute();

           }
       });
}

}

这是我的Downloader.java

public class Downloader extends AsyncTask<Void,Integer, String> {

Context c;
String address;
ListView lv;

ProgressDialog pd;

public Downloader(Context c, String address, ListView lv) {
    this.c = c;
    this.address = address;
    this.lv = lv;
}

//BEFORE JOB STARTS
@Override
protected void onPreExecute() {
    super.onPreExecute();

    pd = new ProgressDialog(c);
    pd.setTitle("Fetch Data");
    pd.setMessage("Please Wait");
    pd.show();
}

@Override
protected String doInBackground(Void... params) {

    String data = downloadData();
    return data;
}


@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);

    pd.dismiss();

    if(s != null){

        Parser p =new Parser(c,s,lv);
        p.execute();

    }else
    {
        Toast.makeText(c,"Unable to download data",Toast.LENGTH_SHORT).show();
    }
}

private String downloadData(){

    //connect and get a stream

    InputStream is = null;
    String line = null;

    try{

        URL url =  new URL(address);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        is = new BufferedInputStream(con.getInputStream());

        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        StringBuffer sb = new StringBuffer();

        if(br != null){

            while((line = br.readLine()) != null)
            {
                sb.append(line+"\n");
            }
        }
        else
        {
            return null;
        }

        return sb.toString();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(is != null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

}

和我的Parser.java

public class Parser extends AsyncTask<Void,Integer,Integer> {

Context c;
ListView lv;
String data;

ArrayList<String> categories = new ArrayList<>();
ProgressDialog pd;

public Parser(Context c, String data, ListView lv) {
    this.c = c;
    this.data = data;
    this.lv = lv;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();

    pd = new ProgressDialog(c);
    pd.setTitle("Parser");
    pd.setMessage("Please Wait");
    pd.show();
}

@Override
protected Integer doInBackground(Void... params) {


    return this.parse();
}

@Override
protected void onPostExecute(Integer integer) {
    super.onPostExecute(integer);

    if(integer == 1)
    {
        //ADAPTER
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(c, android.R.layout.simple_list_item_1, categories);
        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

    }else
    {
        Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
    }
    pd.dismiss();
}

//PARSE RECEIVED DATA
private int parse(){
    try
    {

        //ADD TGAT DATA TO JSON ARRAY FIRST
        JSONArray ja = new JSONArray(data);

        //CREATE JO OBJECT TO HOLD A SINGLE ITEM
        JSONObject jo = null;

        categories.clear();

        //LOOP THROUGH ARRAY
        for(int i =0 ; i<ja.length();i++)
        {
            jo = ja.getJSONObject(i);
            //RETRIEVE NAME
            String name=jo.getString("cat_name");

            //ADD TO ARRAY LIST
            categories.add(name);

        }
        return 1;
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return 0;
}

}

0 个答案:

没有答案