1

I read and apply something from this link:How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? but I get an error NullPointerException onPostExecute on the line delegate.processFinish(result); What is the problem in my code? Here is the code:

public class MainActivity extends Activity implements AsyncResponse{
  ProductConnect asyncTask =new ProductConnect();

  public void processFinish(String output){
    //this you will received result fired from async class of onPostExecute(result) method. 
    Log.v(TAG, output); 
  }


 @Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   asyncTask.delegate = this;
   setContentView(R.layout.activity_main);

   Button b = (Button) findViewById(R.id.button1);
   final Intent i=new Intent(MainActivity.this, second.class);
   b.setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View arg0) {

     // TODO Auto-generated method stub
     new ProductConnect().execute(true);
     startActivity(i);
     //startActivity(new Intent(MainActivity.this, second.class));

    }
  });
}


    // START DATABASE CONNECTION        
    class ProductConnect extends AsyncTask<Boolean, String, String> {          
       public AsyncResponse delegate=null;         
       private Activity activity;          
       public void MyAsyncTask(Activity activity) {
            this.activity = activity;
        }


       @Override
       protected String doInBackground(Boolean... params) {
         String result = null;
         StringBuilder sb = new StringBuilder();
           try {
             // http post
         HttpClient httpclient = new DefaultHttpClient();
         HttpGet httppost = new HttpGet("http://192.168.2.245/getProducts.php");
         HttpResponse response = httpclient.execute(httppost);
         if (response.getStatusLine().getStatusCode() != 200) {
           Log.d("MyApp", "Server encountered an error");
         }

         BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF8"));
         sb = new StringBuilder();
         sb.append(reader.readLine() + "\n");
         String line = null;

         while ((line = reader.readLine()) != null) {
           sb.append(line + "\n");
         }

             result = sb.toString();
         Log.d("test", result);
        } catch (Exception e) {
          Log.e("log_tag", "Error converting result " + e.toString());
        }
          return result;
        }

        @Override
        protected void onPostExecute(String result) {
          try {
            JSONArray jArray = new JSONArray(result);
            JSONObject json_data;
            for (int i = 0; i < jArray.length(); i++) {
              json_data = jArray.getJSONObject(i);
                  t = json_data.getString("name");
                  delegate.processFinish(result);
             }

             } catch (JSONException e1) {
             e1.printStackTrace();
             } catch (ParseException e1) {
             e1.printStackTrace();
             }
               super.onPostExecute(result);
        }

         protected void onPreExecute() {
           super.onPreExecute();
           ProgressDialog pd = new ProgressDialog(MainActivity.this);
           pd.setTitle("Lütfen Bekleyiniz");
           pd.setMessage("Authenticating..");
           pd.show();
         }
    }
Community
  • 1
  • 1
elfoz
  • 115
  • 1
  • 8
  • 17

5 Answers5

3

You initialize your variable to null

public AsyncResponse delegate=null;

so naturally it will give NPE when you try to use it. You give it a value in your Activity so you could pass that to the constructor of your AsyncTask and initialize it to that object.

codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • How can i give it a value ? sorry I'm new for this kind of subjects. – elfoz Oct 02 '13 at 14:43
  • "You give it a value in your Activity so you could pass that to the constructor of your AsyncTask and initialize it to that object." But I see you got an answer that somehow fixed it. – codeMagic Oct 02 '13 at 14:51
  • I didn't give a value for delegate object. It works when it is also null. Even so thank you for your advice. – elfoz Oct 02 '13 at 15:13
  • You did give it a value you just don't realize it. Its important to understand *why* things work. – codeMagic Oct 02 '13 at 15:28
1

Your are starting a new AsyncTask in this line:

new ProductConnect().execute(true);

you should execute your asyncTask change that line with this:

asyncTask.execute(true);
invisbo
  • 3,399
  • 1
  • 16
  • 20
0

I think the best way to do this is using interfaces.. Create a listener for this.

[]'s

Igor Morais
  • 645
  • 1
  • 8
  • 13
  • I created an interface by following this link: http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a but I do something wrong. – elfoz Oct 02 '13 at 14:21
0

you can access asynctask() method when creating new object from it. sample:

LoginSyncProvider syncProvider = (LoginSyncProvider) new LoginSyncProvider(){
                                @Override
                                protected void onPostExecute(Void aVoid) {
                                    super.onPostExecute(aVoid);
                                    //TODO write something here
                                    }
                                }
                            }.execute();
vahid karimi
  • 1,263
  • 1
  • 12
  • 6
-1

You've to pass context to that AsyncTask.

Then, on postExecute, cast context to your Activity.

Example:

((MyActivity)context).doSomethingWithResults(resultOfAsyncTask);

Edit:

Your Activity:

public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        new MyAsyncTask(this).execute();
    }

    public void sayHello(String name){
        Log.d("log","hello "+name+"!!!");
    }
}   

Your asynctask:

class MyAsyncTask extends AsyncTask<String,String,String>{
    Context context;
    public AutoPassarImatges(Context cont) {
        super();
                    this.context = cont;
        // TODO Auto-generated constructor stub
    }

    @Override
    protected String doInBackground(String... params) {
        [.......]

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        ((MyActivity)context).sayHello(result);
    }



}
Reinherd
  • 5,476
  • 7
  • 51
  • 88
  • The OP is using an `interface` to use a `callback` to the `Activity`...not trying to call an `Activity` method. – codeMagic Oct 02 '13 at 14:24
  • @codeMagic as the title states: How can i to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?. I gave him a solution he might understand. – Reinherd Oct 02 '13 at 14:25
  • I understand and I didn't downvote. I'm simply saying that there is already a solution set up, the OP simply needs to initialize the variable that is `null` – codeMagic Oct 02 '13 at 14:29
  • When i delegate object set not null, the same error is occured. – elfoz Oct 02 '13 at 14:34