Android 如何将列表项从AsyncTask获取到主活动?

Android 如何将列表项从AsyncTask获取到主活动?,android,android-activity,android-asynctask,Android,Android Activity,Android Asynctask,我使用AsyncTask将数据从服务器加载到列表,现在我想将此列表发送到主活动。帮我怎么做 这是主要活动 @Override protected void onCreate(Bundle savedInstanceState) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads().detectDiskWrites().detectNetwork

我使用
AsyncTask
将数据从服务器加载到列表,现在我想将此列表发送到主活动。帮我怎么做 这是主要活动

 @Override
protected void onCreate(Bundle savedInstanceState) {
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()

            .detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread

            .penaltyLog().build());
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tx=(TextView)findViewById(R.id.textView);

    ls=(ListView)findViewById(R.id.listView);

    bn=(Button)findViewById(R.id.button);

    new Dataload().execute();


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
这是一个异步任务

class Dataload extends AsyncTask<String,Void,ArrayAdapter> {


    String returnString, s = "";
    String  name;
    int quantity,price;
    ArrayList<String> list = new ArrayList<String>();
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }
    @Override
    protected void onPostExecute(ArrayAdapter adapter) {

        ls.setAdapter(adapter);

    }

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




        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();


        // define the parameter

        postParameters.add(new BasicNameValuePair("h", s));

        String response = null;


        // call executeHttpPost method passing necessary parameters


        try {

            response = CustomHttpClient.executeHttpPost(



                    "http://grclive.16mb.com/select_rum.php",

                    postParameters);


            String result = response.toString();

            try {

                returnString = "";

                JSONArray jArray = new JSONArray(result);

                for (int i = 0; i < jArray.length(); i++) {

                    JSONObject json_data = jArray.getJSONObject(i);

                    name = json_data.getString("r_name");
                    quantity=json_data.getInt("r_quantity");
                    price=json_data.getInt("r_price");
                    list1.add(name + "     " + quantity + " L" + "     " + price + " ₹");






                }


            } catch (JSONException e) {

                Log.e("log_tag", "Error parsing data " + e.toString());

            }



        } catch (Exception e) {

            Log.e("log_tag", "Error in http connection!!" + e.toString());

        }


        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(getApplicationContext(),R.layout.textfield, list1);

        return adapter;
    }


}
类数据加载扩展了异步任务{
字符串返回字符串,s=“”;
字符串名;
整数数量、价格;
ArrayList=新建ArrayList();
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的void onPostExecute(ArrayAdapter适配器){
ls.setAdapter(适配器);
}
@凌驾
受保护的阵列适配器doInBackground(字符串…参数){
ArrayList后参数=新的ArrayList();
//定义参数
后参数。添加(新的BasicNameValuePair(“h”,s));
字符串响应=null;
//调用executehttpost方法传递必要的参数
试一试{
响应=CustomHttpClient.executeHttpPost(
"http://grclive.16mb.com/select_rum.php",
后参数);
字符串结果=response.toString();
试一试{
returnString=“”;
JSONArray jArray=新JSONArray(结果);
for(int i=0;i

我尝试了很多次,请给出一个解决方案,您可以在MainActivity中实现onPostExecute,或者在MainActivity中创建AsyncTask类作为intern类,如果您不想这样做,那么您可以创建一个侦听器来获取此列表。例如,创建一个接口OnDataloadListListener:

public interface OnDataloadListListener{

    void onDataloadListReady(List<String> list);

}
OnDataloadListListener的公共接口{ 作废onDataloadListReady(列表); }
然后在Dataload类中使用它。在Dataload构造函数中传递OnDataloadListListener实例。在onPostExecute中创建适配器,而不是在doInBackground中创建适配器:

class Dataload extends AsyncTask<String,Void,List<String>> {

    public Dataload(OnDataloadListListener onDataloadListListener){
        this.onDataloadListListener = onDataloadListListener;
    }

    String returnString, s = "";
    String  name;
    int quantity,price;
    ArrayList<String> list = new ArrayList<String>();
    OnDataloadListListener onDataloadListListener;

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

    }
    @Override
    protected void onPostExecute(List<String> list) {

    if(onDataloadListListener != null){
        onDataloadListListener.onDataloadListReady(list);
    }
        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(getApplicationContext(),R.layout.textfield, list);

        ls.setAdapter(adapter);


    }

    @Override
    protected List<String> doInBackground(String... params) {




        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();


        // define the parameter

        postParameters.add(new BasicNameValuePair("h", s));

        String response = null;


        // call executeHttpPost method passing necessary parameters


        try {

            response = CustomHttpClient.executeHttpPost(



                    "http://grclive.16mb.com/select_rum.php",

                    postParameters);


            String result = response.toString();

            try {

                returnString = "";

                JSONArray jArray = new JSONArray(result);

                for (int i = 0; i < jArray.length(); i++) {

                    JSONObject json_data = jArray.getJSONObject(i);

                    name = json_data.getString("r_name");
                    quantity=json_data.getInt("r_quantity");
                    price=json_data.getInt("r_price");
                    list1.add(name + "     " + quantity + " L" + "     " + price + " ₹");






                }


            } catch (JSONException e) {

                Log.e("log_tag", "Error parsing data " + e.toString());

            }



        } catch (Exception e) {

            Log.e("log_tag", "Error in http connection!!" + e.toString());

        }



        return list1;
    }


}
类数据加载扩展了异步任务{
公共数据加载(OnDataloadListListener OnDataloadListListener){
this.onDataloadListListener=onDataloadListListener;
}
字符串返回字符串,s=“”;
字符串名;
整数数量、价格;
ArrayList=新建ArrayList();
OnDataloadListListener OnDataloadListListener;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的void onPostExecute(列表){
如果(onDataloadListListener!=null){
onDataloadListListener.onDataloadListReady(列表);
}
阵列适配器=
新的ArrayAdapter(getApplicationContext(),R.layout.textfield,list);
ls.setAdapter(适配器);
}
@凌驾
受保护列表doInBackground(字符串…参数){
ArrayList后参数=新的ArrayList();
//定义参数
后参数。添加(新的BasicNameValuePair(“h”,s));
字符串响应=null;
//调用executehttpost方法传递必要的参数
试一试{
响应=CustomHttpClient.executeHttpPost(
"http://grclive.16mb.com/select_rum.php",
后参数);
字符串结果=response.toString();
试一试{
returnString=“”;
JSONArray jArray=新JSONArray(结果);
for(int i=0;i
并通过以下方式使用它:

@Override
protected void onCreate(Bundle savedInstanceState) {
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()

            .detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread

            .penaltyLog().build());
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tx=(TextView)findViewById(R.id.textView);

    ls=(ListView)findViewById(R.id.listView);

    bn=(Button)findViewById(R.id.button);

    new Dataload(
        new OnDataloadListListener(){
            onDataloadListReady(List<String> list){
                //You have your list here
            }
        }

    ).execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
@覆盖
创建时受保护的void(Bundle savedInstanceState){
StrictMode.setThreadPolicy(新的StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()//StrictMode最常用于捕获应用程序主线程上的意外磁盘或网络访问
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tx=(TextView)findViewById(R.id.TextView);
ls=(ListView)findViewById(R.id.ListView);
bn=(按钮)findviewbyd(R.id.Button);
新数据加载(
新OnDataloadListListener(){
onDataloadListReady(列表){
//这里有你的名单
}
}
).execute();
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(右菜单菜单菜单主菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。