如何将数据从asynctask类返回到oncreate方法

时间:2016-06-29 13:57:30

标签: android

我想访问正在从数据库中成功检索的一些值(test1,test2,test3,topic1),并在Postexecute中也显示在LOGCAT中。 但是当我尝试在PostAsync之外调用它们时,它会返回NULL。 我可以做些什么来实现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"}]}

2 个答案:

答案 0 :(得分:1)

使用AsyncTask时:

您正在与UI线程分开创建一个线程。

所以,在这段代码之后:

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

你将有2个独立的线程(Ui线程,你的asynctask)。

因为,你的主UI线程比AsyncTask执行速度快,你的变量当然是NULL。

此日志将显示为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

总之,如果您想查看变量,请将日志放入

protected void onPostExecute(JSONObject json)

答案 1 :(得分:0)

您无法访问这些值,因为这些值会在一段时间后从数据库中恢复。您可以存储其他Runnable并在postExecute()

中运行它