简体   繁体   English

将AsyncTask从类吸引到MainActivity

[英]Appealing an AsyncTask from a class into MainActivity

I am new at android developing and i need a little help with my code. 我是android开发的新手,我的代码需要一些帮助。 I have to use an AsyncTask from a class into my main activity. 我必须从类中使用AsyncTask进入我的主要活动。 And how do I appeal it in the main function? 我如何在主要功能中吸引它?

My main activity: 我的主要活动:

public class ListActivity extends Activity implements OnItemClickListener {
ArrayList<Person> lista;
ProgressDialog progress;
private ListView lv;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lista);
    lv = (ListView) findViewById(R.id.list);
    lv.setOnItemClickListener(this);

    new DataReturn().onPostExecute("random ip"); 

}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    Person p = (Person) arg0.getItemAtPosition(arg2);
    new AlertDialog.Builder(ListActivity.this).setTitle("Information").setMessage(p.getLastName()).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).setIcon(android.R.drawable.ic_dialog_alert).show();

}

And my AsyncTask code is: 我的AsyncTask代码是:

public class DataReturn extends AsyncTask<String,Void,String> {
ArrayList<Person> rlist;
Dialog progress;
ListView rlv;
Context context;
@Override
protected void onPreExecute() {
    super.onPreExecute();
    ProgressDialog progress = new ProgressDialog(null);
    progress.setCancelable(false);
    progress.setMessage("Loading...");
    progress.setTitle("Loading");
    progress.show();
}

protected String doInBackground(String... arg0) {
    return Utils.httpGetFromUrl(arg0[0]);
}

protected void onPostExecute(String result) {
    ArrayList<Person> rlist = Utils.parseJson(result);
    // ArrayAdapter<String> arrayAdapter = new
    // ArrayAdapter<String>(ListActivity.this,
    // android.R.layout.simple_list_item_1);
    ArrayAdapter<Person> adapter = new ClassAdapter(context, rlist);
    rlv.setAdapter(adapter);    
    progress.dismiss();
}   

If you are having a new class then the way you are doing this is wrong. 如果您要上一门新课,那么您这样做的方式是错误的。 if it is inner class of Mainactivity then doing that was right . 如果它是Mainactivity的内部类,那么这样做是对的。

Try the following 尝试以下

//Asuming there is no parameters in the constructor but context other wise 
//delete MainActivity.this

     DataReturn dataReturn = new DataReturn(MainActivity.this);
     dataReturn.execute(your random ip);

尝试:

new DataReturn().execute("your random ip");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM