在Android中:如何将OnPostExecute()的结果发送到其他活动?

时间:2013-10-03 08:18:32

标签: java android android-asynctask

我得到了OnPostExecute()的结果到主要活动,但我想在第二个活动中使用这个结果。我阅读并使用Bundle应用了一些东西,但它没有运行。我收到错误NullPointerException导致在第二个活动中没有收到值。这是我的MainActivity(它有一个AsyncResponse接口):

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

//开始数据库连接

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

我该怎么办?

4 个答案:

答案 0 :(得分:3)

AsyncTask.execute()是一个非阻塞调用。您无法将结果设置为Bundle并在execute()之后立即启动Intent。这就是你在第二个Activity中获得NPE的原因,因为sending没有被初始化,所以它是null。

移动代码以在回调中启动包含所需数据的新活动:

  public void processFinish(String output){

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

   }

如果您的数据处理完成,请务必致电delegate.processFinished(String)。所以将它移出for循环。 BTW t只会获得JSONArray中的最后一个“名称”-String。如果你想让它们全部使t成为一个String数组并填充它。

答案 1 :(得分:0)

由于您的变量t已在您的活动中全局声明,因此可以直接使用您在t方法中指定的onPostExecute()值。只需要在按钮点击事件中检查其空值,如下所示:

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

答案 2 :(得分: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);

    }
}

答案 3 :(得分:0)

在有人发布解决方案之前不久,它的工作没有任何错误,但已被删除。这个解决方案是这样的:

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

然后OnPostExecute改变如下:

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

最后,在我的第二个活动中,通过这种方式接收字符串:

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

感谢您之前发布此解决方案的人:)