Java android:当我重新点击按钮时,应用程序直接关闭

时间:2013-01-22 10:40:20

标签: android json android-asynctask android-activity

我有一个问题..当我启动我的应用程序时,我点击按钮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;         
    }

}

我的Logcat:

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)

谢谢!!

2 个答案:

答案 0 :(得分:1)

使用布尔标志来控制用户单击按钮,如果已经执行,则再次启动阻止以启动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并阻止用户再次启动它(如果已经运行

答案 1 :(得分:0)

根据the documentation of 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;。将变量命名为与类名相同并不是最好的主意。