2016-04-03 65 views
1

我使用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); 
} 

這是的AsyncTask

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


} 

我試過很多次,請給出一個解決方案

+0

Asynctask和活動在不同的文件? –

+0

@Vivek沒有相同的文件 –

+1

然後有什麼需要返回,只是使參數全局,你可以在任何地方訪問 –

回答

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

更新:我給你你如何能做到這一點的想法,沒有審查或測試碼。

+0

我的assync任務在主要活動內 –

+0

好的,所以你可以在onPostExecute中獲得它,然後在UI線程上運行這個方法。 – aramburu

+0

如何將列表返回到assync任務類的主要活動? –

相關問題