2

Im trying to pass an object from doInBackground to OnPostExecute but failed. I have read similar topics and find them not relevant. (Maybe im not that experienced enough) I'm new to android would like some pointers. I will paste relevant codes instead of everything for easier readability.

Main Activity

public void processFinish(Question q) {
    TextView tview;
    tview = (TextView)findViewById(R.id.textView1);
    tview.setText(q.getQuestion());
}

AsyncTask (Q is an object)

public class getQus extends AsyncTask<String,Void,Question> {
public AsyncResponse delegate;
@Override
protected Question doInBackground(String... params) {
    String range = "1";
    // TODO Auto-generated method stub
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("range",range));
    int q_id = 0;
    String result=null;
    String q_qus =" ";
    String result2 = " ";

    Question q = new Question();

     InputStream is = null;
        try {

              HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://192.168.1.6/fyp/qus.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }
        //convert response to string
        try{

            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();

                result2=sb.toString();
        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }
         System.out.println("HEllo");
        //parse json data
        try{
                JSONArray jArray = new JSONArray(result2);
                for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        Log.i("log_tag","id: "+json_data.getInt("q_id")+
                                ", qus: "+json_data.getString("q_qus")
                        );
                        q.setQid(json_data.getInt("q_id"));
                        q.setQuestion(json_data.getString("q_qus"));
                        return q;
                }

        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }
        return q;

}
protected void onPostExecute(Question q) {
    System.out.println("AT ONPOSTEXECUTE");
    System.out.println(q.getQuestion());
    delegate.processFinish(q);
}

}

Findings: I am able to see my log.i results in my console only. OnPostExecute does not fire at all.

Any Kind Help Or Suggestions would be deeply appreciated. Thank you very much!

Gene
  • 2,178
  • 3
  • 30
  • 50

1 Answers1

2

Change

 extends AsyncTask<String,Void,Object> 

to

 extends AsyncTask<String,Void,Question> 

the third generic parameter is the Result. From the doc

Result, the type of the result of the background computation.

For the NPE:

public class getQus extends AsyncTask<String,Void,Question> {
public AsyncResponse delegate;
   public getQus(AsyncResponse d) {
       delegate = d;
   }
   // other code
}

and if your activity is implementing that interface you simply do:

new getQus(ActivityName.this).execute();
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • can you post the whole AsyncTask? – Blackbelt Dec 19 '14 at 15:12
  • Here you go ! @Blackbelt Thanks! – Gene Dec 19 '14 at 15:22
  • Im using http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a answer for the passing of results from onpostexecute to main activity. – Gene Dec 19 '14 at 15:27
  • `delegate` is null. You never initialize it. Who is the delegate? Take a look to my answer here:http://stackoverflow.com/questions/16752073/how-do-i-return-a-boolean-from-asynctask – Blackbelt Dec 19 '14 at 15:28
  • What do you mean by that bro? I did initialise it on the top, changing to public AsyncResponse delegate = null; doesnt work either. – Gene Dec 19 '14 at 15:32
  • is AsyncResponse an interface? – Blackbelt Dec 19 '14 at 15:32
  • Hi Yes! this is the following codes for the interface.. public interface AsyncResponse { void processFinish(Question q); } – Gene Dec 19 '14 at 15:35
  • who is implementing that interface? – Blackbelt Dec 19 '14 at 15:35
  • Then create a constructor in the async task, and pass the activity as parameter. Assign the parameter to the delegate – Blackbelt Dec 19 '14 at 15:43
  • What do you mean by that? Im kinda confused right now. – Gene Dec 19 '14 at 15:48
  • Thanks for all your help blackbelt. I will try to solve and if really cant, will post an separate thread. Kinda unfair to you. Thank you very much! – Gene Dec 19 '14 at 15:57