簡體   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