2

I want to access some values (test1,test2,test3,topic1) which are being retrieved from the database successfully and are displayed in the LOGCAT too inside the Postexecute. But when I attempt to call them outside the PostAsync,it return me NULL. What can I do to achieve the actual values of these variables outside PostAsync

modify_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

              String evtdt = eventdate.getText().toString();
                      String evtloc = item;
                      String orgnm = orgname2.getText().toString();

                      new PostAsync().execute(evtdt,evtloc,orgnm);

                Log.d("test1outside",test1);//Showing NULL
                Log.d("test2outside",test2);//Showing NULL
                Log.d("test3outside",test3);//Showing NULL
                Log.d("Topic1outside",Topic1);//Showing NULL

            }
        }
    });
}


class PostAsync extends AsyncTask<String, String, JSONObject> {

    JSONParser jsonParser = new JSONParser();

    private ProgressDialog pDialog;

    private static final String LOGIN_URL = "http://10.0.3.2/modify_visit_details.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";


    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(modify_visit_details.this);

    }

    @Override
    protected JSONObject doInBackground(String... args) {

        try {

            HashMap<String, String> params = new HashMap<>();
            params.put("event_date", args[0]);
            params.put("event_location", args[1]);
            params.put("organisation_name", args[2]);

            Log.d("request", "starting");

            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "POST", params);

            if (json != null) {
                Log.d("JSON result",json.toString());
                return json;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(JSONObject json) {

        int success = 0;
        String message = "";

        test1 = eventdate.getText().toString();
        test2 = item;
        test3 = orgname2.getText().toString();

        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }


        else if (json != null) {
            {

                JSONArray data= null;
                try {
                    data = json.getJSONArray("details");
                    JSONObject obj=data.getJSONObject(0);
                    Topic1=obj.getString("topic1");

                    Log.d("test1",test1);//Printing all correctly in LOG
                    Log.d("test2",test2);
                    Log.d("test3",test3);
                    Log.d("Topic1",Topic1);


                } catch (JSONException e) {
                    e.printStackTrace();
                }



            }


        }
        else {
            Toast toast = Toast.makeText(
                    modify_visit_details.this,
                    "json null",
                    Toast.LENGTH_LONG
            );
            ViewGroup group = (ViewGroup) toast.getView();
            TextView messageTextView = (TextView) group.getChildAt(0);
            messageTextView.setTextSize(20);
            messageTextView.setTypeface(Typeface.SERIF);
            toast.show();

            if (success == 1) {
                Log.d("Success", message);
            } else {
                Log.d("Failure", message);
            }
        }
    }

}

LOGCAT

somya.client_feedback_application E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                               Process: com.example.somya.client_feedback_application, PID: 17405
                                                                                                      java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
                                                                                                           at com.example.somya.client_feedback_application.modify_visit_details$1.onClick(modify_visit_details.java:96)
                                                                                                           at android.view.View.performClick(View.java:4780)
                                                                                                           at android.view.View$PerformClick.run(View.java:19866)
                                                                                                           at android.os.Handler.handleCallback(Handler.java:739)
                                                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                                           at android.os.Looper.loop(Looper.java:135)
                                                                                                           at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                                                           at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
        06-29 09:11:36.211 14445-14462/system_process W/ActivityManager:   Force finishing activity 1 com.example.somya.client_feedback_application/.modify_visit_details
        06-29 09:11:36.247 14144-14144/? E/EGL_emulation: tid 14144: eglCreateSyncKHR(1209): error 0x3004 (EGL_BAD_ATTRIBUTE)
        06-29 09:11:36.289 17405-17441/com.example.somya.client_feedback_application D/JSON Parser: result: {"details":[{"event_date":"2016-06-08","event_location":"Boeblingen","organisation_name":"hcl","topic1":"Welcome,Orientation and IBM Client Center Walk Through"}]}
Juan Cruz Soler
  • 8,172
  • 5
  • 41
  • 44
Somya Arora
  • 87
  • 11

2 Answers2

1

When you are using AsyncTask:

You are creating a thread separately from UI thread.

So, after this code:

new PostAsync().execute(evtdt,evtloc,orgnm);

You will have 2 separate threads (Ui thread, Your asynctask).

As, your main UI thread is faster than your AsyncTask execution, Your variables of course, are NULL.

This log will will be displayed as NULL:

 Log.d("test1outside",test1);//Showing NULL
 Log.d("test2outside",test2);//Showing NULL
 Log.d("test3outside",test3);//Showing NULL
 Log.d("Topic1outside",Topic1);//Showing NULL

In conclusion, If you would like to see your variables, put your logs in

protected void onPostExecute(JSONObject json)
uelordi
  • 2,189
  • 3
  • 21
  • 36
  • those logs are already there in onPostExecute and as per OP, it is correct – AADProgramming Jun 29 '16 at 14:18
  • Ok, so the defining interfaces could be the solution of the problem, as the aforementioned comment says, http://stackoverflow.com/a/9963705/2995941 – uelordi Jun 29 '16 at 14:23
  • @uelordi You are absolutely correct.But what if I want to access the values outside onPostExecute,the real values not the null. – Somya Arora Jun 29 '16 at 14:24
  • @somyaArora, you can copy the values in global auxiliar variables to access or have a flag to indicate if are ready. It is not a good idea to access to variables from other threads directly without wait to be ready because its a undefined behavoir. – vgonisanz Jul 01 '16 at 07:26
0

You can't just access those values because those are retrived from database some time later. You can store other Runnable and run it in postExecute()

Alex Shutov
  • 3,217
  • 2
  • 13
  • 11