2016-04-03 7 views
1

Ich verwende AsyncTask, um Daten vom Server zu einer Liste zu laden, und jetzt möchte ich diese Liste an die Hauptaktivität senden. Dies ist HauptaktivitätWie bekomme ich Listenelemente von der AsyncTask zur Hauptaktivität?

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

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


} 

Ich habe versucht, so viele Male, helfen Sie mir, wie Sie dieses zu tun geben Sie bitte eine Lösung

+0

Ist asynctask und Aktivität in verschiedenen Dateien? –

+0

@Vivek keine gleiche Datei –

+1

Dann was ist der Rückkehr, nur diesen Parameter global gemacht und Sie können überall zugreifen –

Antwort

1

Sie können OnPostExecute in Ihrem MainActivity implementieren oder erstellen Die AsyncTask-Klasse als interne Klasse innerhalb von MainActivity. Wenn Sie dies nicht tun möchten, können Sie einen Listener zum Abrufen dieser Liste erstellen. Zum Beispiel einer Schnittstelle OnDataloadListListener erstellen:

public interface OnDataloadListListener{ 

    void onDataloadListReady(List<String> list); 

} 

Und es dann in Ihrer DATALOAD- Klasse. Übergeben Sie im Dataload-Konstruktor eine OnDataloadListListener-Instanz. Erstellen Sie den Adapter in OnPostExecute statt es in doInBackground tun:

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


} 

und verwenden Sie es nach:

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

Update: Ich gebe Ihnen eine Idee, wie Sie es tun können, ohne Überprüfung oder testen Sie die Code.

+0

meine assync Aufgabe ist innerhalb der Hauptaktivität –

+0

Ok, so können Sie die Liste erhalten, sobald Sie es in onPostExecute erhalten, läuft diese Methode auf UI-Thread. – aramburu

+0

Wie kann ich die Liste aus assync task class ??? –

Verwandte Themen