0

I'm writing an android login application which checks if the user is valid or not and then starts a new Activity if he's a valid user. I'm a beginner to both Android programming and PHP coding. But, the application is crashing when i click the login button. I'm using PHP code.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    login=(Button)findViewById(R.id.id_buttonLogin);
    register=(Button)findViewById(R.id.id_buttonSignup);

    phone=(EditText)findViewById(R.id.id_phone);
    password=(EditText)findViewById(R.id.id_password);

    //sPhone=phone.getText().toString();
    //sPassword=password.getText().toString();


    login.setOnClickListener(this);

    register.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Intent registerOption=new Intent("easy.assign.droid.REGISTRATIONOPTIONACTIVITY");
            startActivity(registerOption);
        }
    });


}

public void onClick(View v) 
{
    new MyAsyncTask().execute();
}

private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    String result = null;
    try
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");

        String line="0";
        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());
    }
    return result;  
}//END convertStreamToString()

private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
        ProgressDialog pDialog;
        @Override
        protected void onPostExecute(Void result) 
        {
            pDialog.dismiss();
            Intent nextpage=new Intent("easy.assign.droid.HOMESTUDENT");
            startActivity(nextpage);
        }

        @Override
        protected void onPreExecute() 
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(LoginActivity.this);
            pDialog.setMessage("Loading data. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) 
        {

            //Create new default HTTPClient
            httpclient = new DefaultHttpClient();

            //Create new HTTP POST with URL to php file as parameter
            httppost = new HttpPost("http://10.0.2.2/project/check.php"); 

            sPhone=phone.getText().toString();
            sPassword=password.getText().toString();
            //Next block of code needs to be surrounded by try/catch block for it to work
            try 
            {
                //Create new Array List
                nameValuePairs = new ArrayList<NameValuePair>(2);

                //place them in an array list
                nameValuePairs.add(new BasicNameValuePair("sPhone", sPhone));
                nameValuePairs.add(new BasicNameValuePair("sPassword", sPassword));

                //Add array list to http post
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


                //assign executed form container to response
                response = httpclient.execute(httppost); //response from the PHP file

                //check status code, need to check status code 200
                if(response.getStatusLine().getStatusCode() == 200)
                {
                    //assign response entity to http entity
                    entity = response.getEntity();

                    //check if entity is not null
                    if(entity != null)
                    {
                        //Create new input stream with received data assigned
                        InputStream instream = entity.getContent();

                        //Create new JSON Object. assign converted data as parameter.
                        jArray = new JSONArray(convertStreamToString(instream));
                        JSONObject json_data = null;
                        String retUser = null, retPass = null;
                        for(int i=0;i<jArray.length();i++)
                        {
                            json_data = jArray.getJSONObject(i);
                            retUser = json_data.get("sphone").toString();
                            retPass = json_data.get("spassword").toString();
                        }

                        //assign json responses to local strings
                        //String retUser = jsonResponse.getString("sphone");//mySQL table field
                        //String retPass = jsonResponse.getString("spassword");

                        //Validate login
                        if(sPhone.equals(retUser)&& sPassword.equals(retPass))
                        { //Check whether 'retUser' and 'retPass' matches username/password 
                            //Display a Toast saying login was a success
                            SharedPreferences sp = getSharedPreferences("login details", 0);
                            SharedPreferences.Editor spedit = sp.edit();

                            spedit.putString("sPhone", sPhone);
                            spedit.putString("sPassword", sPassword);

                            spedit.commit();
                            //Toast.makeText(getBaseContext(), "Successful", Toast.LENGTH_SHORT).show();
                        } 
                        else 
                        {
                            //Display a Toast saying it failed.
                            Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
                        }

                    }
                }
            } 
            catch(Exception e)
            {
                e.printStackTrace();
                //Display toast when there is a connection error
                //Change message to something more friendly
               //Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
               Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
            }

            return null;
        }
}
}

Here's the PHP code:

<?php

$connect = mysqli_connect("localhost","root","","easyassigndroid");

if(mysqli_connect_errno($connect))
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
    echo "success";
}

$username = isset($_POST['sPhone']) ? $_POST['sPhone'] : '';
$password = isset($_POST['sPassword']) ? $_POST['sPassword'] : '';

$query = mysqli_query($connect, "select * from users where sphone='$username' and spassword='$password' ");

$num = mysqli_num_rows($query);

if($num==1)
{
    while($list = mysqli_fetch_assoc($query))
    {
        $output = $list;
        print(json_encode($output));
    }

    mysqli_close();
}

?>

I get "org.json.JSONException: Value success of type java.lang.String cannot be converted to JSONObject" and a "FATAL EXCEPTION". In addition, I get the following exceptions in the logcat:

03-31 11:24:43.337: W/System.err(532): org.json.JSONException: Value success of type java.lang.String cannot be converted to JSONObject
03-31 11:24:43.337: W/System.err(532):  at org.json.JSON.typeMismatch(JSON.java:111)
03-31 11:24:43.367: W/System.err(532):  at org.json.JSONObject.<init>(JSONObject.java:158)
03-31 11:24:43.377: W/System.err(532):  at org.json.JSONObject.<init>(JSONObject.java:171)
03-31 11:24:43.377: W/System.err(532):  at easy.assign.droid.LoginActivity$MyAsyncTask.doInBackground(LoginActivity.java:160)
03-31 11:24:43.377: W/System.err(532):  at   easy.assign.droid.LoginActivity$MyAsyncTask.doInBackground(LoginActivity.java:1)
03-31 11:24:43.407: W/System.err(532):  at android.os.AsyncTask$2.call(AsyncTask.java:264)
03-31 11:24:43.407: W/System.err(532):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-31 11:24:43.417: W/System.err(532):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-31 11:24:43.417: W/System.err(532):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
03-31 11:24:43.447: W/System.err(532):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-31 11:24:43.447: W/System.err(532):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-31 11:24:43.457: W/System.err(532):  at java.lang.Thread.run(Thread.java:856)
03-31 11:24:43.507: W/dalvikvm(532): threadid=11: thread exiting with uncaught exception (group=0x409c01f8)
03-31 11:24:43.617: E/AndroidRuntime(532): FATAL EXCEPTION: AsyncTask #1
03-31 11:24:43.617: E/AndroidRuntime(532): java.lang.RuntimeException: An error occured while executing doInBackground()
03-31 11:24:43.617: E/AndroidRuntime(532):  at android.os.AsyncTask$3.done(AsyncTask.java:278)
03-31 11:24:43.617: E/AndroidRuntime(532):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-31 11:24:43.617: E/AndroidRuntime(532):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-31 11:24:43.617: E/AndroidRuntime(532):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-31 11:24:43.617: E/AndroidRuntime(532):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-31 11:24:43.617: E/AndroidRuntime(532):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
03-31 11:24:43.617: E/AndroidRuntime(532):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-31 11:24:43.617: E/AndroidRuntime(532):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-31 11:24:43.617: E/AndroidRuntime(532):  at java.lang.Thread.run(Thread.java:856)
03-31 11:24:43.617: E/AndroidRuntime(532): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
03-31 11:24:43.617: E/AndroidRuntime(532):  at android.os.Handler.<init>(Handler.java:121)
03-31 11:24:43.617: E/AndroidRuntime(532):  at android.widget.Toast$TN.<init>(Toast.java:317)
03-31 11:24:43.617: E/AndroidRuntime(532):  at android.widget.Toast.<init>(Toast.java:91)
03-31 11:24:43.617: E/AndroidRuntime(532):  at android.widget.Toast.makeText(Toast.java:233)
03-31 11:24:43.617: E/AndroidRuntime(532):  at easy.assign.droid.LoginActivity$MyAsyncTask.doInBackground(LoginActivity.java:194)
03-31 11:24:43.617: E/AndroidRuntime(532):  at easy.assign.droid.LoginActivity$MyAsyncTask.doInBackground(LoginActivity.java:1)
03-31 11:24:43.617: E/AndroidRuntime(532):  at android.os.AsyncTask$2.call(AsyncTask.java:264)
03-31 11:24:43.617: E/AndroidRuntime(532):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-31 11:24:43.617: E/AndroidRuntime(532):  ... 5 more
03-31 11:24:44.507: I/dalvikvm(532): threadid=3: reacting to signal 3
03-31 11:24:44.527: I/dalvikvm(532): Wrote stack traces to '/data/anr/traces.txt'
03-31 11:24:44.797: E/WindowManager(532): Activity easy.assign.droid.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@411ddc48 that was originally added here
03-31 11:24:44.797: E/WindowManager(532): android.view.WindowLeaked: Activity easy.assign.droid.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@411ddc48 that was originally added here
03-31 11:24:44.797: E/WindowManager(532):   at android.view.ViewRootImpl.<init>(ViewRootImpl.java:344)
03-31 11:24:44.797: E/WindowManager(532):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
03-31 11:24:44.797: E/WindowManager(532):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
03-31 11:24:44.797: E/WindowManager(532):   at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
03-31 11:24:44.797: E/WindowManager(532):   at android.view.Window$LocalWindowManager.addView(Window.java:537)
03-31 11:24:44.797: E/WindowManager(532):   at android.app.Dialog.show(Dialog.java:278)
03-31 11:24:44.797: E/WindowManager(532):   at android.app.ProgressDialog.show(ProgressDialog.java:116)
03-31 11:24:44.797: E/WindowManager(532):   at android.app.ProgressDialog.show(ProgressDialog.java:99)
03-31 11:24:44.797: E/WindowManager(532):   at android.app.ProgressDialog.show(ProgressDialog.java:94)
03-31 11:24:44.797: E/WindowManager(532):   at easy.assign.droid.LoginActivity$MyAsyncTask.onPreExecute(LoginActivity.java:117)
03-31 11:24:44.797: E/WindowManager(532):   at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
03-31 11:24:44.797: E/WindowManager(532):   at android.os.AsyncTask.execute(AsyncTask.java:511)
03-31 11:24:44.797: E/WindowManager(532):   at easy.assign.droid.LoginActivity.onClick(LoginActivity.java:75)
03-31 11:24:44.797: E/WindowManager(532):   at android.view.View.performClick(View.java:3511)
03-31 11:24:44.797: E/WindowManager(532):   at android.view.View$PerformClick.run(View.java:14105)
03-31 11:24:44.797: E/WindowManager(532):   at android.os.Handler.handleCallback(Handler.java:605)
03-31 11:24:44.797: E/WindowManager(532):   at android.os.Handler.dispatchMessage(Handler.java:92)
03-31 11:24:44.797: E/WindowManager(532):   at android.os.Looper.loop(Looper.java:137)
03-31 11:24:44.797: E/WindowManager(532):   at android.app.ActivityThread.main(ActivityThread.java:4424)
03-31 11:24:44.797: E/WindowManager(532):   at java.lang.reflect.Method.invokeNative(Native Method)
03-31 11:24:44.797: E/WindowManager(532):   at java.lang.reflect.Method.invoke(Method.java:511)
03-31 11:24:44.797: E/WindowManager(532):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-31 11:24:44.797: E/WindowManager(532):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-31 11:24:44.797: E/WindowManager(532):   at dalvik.system.NativeStart.main(Native Method)
03-31 11:24:47.237: I/Process(532): Sending signal. PID: 532 SIG: 9

Can anyone tell me where the problem is? In the PHP code, Android code or both?

7
  • Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() this makes your trouble
    – Eveli
    Apr 2, 2013 at 12:37
  • echo "success" this line in php causing an error ... you don't getting valid json from server ...
    – Selvin
    Apr 2, 2013 at 12:40
  • 1
    I don't believe you can Toast within the doInBackground, you can't manipulate, call, etc any UI components from a background thread.
    – jnthnjns
    Apr 2, 2013 at 12:42
  • 1
    You have messy, first you cannot show Toast from background thread and why you are fetching at first JSONArray? You need to fetch root JSONObject and then its childs. Apr 2, 2013 at 12:47
  • @Sajmon How do I fetch root JSONObject? Can you tell me? :) Apr 2, 2013 at 12:54

3 Answers 3

0

this may helps you in Your

doInBackground

    sPhone=phone.getText().toString();
    sPassword=password.getText().toString();

you trying to get String from Edittext means could not bind Control here and also

Toast like

runOnUiThread(new Runnable() {
    public void run() {
       Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
   }
});
1
  • I did that. Yet, I keep getting the same errors. Is the JSON part of my code correct? Apr 2, 2013 at 14:59
0

your trying to show Toast message in doInBackground(), run this code in runOnUiThread()

change this code in doInBackground() method

Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();

and this

sPhone=phone.getText().toString();
sPassword=password.getText().toString();

like this

runOnUiThread(new Runnable() {
   public void run() {
      sPhone=phone.getText().toString();
      sPassword=password.getText().toString();
   }
});

runOnUiThread(new Runnable() {
    public void run() {
       Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
   }
});
3
  • Or, since this Toast is a success / fail parameter he could simply pass status to onPostExecute and Toast from there. Couple different options.
    – jnthnjns
    Apr 2, 2013 at 12:50
  • I did what you've mentioned :) But, still the problem persists :( Apr 2, 2013 at 12:58
  • I get the same errors that I'd mentioned in the beginning. Do you know tutorials for a login application using AsyncTask? :( Apr 2, 2013 at 14:39
-1
new MyAsyncTask().execute();

private class MyAsyncTask extends AsyncTask<Void, Void, Void>

You have to write

new MyAsyncTask().execute(null,null,null);  
1
  • This doesn't help. I get the same errors I'd mentioned in the first post :( Apr 2, 2013 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.