简体   繁体   English

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

[英]How can i to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

I read and apply something from this link: How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? 我从这个链接中读取并应用了一些东西: 如何将OnPostExecute()的结果导入主活动,因为AsyncTask是一个单独的类? but I get an error NullPointerException onPostExecute on the line delegate.processFinish(result); 但是我在行delegate.processFinish(result)上得到一个错误NullPointerException onPostExecute; 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();
         }
    }

You initialize your variable to null 您将变量初始化为null

public AsyncResponse delegate=null;

so naturally it will give NPE when you try to use it. 所以当你尝试使用它时,它会自然地给出NPE 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. 您在Activity为它赋值,这样您就可以将它传递给AsyncTask的构造函数并将其初始化为该对象。

Your are starting a new AsyncTask in this line: 您正在此行中启动一个新的AsyncTask:

new ProductConnect().execute(true);

you should execute your asyncTask change that line with this: 你应该执行你的asyncTask更改:

asyncTask.execute(true);

I think the best way to do this is using interfaces.. Create a listener for this. 我认为最好的方法是使用接口..为此创建一个监听器。

[]'s []的

you can access asynctask() method when creating new object from it. 从中创建新对象时,可以访问asynctask()方法。 sample: 样品:

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

You've to pass context to that AsyncTask. 您必须将上下文传递给AsyncTask。

Then, on postExecute, cast context to your Activity. 然后,在postExecute上,将上下文转换为您的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: 你的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);
    }



}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果我有一个单独的类扩展了一个如何从onPostExecute()获取值 <AsyncTask> 类? - How to get a value from onPostExecute() to if I have a separate class that extends an <AsyncTask> class? 使用AsyncTask在主Activity的单独类中获取控件 - Get controls in a separate class of the main Activity using AsyncTask 如何从AsyncTask类的onPostExecute方法返回值? - How can i return value from AsyncTask class onPostExecute method? 在Android中:如何将OnPostExecute()的结果发送到其他活动? - In Android: How can i send the result of from OnPostExecute() to other activity? AsyncTask-如何在onPostExecute之后将值传递回活动类? - AsyncTask - How to pass value back to activity class after onPostExecute? 如何停止类的onPostExecute()在 <AsyncTask> 得到字符串结果后? - How to stop onPostExecute() of a class extends on <AsyncTask> after getting the string result? 不在AsyncTask的onPostExecute中设置Activity的实例变量或如何将数据从AsyncTask返回到主UI线程 - Instance variable of Activity not being set in onPostExecute of AsyncTask or how to return data from AsyncTask to main UI thread 从asynctask类的onPostExecute方法中调用活动 - Call activity in method onPostExecute from asynctask class 无法覆盖 AsyncTask 类中的 onPostExecute() 方法或使其触发 - Can't Override onPostExecute() method in AsyncTask Class or get it to trigger 从 onPostExecute 内部 AsyncTask 到 OnCreate 获取结果 - Get Result from onPostExecute inner AsyncTask to OnCreate
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM