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

时间:2016-04-03 18:27:12

标签: android android-activity android-asynctask

我使用$lastUpdate = Input::get('last_update'); $userId = Auth::user()->id; // assumes a relationship named 'vendor' $events = EventDetails::whereHas('vendor', function($query) use ($userId) { // $query is query for the EventVendors $query->where('user_id', $userId)->where('is_active', 1) }) ->where(function($query) use ($lastUpdate) { $query->where('created_at', $lastUpdate); $query->orWhere('updated_at', $lastUpdate); }) ->where('is_active', 1) ->with("details_sub") ->with("extras") ->with("chargesDiscounts") ->toSql(); 将数据从服务器加载到列表中,现在我想将此列表发送到主活动。帮帮我怎么做 这是主要活动

AsyncTask

这是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);
}

我尝试了很多次请提供解决方案

1 个答案:

答案 0 :(得分:1)

您可以在MainActivity中实现onPostExecute,或者将AsyncTask类创建为MainActivity中的实习类,如果您不想这样做,那么您可以创建一个用于获取此列表的侦听器。例如,创建一个接口OnDataloadListListener:

public interface OnDataloadListListener{

    void onDataloadListReady(List<String> list);

}

然后在你的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;
    }


}

并使用它:

@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);
}

更新:我会告诉您如何操作,无需查看或测试代码。