从AsynchTask的doInBackround()获取JSONObject并传递给主类

时间:2014-01-07 04:08:00

标签: android json android-asynctask jsonobject

我正在尝试在Async任务之外使用json对象,但我的类无法识别它。

如何将JSONObject传递给异步任务的外部?

我唯一能找到的就是尝试使用onProgressUpdate()传递对象,但我尝试实现并且对象会出现空白:(。

任何帮助将不胜感激,谢谢。

这是我的班级:

public class NewHomepage extends Activity {

    public static String url = "http://www.alkouri.com/android/SQL.php?username=";
    public static String usernamefromlogin;
    public static TextView errorchecking; 
    public static JSONArray user = null;

    //JSON Node Names 
    public String TAG_USER = "users";
    public String TAG_FIRST = "first";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reshomepage);
        //get data from previous screen
          Intent intent = getIntent();
          getIntent().getExtras();

          //convert intent (intent) to string called "usernamefromlogin"     
         //error checking in log cat to see value of "usernamefromlogin"      
          usernamefromlogin = intent.getExtras().getString("username2"); 
           Log.d("log usernamefromlogin", usernamefromlogin);

          //take the string "url" and add string "usernamefromlogin" after it       
         //error checking in log cat to see value of url5
          String url5 = url.concat(usernamefromlogin);                           
            Log.d("log url5", url5);

            //start asynch task
         class PostTask2 extends AsyncTask<String, String, String> {
               @Override
               protected void onPreExecute() {
                  super.onPreExecute();

               }//end PreExecute

               @Override
               protected String doInBackground(String... params) {
                //pass url from outside class to inside this class   
                String url5 = params[0];

                //Creating new JSON Parser
                JSONParser jParser = new JSONParser();

                // Getting JSON from URL
                JSONObject json = jParser.getJSONFromUrl(url5);

                return null;

               }//end doInBackground

             protected void onProgressUpdate(String... values) {
                  super.onProgressUpdate(values);
              }//end onProgressUpdate

               @Override
               protected void onPostExecute(String result) {
               super.onPostExecute(result);

               }//end onPostExecute
               }//end Async task

        //execute the Async task
        new PostTask2().execute(url5);

    }//end oncreate

    @Override
    public void onBackPressed() {
        // do nothing on back press
    }
 }//end class

3 个答案:

答案 0 :(得分:0)

您需要将AsyncTask calss放在onCreate方法之外,并从onCreate方法中调用它。

P.S。 但是,如在评论中一样,发布您的json响应并告诉我们您要从响应中解析的内容。最重要的是,您需要使用HTTP或Rest Client来查询服务器并获得响应。

修改

要了解如何向服务器发出请求,请查看此tutorial,或者您也可以查看此tutorial

答案 1 :(得分:0)

您必须从onCreate方法中提取asynctask并将其作为嵌套类插入NewHomepage。

现在,您可以从doInBackground()返回一个JSONObject,如下面的代码所示。注意AsncTask。

很高兴学习关于活动生命周期和内存泄漏的一些事情(很难)(我很认真,尝试一下,仅仅是为了练习)。对于真实的应用程序,我强烈推荐像Volley这样的Rest客户端库。

    public class NewHomepage extends Activity {

        // ... your activity code


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            new PostTask2().execute(url5);
        }

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

                    @Override
                    protected void onPreExecute() {
                        super.onPreExecute();

                    }//end PreExecute

                    @Override
                    protected String doInBackground(String... params) {
                        //pass url from outside class to inside this class
                        String url5 = params[0];

                        //Creating new JSON Parser
                        JSONParser jParser = new JSONParser();

                        // Getting JSON from URL
                        JSONObject json = jParser.getJSONFromUrl(url5);

                        return json;

                    }//end doInBackground

                    protected void onProgressUpdate(String... values) {
                        super.onProgressUpdate(values);
                    }//end onProgressUpdate

                    @Override
                    protected void onPostExecute(JSONObject result) {
                        // HERE, this is running on the main thread.
                        // You can do whatever you need to do with your JSONObject.
                        // Maybe call setData(result) but be careful, the user might have left this activty already!
                        // And the View might have been already destroyed, so watchout for null-pointer-exceptions
                    }//end onPostExecute
                }
    }

答案 2 :(得分:0)

您可以在JSONObject中退回onPostExecute,如下所示:

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

          ..............................

           @Override
           protected String doInBackground(String... params) {
            //pass url from outside class to inside this class   
            String url5 = params[0];

            //Creating new JSON Parser
            JSONParser jParser = new JSONParser();

            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url5);

            return json;

           }//end doInBackground

         protected void onProgressUpdate(String... values) {
              super.onProgressUpdate(values);
          }//end onProgressUpdate

           @Override
           protected void onPostExecute(JSONObject result) {
           super.onPostExecute(result);

           }//end onPostExecute
           }//end Async task