1

我使用 jsonParser.makeHttpRequest 创建应用程序来检查数据库的登录信息我尝试让我的应用程序在 10 秒后停止,以防没有互联网连接或服务器没有响应。但是,当登录按钮第二次单击应用程序崩溃时,代码可以工作,任何人都可以支持为什么会发生这种情况

请参阅下面的代码

    package com.example.pfms;


import java.util.ArrayList;
import java.util.List;



import org.apache.http.NameValuePair;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ListActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;


public class MainActivity extends Activity {

    private String id,pass,p,logincheck;
    private EditText username,password;
    private Button login;
    private CheckLogin cl;
    private ProgressDialog pDialog;
    private SharedPreferences prefs;
    JSONParser jsonParser = new JSONParser();
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCT = "product";
    private static final String url = "http://192.168.1.11/pfm/get_id.php";


    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        cl= new CheckLogin();
        username=(EditText)findViewById(R.id.editText1);
        password=(EditText)findViewById(R.id.editText2);
        login=(Button)findViewById(R.id.button1);
        prefs = this.getSharedPreferences("com.example.pfms", MODE_PRIVATE);
        logincheck=prefs.getString("com.example.pfms.login", "0");
        if(!logincheck.equals("0")){
            Intent i=new Intent(MainActivity.this,TechOption.class);
            Bundle info=new Bundle();
            info.putString("techid",logincheck);
            i.putExtras(info);
            startActivity(i);   
        }

login.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        cl.execute(); 

    }
});
    }




    class CheckLogin extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Checking Login info. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            p="0";
            pass="0";
            Log.d("test", "dialog");
        }

        /**
         * Getting product details in background thread
         * */

        protected String doInBackground(String... params) {

            // updating UI from Background Thread
    //      runOnUiThread(new Runnable() {
    //          public void run() {
                    // Check for success tag
                    int success;
                    try {
                        Log.d("test", "run");
                        // Building Parameters
                        List<NameValuePair> params2 = new ArrayList<NameValuePair>();

                        id=username.getText().toString();
                        pass=password.getText().toString();
                        params2.add(new BasicNameValuePair("id",id));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request

                //      HttpParams httpParameters = new BasicHttpParams();
                //      HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
                //      HttpConnectionParams.setSoTimeout(httpParameters, 30000);
                //      DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

                        messageHandler.sendEmptyMessageDelayed(0, 10000);
                        Log.d("test", "before");
                        JSONObject json = jsonParser.makeHttpRequest(
                                url, "GET", params2);

                        // check your log for json response
                        Log.d("Single Product Details", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        Log.d("test", "before success");
                        if (success == 1) {
                            // successfully received product details
                            JSONArray actiondetail = json
                                    .getJSONArray(TAG_PRODUCT); // JSON Array

                            // get first product object from JSON Array



                                JSONObject c = actiondetail.getJSONObject(0);

                                // Storing each json item in variable
                                p="";

                                 p = c.getString("pass");
                                Log.d("info", "p="+p);
                                Log.d("info", "pass="+pass);





                        }else{
                            Toast.makeText(getBaseContext(), "Wrong  Username", Toast.LENGTH_LONG).show();

                        }

                        Log.d("test", "after success");
                    } catch (JSONException e) {
                        //pDialog.dismiss();
                        //Toast.makeText(getBaseContext(), "Please check internet connection", Toast.LENGTH_LONG).show();

                        e.printStackTrace();
                    }
        //      }
    //      });





            return null;
        }


        /**
         * After completing background task Dismiss the progress dialog
         * **/

        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
            Log.d("test", "dismiss dailog");
            if(p.contentEquals(pass)){
                Intent i=new Intent(MainActivity.this,TechOption.class);
                Bundle info=new Bundle();
                info.putString("techid",id);
                i.putExtras(info);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("com.example.pfms.login",id); 
                editor.commit();
                startActivity(i);   
            }
            else{
                Toast.makeText(getBaseContext(), "Wrong  Password", Toast.LENGTH_LONG).show();
            }

        }
    }

    private Handler messageHandler = new Handler() {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pDialog.dismiss();
            Toast.makeText(getBaseContext(), "Please check internet connection", Toast.LENGTH_LONG).show();
            cl.cancel(true);

        }
    }; 

}

请参阅下面的错误:

11-05 09:37:09.053: D/AndroidRuntime(1398): Shutting down VM
11-05 09:37:09.053: W/dalvikvm(1398): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-05 09:37:09.123: E/AndroidRuntime(1398): FATAL EXCEPTION: main
11-05 09:37:09.123: E/AndroidRuntime(1398): java.lang.IllegalStateException: Cannot execute task: the task is already running.
11-05 09:37:09.123: E/AndroidRuntime(1398):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:575)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at android.os.AsyncTask.execute(AsyncTask.java:534)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at com.example.pfms.MainActivity$2.onClick(MainActivity.java:79)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at android.view.View.performClick(View.java:4240)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at android.view.View$PerformClick.run(View.java:17721)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at android.os.Handler.handleCallback(Handler.java:730)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at android.os.Looper.loop(Looper.java:137)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at java.lang.reflect.Method.invokeNative(Native Method)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at java.lang.reflect.Method.invoke(Method.java:525)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-05 09:37:09.123: E/AndroidRuntime(1398):     at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

0

AsyncTask 的对象只能运行一次。这就是为什么你得到IllegalStateException.

从 onCreate() 中移除对象实例化 [ cl= new CheckLogin()]。

相反,

login.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        new CheckLogin.execute(); // creating an anonymous object of the AsyncTask makes sure that you never use it again which prevents any IllegalStateExceptions

    }
});
于 2013-11-05T14:42:13.073 回答