2013-10-03 25 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); 
    } 

最后在我的第二次活动通过这种方式得到的字符串不久之前发布此解决方案:)

相关问题