1

I crate app to check the database for login info by using jsonParser.makeHttpRequest I try to make my app to stop after 10 second in case there is no internet connection or no response from the server. The code work however when the login button click for the second time the app crash Could anyone please support why this happen

please see the below for the code

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

        }
    }; 

}

please see the below for Error :

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)
  • Stop making new users and posting the same code again and again. [1](http://stackoverflow.com/questions/19788635/android-get-data-from-mysql-table/19788740#19788740) [2](http://stackoverflow.com/questions/19782231/jsonexceptionandroid-cant-connect-mysql-and-php) [3](http://stackoverflow.com/questions/19623771/how-to-fix-fatal-exceptionmain-android-os-networkonmainthreadexception) and I'm sure there are more... – metter Nov 05 '13 at 14:27
  • what you mean this is my first time in stackoverflow – user2956592 Nov 05 '13 at 14:30
  • Please post the error logs too – Aman Gautam Nov 05 '13 at 14:33

1 Answers1

0

An object of an AsyncTask can be run only once. That is why you are getting the IllegalStateException.

Remove the object instantiation [cl= new CheckLogin()] from onCreate().

And instead,

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

    }
});
Swayam
  • 16,294
  • 14
  • 64
  • 102