1

我从这个链接阅读并应用了一些东西: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();
         }
    }
4

5 回答 5

3

您将变量初始化为null

public AsyncResponse delegate=null;

NPE所以当你尝试使用它时,它自然会给出。你给它一个值,Activity这样你就可以将它传递给你的构造函数AsyncTask并将它初始化为那个对象。

于 2013-10-02T14:20:15.433 回答
1

您正在此行中启动一个新的 AsyncTask:

new ProductConnect().execute(true);

您应该执行您的 asyncTask 更改该行:

asyncTask.execute(true);
于 2013-10-02T14:46:22.000 回答
0

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

[]的

于 2013-10-02T14:17:19.813 回答
0

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

LoginSyncProvider syncProvider = (LoginSyncProvider) new LoginSyncProvider(){
                                @Override
                                protected void onPostExecute(Void aVoid) {
                                    super.onPostExecute(aVoid);
                                    //TODO write something here
                                    }
                                }
                            }.execute();
于 2015-10-27T13:51:48.063 回答
-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+"!!!");
    }
}   

你的异步任务:

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



}
于 2013-10-02T14:15:23.630 回答