0

我有问题..当我启动我的应用程序并单击按钮 le 应用程序直接关闭...我不知道如何解决问题...您有什么想法吗?

有时,该应用程序成功运行,但是当我重新单击时,该应用程序直接关闭:(

我的代码:

public class AsyncBigCalculActivity extends Activity {

    private Button mButton;
    private TextView data;
    private String dataImplode;
    PostTask PostTask = new PostTask(this);


    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) {
                AsyncBigCalculActivity activity;
                    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();
              AsyncBigCalculActivity.this.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 de la requête en string
        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());
        }

        // Parse les données JSON
        try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){


                JSONObject data = jArray.getJSONObject(i);

                Num = data.getString("destinataire_mobile");
                Message = data.getString("destinataire_message");
                Id = data.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("site.com","id",Id);


                }

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

}

我的日志猫:

01-22 11:29:58.219: I/global(6771): In close() at SocketHttpClientConnection
01-22 11:29:58.619: E/log_tag(6771): Error parsing data org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
01-22 11:30:21.929: D/AndroidRuntime(6771): Shutting down VM
01-22 11:30:21.929: W/dalvikvm(6771): threadid=1: thread exiting with uncaught exception (group=0x40a4e228)
01-22 11:30:21.939: E/AndroidRuntime(6771): FATAL EXCEPTION: main
01-22 11:30:21.939: E/AndroidRuntime(6771): java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:553)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at android.os.AsyncTask.execute(AsyncTask.java:511)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at com.arnaud.AsyncBigCalculActivity$1.onClick(AsyncBigCalculActivity.java:68)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at android.view.View.performClick(View.java:3538)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at android.view.View$PerformClick.run(View.java:14330)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at android.os.Handler.handleCallback(Handler.java:608)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at android.os.Looper.loop(Looper.java:156)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at android.app.ActivityThread.main(ActivityThread.java:5005)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at java.lang.reflect.Method.invokeNative(Native Method)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at java.lang.reflect.Method.invoke(Method.java:511)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-22 11:30:21.939: E/AndroidRuntime(6771):     at dalvik.system.NativeStart.main(Native Method)

谢谢 !!

4

2 回答 2

1

使用布尔标志来控制用户单击 Button 并阻止 AsyncTask 再次启动(如果它已经在执行)。将您的代码更改为:

public class AsyncBigCalculActivity extends Activity {
      // your code here...
   public static boolean status=false;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        PostTask = new PostTask(this);

        mButton = (Button) findViewById(R.id.btnLaunch);
        // On met un Listener sur le bouton
        mButton.setOnClickListener(new OnClickListener() {


            public void onClick(View arg0) {
               if(!status){
                AsyncBigCalculActivity activity;
                   status=true;
                    PostTask.execute();
                }
                else{
                        // show message here
                 }

            }
        });         
}

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

       @Override
       protected void onPreExecute() {
          super.onPreExecute();
            status=true;  //<< make status true 
       }

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

          status=false; //<< make status false 
       } 
       }

第二种方法是使用AsyncTask.Status并防止用户在已经运行时再次启动它

于 2013-01-22T10:47:36.090 回答
0

根据AsyncTask 的文档 The task can be executed only once (an exception will be thrown if a second execution is attempted.)

这意味着您必须在每次要运行 PostTask 时创建一个新对象。如果您在运行时或运行后不需要引用所述对象,只需使用它来启动您的任务:

public void onClick(View arg0) {
   if(!status){
      AsyncBigCalculActivity activity;
         status=true;
         new PostTask.execute(); // create new instance of PostTask and execute it.
   }
   else {
      // show message here
   }
}

或者,如果您需要对其进行引用:

public void onClick(View arg0) {
   if(!status){
      AsyncBigCalculActivity activity;
         status=true;
         postTask = new PostTask();
         postTask.execute();
   }
   else {
      // show message here
   }
}

postTask 在哪里PostTask postTask = null;。将变量命名为与类名相同并不是最好的主意。

于 2013-01-22T10:53:25.933 回答