2013-02-03 10 views
6

Sto tentando di restituire un array dal mio AsyncTask alla mia attività mentre sto cercando di creare un ListView da quell'array. Sfortunatamente, il programma limita l'errore perché non mi permette di restituire un array. I miei codici sono le seguenti:Restituire un array [] da AsyncTask all'attività principale

MainMenu Classe:

public class MainMenu extends Activity { 
String username; 
public String[] returnValue; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main_menu); 
    username ="user1"; 

if (checkInternetConnection()) { 

    try { 
     MainAsyncTask mat = new MainAsyncTask(MainMenu.this); 
     mat.execute(username); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} else { 
    Toast.makeText(getApplicationContext(),"No internet connection. Please try again later",Toast.LENGTH_SHORT).show(); 
    } 
} 

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

private boolean checkInternetConnection() { 
    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 

    if (conMgr.getActiveNetworkInfo() != null 
      && conMgr.getActiveNetworkInfo().isAvailable() 
      && conMgr.getActiveNetworkInfo().isConnected()) { 
     return true; 
    } else { 
     return false; 
    } 
}} 

MainAsyncTask:

public class MainAsyncTask extends AsyncTask<String, Void, Integer> { 
    private MainMenu main; 
    private String responseText, http; 
    private Ipaddress ipaddr = new Ipaddress(http); 
    private Context context; 

    public MainAsyncTask(MainMenu main) { 
     this.main = main; 
    } 

    protected Integer doInBackground(String... arg0) { 
     int responseCode = 0; 
     try { 
      HttpClient client = new HttpClient(main.getApplicationContext()); 
      Log.e("SE3", ipaddr.getIpAddress()); 
      HttpPost httpPost = new HttpPost(ipaddr.getIpAddress() 
        + "/MainServlet"); 

      List<NameValuePair> nvp = new ArrayList<NameValuePair>(); 

      JSONObject json = new JSONObject(); 
      json.put("username", arg0[0]); 

      Log.e("SE3", arg0[0]); 

      nvp.add(new BasicNameValuePair("data", json.toString())); 
      httpPost.setEntity(new UrlEncodedFormEntity(nvp)); 

      HttpResponse response = client.execute(httpPost); 

      if (response != null) { 
       if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
        try { 
         BufferedReader reader = new BufferedReader(
           new InputStreamReader(response.getEntity() 
             .getContent())); 
         StringBuilder sb = new StringBuilder(); 
         String line; 
         while ((line = reader.readLine()) != null) { 
          sb.append(line); 
         } 
         responseText = sb.toString(); 
        } catch (IOException e) { 
         Log.e("SE3", "IO Exception in reading from stream."); 
         responseText = "Error"; 
        } 
       } else { 
        responseText = "Error"; 
       } 
      } else { 
       responseText = "Response is null"; 
      } 
     } catch (Exception e) { 
      responseCode = 408; 
      responseText = "Response is null"; 
      e.printStackTrace(); 
     } 
     return responseCode; 
    } 

    protected void onPostExecute(Integer result) { 
     if (result == 408 || responseText.equals("Error") 
       || responseText.equals("Response is null")) { 
      Toast.makeText(main.getApplicationContext(), 
        "An error has occured, please try again later.", 
        Toast.LENGTH_SHORT).show(); 
     } else { 
      JSONObject jObj; 
      try { 
       jObj = new JSONObject(responseText); 
       String folderString = jObj.getString("folder"); 

       String [] folders = folderString.split(";");  
       //I need to return folders back to MainMenu Activity 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

mia domanda è come dovrei modificare in modo che io sono in grado di leggere il mio Array indietro sulla mia l'attività con le mie connessioni rimane intatta.

risposta

3

vorrei raccomandare che si dichiara MainAsyncTask in questo modo:

public class MainAsyncTask extends AsyncTask<String, Void, String[]> { 

Quindi modificare doInBackground di fare tutto il processo che si sta ora facendo a onPostExecute (ad eccezione della parte Toast) e farlo tornare il String[] (o null se c'è un errore). È possibile memorizzare il codice risultato in una variabile di istanza di MainAsyncTask e restituire null in caso di errore. Quindi onPostExecute ha accesso alle stesse informazioni che ha con il tuo codice corrente. Infine, se non ci sono errori, basta chiamare un metodo nell'attività principale da onPostExecute per eseguire gli aggiornamenti dell'interfaccia utente, passandogli il risultato String[].

Problemi correlati