0

I am new to android, I am getting data in JSON format in AsyncTask and I have some TextView's and RadioButton's. The data which I am getting in AsyncTask I want the TextView to show the same data. In doInBackground() method I am getting data properly but when i am accessing the data in postExecute() I am not gettting data.

Here is my code. Please Help me..

 String que,ans1, ans2, ans3, ans4, ans5, correct_ans, explainat;

In AsyncTask

   private class NetCheck extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        nDialog = new ProgressDialog(SectionTestActivity.this);
        nDialog.setMessage("Loading..");
        nDialog.setTitle("Please Wait");
        nDialog.setIndeterminate(false);
        nDialog.setCancelable(true);
        nDialog.show();
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Log.e("Post exec calleld", "dfds");
        nDialog.dismiss();

        Log.e("Post Exeec Ques",""+que);

        sectionName.setText("" + section_category);
        question.setText("" + que.toString());
        rb_1.setText("" + ans1.toString());
        rb_2.setText("" + ans2);
        rb_3.setText("" + ans3);
        rb_4.setText("" + ans4);
        rb_5.setText("" + ans5);

    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        try {

            cd = new ConnectionDetector(getApplicationContext());

            if (!cd.isConnectingToInternet()) {
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(
                        new Runnable() {
                            @Override
                            public void run() {
                                AlertDialog alertDialog = new AlertDialog.Builder(
                                        SectionTestActivity.this).create();
                                alertDialog.setMessage("Error connecting to internet.");
                                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                });

                                alertDialog.show();
                            }
                        }
                );
            }
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpRequest = new HttpPost(

                    "http://url");
            httpRequest.setHeader("Content-Type", "application/json");
            SharedPreferences preff = getSharedPreferences(
                    "MyPref", MODE_PRIVATE);
            String userid = preff.getString("id", null);
            Log.e("Student id", "" + userid);


            JSONObject json = new JSONObject();
            json.put("section_id", section_id);
            json.put("userid", userid);


            Log.e("JSON Object", json.toString());

            StringEntity se = new StringEntity(json.toString());

            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");

            httpRequest.setEntity(se);
            HttpResponse httpRes = httpClient.execute(httpRequest);

            java.io.InputStream inputStream = httpRes.getEntity()
                    .getContent();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            inputStream.close();
            strServerResponse = sb.toString();
            Log.e("Server Response", "" + strServerResponse.toString());
            if (strServerResponse != null) {
                try {
                    Log.e("if block execute", "df");

                    JSONArray arr = new JSONArray(strServerResponse);
                    JSONObject jsonObj = arr.getJSONObject(0);
                    pojo = new Pojo();
                    for (int i = 0; i < arr.length(); i++) {

                        JSONObject jobj2 = arr.getJSONObject(i);
                        que = jobj2.optString("title").trim();
                        qid = jobj2.optString("id").trim();
                        //qid=questionid;
                        ans1 = jobj2.optString("ans_a");
                        ans2 = jobj2.optString("ans_b");
                        ans3 = jobj2.optString("ans_c");
                        ans4 = jobj2.optString("ans_d");
                        ans5 = jobj2.optString("ans_e");
                        correct_ans = jobj2.optString("right_ans");
                        explainat = jobj2.optString("explanation");

                        Log .e("Que", ""+que);
                        Log .e("QueID", ""+qid);
                        Log .e("Ans2", ""+ans2);
                        Log .e("Ans3", ""+ans3);
                        Log .e("Ans4", ""+ans4);
                        Log .e("Ans5", ""+ans5);
                        Log .e("Ans1", ""+ans1);
                        Log .e("Correct anss", ""+correct_ans);
                        Log .e("Explll", ""+explainat);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler",
                        "Couldn't get any data from the url");
            }

        } catch (UnsupportedEncodingException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (ClientProtocolException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;

    }

}

This is JSON

   [{"id":"1","title":"Rahul bought a bike for Rs 24000 and sold it for 28000. What is his profit?","description":"","ans_a":"16.66%","ans_b":"20%","ans_c":"25%","ans_d":"30%","ans_e":"","right_ans":"A","explanation":"Sdcsdf sdf skdfj lsdfjlsdfj sdkjfn ;fgad"},{"rowid":93}]

I am not getting data here.

USER9561
  • 1,084
  • 3
  • 15
  • 41

2 Answers2

1

Hi if you want to get result in postexecute method then change the return type of doinBackground method to String,

Here am adding the skeleton example..

private class NetCheck extends AsyncTask<Void, Void,String>
    {

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

        @Override
        protected String doInBackground(Void... params) {
            return "your result string";
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }
Nandhu
  • 68
  • 11
0

Thats because you are looping to array and at second object you didnt have Que and other logged params hence they return empty string "" from optString if you have to get data from first object change JSONObject jobj2 = arr.getJSONObject(0); and not the for loop

Abhijeet
  • 392
  • 2
  • 13