我怎样才能将OnPostExecute()的结果导入主活动,因为AsyncTask是一个单独的类?

时间:2013-10-02 14:12:46

标签: java android android-asynctask

我从这个链接中读取并应用了一些内容:How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?但是我在行delegate.processFinish(result)上遇到错误NullPointerException onPostExecute;我的代码有什么问题?这是代码:

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();
         }
    }

5 个答案:

答案 0 :(得分:3)

您将变量初始化为null

public AsyncResponse delegate=null;

当你尝试使用它时,它会自然地给出NPE。您可以在Activity中为其指定一个值,以便将其传递给AsyncTask的构造函数并将其初始化为该对象。

答案 1 :(得分:1)

您正在此行中开始新的AsyncTask:

new ProductConnect().execute(true);

你应该用这个来执行你的asyncTask更改:

asyncTask.execute(true);

答案 2 :(得分:0)

我认为最好的方法是使用接口..为此创建一个监听器。

[]的

答案 3 :(得分:0)

从中创建新对象时可以访问asynctask()方法。 样品:

LoginSyncProvider syncProvider = (LoginSyncProvider) new LoginSyncProvider(){
                                @Override
                                protected void onPostExecute(Void aVoid) {
                                    super.onPostExecute(aVoid);
                                    //TODO write something here
                                    }
                                }
                            }.execute();

答案 4 :(得分:-1)

您必须将上下文传递给AsyncTask。

然后,在postExecute上,将上下文转换为您的Activity。

示例:

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

编辑:

您的活动:

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+"!!!");
    }
}   

你的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);
    }



}