如何从AsyncTask调用活动方法

时间:2013-01-21 13:24:35

标签: android android-asynctask android-activity

当我启动我的应用程序时,它会直接关闭。我一直在寻找,但我还没有找到解决问题的方法。

您有解决问题的想法吗?

public class AsyncBigCalculActivity extends Activity {
    private Button mButton;
    private TextView data;
    private String dataImplode;
    PostTask PostTask = new PostTask(this);
    public AsyncBigCalculActivity activity;

    public void sendSMS(String phoneNumber, String message) {  
        Toast.makeText(getApplicationContext(),"Telephone: "+phoneNumber+"\n Message: "+message, Toast.LENGTH_LONG).show();
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        // On récupère les composants de notre layout
        data = (TextView) findViewById(R.id.data);
        mButton = (Button) findViewById(R.id.btnLaunch);

        // On met un Listener sur le bouton
        mButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                    PostTask.execute();
            }
        });         
}

       // The definition of our task class
       private class PostTask extends AsyncTask<String, Integer, String> {

           private AsyncBigCalculActivity activty;

       public PostTask(AsyncBigCalculActivity activty) {
          this.activty = activty;
       }

       @Override
       protected void onPreExecute() {
          super.onPreExecute();

       }

       @Override
       protected String doInBackground(String... params) {
          return getServerData("http://site.com","etat","nok");
       }

       @Override
       protected void onProgressUpdate(Integer... values) {
          super.onProgressUpdate(values);
       }

       @Override
       protected void onPostExecute(String result) {
          super.onPostExecute(result);

          if(result != null || result.length()>0){
              String[] res = result.split(";-;");
              Toast.makeText(getApplicationContext(), res[0]+"\n"+res[1]+"\n"+res[2], Toast.LENGTH_LONG).show();
              activity.sendSMS("0000000000", "Hello World !");  
          }

       }
       }


private String getServerData(String returnString,String post, String valeur) {
        String Num ="";
        String Message ="";
        String Id ="";

        InputStream is = null;
        String result = "";

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair(post,valeur));

        // Envoie de la commande http
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(returnString);
            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());
        }

        // Convertion
        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();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        // Parsing 
        try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                Num = jArray.getJSONObject(i).getString("destinataire_mobile");
                Message = jArray.getJSONObject(i).getString("destinataire_message");
                Id = jArray.getJSONObject(i).getString("id");
                dataImplode = Num+";-;"+Message+";-;"+Id;

                if(((Num.length())==12) && (((Message.length())>=2)) && Num != "" && Message !=""){





                    SmsManager sms = SmsManager.getDefault();
                    ArrayList<String> parts = sms.divideMessage(Message);
                    sms.sendMultipartTextMessage(Num, null, parts, null, null);

                    getServerData("http://site.com","id",Id);
                }

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

错误Logcat:

01-21 14:05:45.978: I/global(7218): In close() at SocketHttpClientConnection
01-21 14:05:49.788: D/HtcBuildUtils(7218): NetworkOperator: 20801
01-21 14:05:49.788: D/HtcBuildUtils(7218): NetworkOperator: 20801
01-21 14:05:49.788: D/HtcBuildUtils(7218): NetworkOperator: 20801
01-21 14:05:49.788: D/HtcBuildUtils(7218): NetworkOperator: 20801
01-21 14:05:49.788: D/SmsManager(7218): General sendMultipartText
01-21 14:05:49.908: I/global(7218): In close() at SocketHttpClientConnection
01-21 14:05:50.098: E/log_tag(7218): Error parsing data org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
01-21 14:05:50.108: D/AndroidRuntime(7218): Shutting down VM
01-21 14:05:50.108: W/dalvikvm(7218): threadid=1: thread exiting with uncaught exception (group=0x40a5c228)
01-21 14:05:50.118: E/AndroidRuntime(7218): FATAL EXCEPTION: main
01-21 14:05:50.118: E/AndroidRuntime(7218): java.lang.NullPointerException
01-21 14:05:50.118: E/AndroidRuntime(7218):     at com.arnaud.AsyncBigCalculActivity$PostTask.onPostExecute(AsyncBigCalculActivity.java:111)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at com.arnaud.AsyncBigCalculActivity$PostTask.onPostExecute(AsyncBigCalculActivity.java:1)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at android.os.AsyncTask.finish(AsyncTask.java:602)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at android.os.Looper.loop(Looper.java:156)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at android.app.ActivityThread.main(ActivityThread.java:5005)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at java.lang.reflect.Method.invokeNative(Native Method)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at java.lang.reflect.Method.invoke(Method.java:511)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-21 14:05:50.118: E/AndroidRuntime(7218):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

问题是你的PostTask构造函数永远不会被调用。这是因为您在没有实例化PostTask.execute()的情况下调用PostTask

这是两个解决方案:

您可以使用activity.sendSMS方法将AsyncBigCalculActivity.this.sendSMS()替换为onPostExecute

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);

    if(result != null || result.length() > 0){
        String[] res = result.split(";-;");
        Toast.makeText(getApplicationContext(), res[0]+"\n"+res[1]+"\n"+res[2], Toast.LENGTH_LONG).show();
        AsyncBigCalculActivity.this.sendSMS("0000000000", "Hello World !");  
     }
}

或只需在new PostTask(AsyncBigCalculActivity.this).execute()方法上致电onClick