繁体   English   中英

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

[英]In Android: How can i send the result of from OnPostExecute() to other activity?

我得到了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);
      }

我该怎么办?

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

移动代码以在回调中使用所需数据启动新活动:

  public void processFinish(String output){

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

   }

如果数据处理完成,请确保调用delegate.processFinished(String) 所以将它移出for循环。 BTW t只会获得JSONArray中的最后一个“名称”-String。 如果你想获得他们都做t的String数组和填充它。

由于您的变量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); } } }); 
// 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);

    }
}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM