2013-10-03 22 views
1

我得到了OnPostExecute()對主要活動的結果,但我想在第二個活動中使用此結果。我使用Bundle閱讀和應用了一些東西,但它並沒有運行。我得到錯誤NullPointerException導致沒有收到第二個活動的值。這裏是我的MainActivity(它有一個接口AsyncResponse):在Android中:我如何將OnPostExecute()的結果發送到其他活動?

public class MainActivity extends Activity implements AsyncResponse 
{ 
public String t; 
public Bundle bnd; 
public Intent intent; 
public String sending; 
    private static final String TAG = "MyActivity"; 
    ProductConnect asyncTask =new ProductConnect(); 
    public void processFinish(String output){ 
     sending=output; 
    } 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     asyncTask.delegate = this; 

     setContentView(R.layout.activity_main); 

      Button b = (Button) findViewById(R.id.button1); 

      bnd=new Bundle(); 

     intent=new Intent(MainActivity.this, second.class); 

     b.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       asyncTask.execute(true); 
      bnd.putString("veri", sending); 
      intent.putExtras(bnd); 
      startActivity(intent); 
      } 
     }); 
    } 

// START數據庫連接

class ProductConnect extends AsyncTask<Boolean, String, String> { 

     public AsyncResponse delegate=null; 

     private Activity activity; 

     public void MyAsyncTask(Activity activity) { 
      this.activity = activity; 
     } 

     @Override 
     protected String doInBackground(Boolean... params) { 
      String result = null; 
      StringBuilder sb = new StringBuilder(); 
      try { 

       // http post 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpGet httppost = new HttpGet(
         "http://192.168.2.245/getProducts.php"); 
       HttpResponse response = httpclient.execute(httppost); 
       if (response.getStatusLine().getStatusCode() != 200) { 
        Log.d("MyApp", "Server encountered an error"); 
       } 

       BufferedReader reader = new BufferedReader(
         new InputStreamReader(
           response.getEntity().getContent(), "UTF8")); 
       sb = new StringBuilder(); 
       sb.append(reader.readLine() + "\n"); 
       String line = null; 

       while ((line = reader.readLine()) != null) { 
        sb.append(line + "\n"); 
       } 
       result = sb.toString(); 
       Log.d("test", result); 
      } catch (Exception e) { 
       Log.e("log_tag", "Error converting result " + e.toString()); 
      } 
      return result; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      try { 
       JSONArray jArray = new JSONArray(result); 
       JSONObject json_data; 
       for (int i = 0; i < jArray.length(); i++) { 
        json_data = jArray.getJSONObject(i); 

        t = json_data.getString("name"); 
           delegate.processFinish(t); 
      } 

      } catch (JSONException e1) { 
       e1.printStackTrace(); 
      } catch (ParseException e1) { 
       e1.printStackTrace(); 
      } 
      super.onPostExecute(result); 
     } 

     protected void onPreExecute() { 
       super.onPreExecute(); 
       ProgressDialog pd = new ProgressDialog(MainActivity.this); 
       pd.setTitle("Please wait"); 
       pd.setMessage("Authenticating.."); 
       pd.show(); 
      } 
    } 

這裏是我的第二個活動:

public class second extends ActionBarActivity { 
     public CharSequence mTitle; 
     private static final String TAG = "MyActivity"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.second); 

     Bundle receive=getIntent().getExtras(); 
     String get=receive.getString("veri"); 
      Log.v(TAG, get); 
     } 

我應該做的?

+0

請發佈您的logcat也。 – GrIsHu

+0

processFinish(String output)用於將OnPostExecute的結果獲取到main。我跟着這個鏈接,當我編碼這個:http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a – elfoz

+0

LogCat :java.lang.RuntimeException:無法啓動活動ComponentInfo {com.example.helloandroid/com.example.helloandroid.second}:java.lang.NullPointerException:println需要一條消息 – elfoz

回答

3

AsyncTask.execute()是一個非阻塞的調用。您不能將結果設置爲Bundle,並在execute()後立即啓動一個Intent。這就是爲什麼你在第二個活動中獲得NPE的原因,因爲sending未初始化,所以它爲空。

移動代碼開始一個新的活動,在您的回調所需的數據:

public void processFinish(String output){ 

     bnd.putString("veri", output); 
     intent.putExtras(bnd); 
     startActivity(intent); 

    } 

並確保您撥打delegate.processFinished(String)如果您的數據處理完成。所以把它移出for循環。 BTW t將只獲取JSONArray中的最後一個「名稱」字符串。如果你想讓他們全部使t成爲一個String數組並填充它。

+0

我同意,事情是你的異步甚至沒有做切換活動,所以你沒有任何結果尚未... – Cehm

+0

@Cehm我希望我的編輯更清楚。 –

0

由於您的變量t已在您的活動中全局聲明,因此可以直接使用您在onPostExecute()方法中分配的值t。只要你只需要在你的按鈕單擊事件,如下檢查其空值:

b.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View arg0) { 
     asyncTask.execute(true); 
     if(t != null || t != "") 
      { 
       bnd.putString("veri", t); 
       intent.putExtras(bnd); 
      startActivity(intent); 
     } 
     } 
    }); 
+0

有人在這裏發佈了一個解決方案,它的工作原理,但它被刪除。我上面發佈了這個解決方案 – elfoz

0
// try this 
public class MainActivity extends Activity 
{ 
    public String t; 
    public Bundle bnd; 
    public Intent intent; 
    private static final String TAG = "MyActivity"; 
    ProductConnect asyncTask; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 

     Button b = (Button) findViewById(R.id.button1); 

     bnd=new Bundle(); 

     intent=new Intent(MainActivity.this, second.class); 
     asyncTask = new ProductConnect(new ResultListener() { 
      @Override 
      public void onResultGet(String value) { 
       bnd.putString("veri", value); 
       intent.putExtras(bnd); 
       startActivity(intent); 
      } 
     }); 
     b.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       asyncTask.execute(true); 

      } 
     }); 
    } 

    class ProductConnect extends AsyncTask<Boolean, String, String> { 

     private ResultListener target; 

     public ProductConnect(ResultListener target) { 
      this.target = target; 
     } 

     @Override 
     protected String doInBackground(Boolean... params) { 
      String result = null; 
      StringBuilder sb = new StringBuilder(); 
      try { 

       // http post 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpGet httppost = new HttpGet(
         "http://192.168.2.245/getProducts.php"); 
       HttpResponse response = httpclient.execute(httppost); 
       if (response.getStatusLine().getStatusCode() != 200) { 
        Log.d("MyApp", "Server encountered an error"); 
       } 

       BufferedReader reader = new BufferedReader(
         new InputStreamReader(
           response.getEntity().getContent(), "UTF8")); 
       sb = new StringBuilder(); 
       sb.append(reader.readLine() + "\n"); 
       String line = null; 

       while ((line = reader.readLine()) != null) { 
        sb.append(line + "\n"); 
       } 
       result = sb.toString(); 
       Log.d("test", result); 
      } catch (Exception e) { 
       Log.e("log_tag", "Error converting result " + e.toString()); 
      } 
      return result; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      try { 
       JSONArray jArray = new JSONArray(result); 
       JSONObject json_data; 
       for (int i = 0; i < jArray.length(); i++) { 
        json_data = jArray.getJSONObject(i); 

        t = json_data.getString("name"); 
        target.onResultGet(t); 
       } 

      } catch (JSONException e1) { 
       e1.printStackTrace(); 
      } catch (ParseException e1) { 
       e1.printStackTrace(); 
      } 
      super.onPostExecute(result); 
     } 

     protected void onPreExecute() { 
      super.onPreExecute(); 
      ProgressDialog pd = new ProgressDialog(MainActivity.this); 
      pd.setTitle("Please wait"); 
      pd.setMessage("Authenticating.."); 
      pd.show(); 
     } 
    } 

    interface ResultListener { 

     public void onResultGet(String value); 

    } 
} 
0

前不久有人張貼的解決方案和它的作品沒有任何錯誤,但它已被刪除。該解決方案是這樣的:

public void onClick(View arg0) { 
     asyncTask.execute(true); 
     } 
    }); 
    } 

然後OnPostExecute改變這樣的:

String receivedVal= getIntent().getExtras().getString("veri"); 
    Log.v(TAG, receivedVal); 

謝謝你這樣的人誰:

protected void onPostExecute(String result) { 
     Intent passValue=new Intent(MainActivity.this, second.class); 
     try { 
      JSONArray jArray = new JSONArray(result); 
      JSONObject json_data; 
      for (int i = 0; i < jArray.length(); i++) { 
       json_data = jArray.getJSONObject(i); 

       t = json_data.getString("name"); 
          delegate.processFinish(t); 

      } 
      passValue.putExtra("veri", t); 
      startActivity(passValue); 

     } catch (JSONException e1) { 
      e1.printStackTrace(); 
     } catch (ParseException e1) { 
      e1.printStackTrace(); 
     } 
     super.onPostExecute(result); 
    } 

最後在我的第二次活動通過這種方式得到的字符串不久之前發佈此解決方案:)

相關問題