1

I got the result of OnPostExecute() to main activity but I want to use this result in second activity. I read and applied something with using Bundle but it doesn't run. I got error NullPointerException cause of not receiving the value in the second activity. Here is my MainActivity (It has an interface 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);
            }
        });
    }

// START DATABASE CONNECTION

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

Here is My Second Activity:

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

What should i do?

GrIsHu
  • 29,068
  • 10
  • 64
  • 102
elfoz
  • 115
  • 1
  • 8
  • 17
  • Please post your logcat also. – GrIsHu Oct 03 '13 at 08:28
  • processFinish(String output) is for getting result of OnPostExecute to main. I followed this link when i coded this: http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a – elfoz Oct 03 '13 at 08:34
  • LogCat: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloandroid/com.example.helloandroid.second}: java.lang.NullPointerException: println needs a message – elfoz Oct 03 '13 at 08:35
  • Check out my answer which may help you. – GrIsHu Oct 03 '13 at 08:37
  • all what you need is how to use intents in android, here is a tutorial about how to use them and transfer data between your activities : http://www.android-ios-tutorials.com/android/android-intent-tutorial – Houcine Oct 03 '13 at 08:40
  • Thank you for tutorial @Houcine – elfoz Oct 03 '13 at 09:04

4 Answers4

3

AsyncTask.execute() is a non-blocking call. You can't set the result to the Bundle and start an Intent immediatly after execute(). That's why you are getting a NPE in your second Activity because sending isn't initialized, so it's null.

Move the code to start a new Activity with the desired data in your callback:

  public void processFinish(String output){

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

   }

And make sure you call delegate.processFinished(String) if your data processing is finished. So move it out of the for loop. BTW t will only get the last "name"-String in the JSONArray. If you wanna get them all make t a String array and fill it.

Steve Benett
  • 12,843
  • 7
  • 59
  • 79
  • I agree, thing is your async isnt even done when switching activity so you dont have any results yet... – Cehm Oct 03 '13 at 08:32
0

As your variable t is globally declared in your activity so can directly use the value of t which you are assigning in your onPostExecute() method. Just you need to check for its null value only in your button click event as below :

   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);
         }
      }
     });
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
  • Someone posted a solution here and it works but it was deleted. I posted this solution above. – elfoz Oct 03 '13 at 09:07
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);

    }
}
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
0

Shortly before someone posted a solution and it works without any errors but it was deleted. This solution is by this way:

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

Then OnPostExecute changed like this:

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

Lastly in my second activity receive the string by this way:

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

Thank you someone who posted this solution shortly before :)

GrIsHu
  • 29,068
  • 10
  • 64
  • 102
elfoz
  • 115
  • 1
  • 8
  • 17