-1

I just want to access my database using PHP, and view the result in a Toast, but I don't know where I should looking for the error (FATAL EXCEPTION: AsyncTask #2).

Android Code:

btnLogin.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            if (  ( !username.getText().toString().equals("")) && ( !password.getText().toString().equals("")) )
              {
                 new Connect().execute();
              }
              else if ( ( !username.getText().toString().equals("")) )
              {
                  Toast.makeText(getApplicationContext(),
                          "Password field empty", Toast.LENGTH_SHORT).show();
              }
              else if ( ( !password.getText().toString().equals("")) )
              {
                  Toast.makeText(getApplicationContext(),
                          "User Name field empty", Toast.LENGTH_SHORT).show();
              }
              else
              {
                  Toast.makeText(getApplicationContext(),
                          "User Name and Password field are empty", Toast.LENGTH_SHORT).show();
              }


        }
    });
}


class Connect extends AsyncTask<String, String, String>
{
    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        List<NameValuePair> params= new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username.getText().toString()));
        params.add(new BasicNameValuePair("password", password.getText().toString()));

        JSONObject json=JSONParser.getJSONFromUrl(loginURL, params);

        try {
            String login = json.getString(sTag_Login);
            if (login=="Admin") {
                Toast.makeText(getApplicationContext(), "Welcome Admin", Toast.LENGTH_LONG).show();
            }
            else if (login=="Customer") {
                Toast.makeText(getApplicationContext(), "Welcome", Toast.LENGTH_LONG).show();
            }
            {
                Toast.makeText(getApplicationContext(), "error ", Toast.LENGTH_LONG).show();
            }
        } catch(JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
}

And this's my PHP code:

<?php

 // array for JSON response
$response = array();
$db = mysqli_connect('mysql.hostinger.ae','u641845309_ur','q1p0w2o9','u641845309_song');

// username and password sent from Form and protect MySQL injection for Security purpose
$username = $_POST['username']; 
$password = $_POST['password']; 

$sql = "SELECT * FROM customer WHERE UName='$username' and Password='$password'";

// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$result=mysqli_query($db,$sql);  

// If result matched $myusername and $mypassword, table row must be 1 row
if ($result)
{ 
    while($row = mysqli_fetch_array($result)) {
        if(strtolower($username) == 'admin') 
            $response["login"] =   "Admin"; 
        else 
            $response["login"] = "Customer"; 
    }
}
else 
{
    $response["login"] ="error"; 
}

// echoing JSON response
echo json_encode($response);

JSON Code:

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public static JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

And this is logcat:

01-15 13:49:35.770: D/gralloc_goldfish(2098): Emulator without GPU emulation detected.
01-15 13:49:39.800: D/dalvikvm(2098): GC_FOR_ALLOC freed 166K, 7% free 3117K/3348K, paused 54ms, total 68ms
01-15 13:49:39.800: D/InputEventConsistencyVerifier(2098): KeyEvent: ACTION_UP but key was not down.
01-15 13:49:39.800: D/InputEventConsistencyVerifier(2098):   in android.widget.LinearLayout{b3d26008 V.E..... ......I. 0,59-455,118}
01-15 13:49:39.800: D/InputEventConsistencyVerifier(2098):   0: sent at 8592505000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=8592505, downTime=8592401, deviceId=0, source=0x101 }
01-15 13:50:01.560: W/System.err(2098): java.net.UnknownHostException: Unable to resolve host "mwssong.esy.es": No address associated with hostname
01-15 13:50:01.570: W/System.err(2098):     at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
01-15 13:50:01.580: W/System.err(2098):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-15 13:50:01.580: W/System.err(2098):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
01-15 13:50:01.580: W/System.err(2098):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-15 13:50:01.590: W/System.err(2098):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-15 13:50:01.590: W/System.err(2098):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-15 13:50:01.590: W/System.err(2098):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-15 13:50:01.600: W/System.err(2098):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-15 13:50:01.600: W/System.err(2098):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-15 13:50:01.600: W/System.err(2098):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-15 13:50:01.600: W/System.err(2098):     at com.example.e_music.JSONParser.getJSONFromUrl(JSONParser.java:44)
01-15 13:50:01.610: W/System.err(2098):     at com.example.e_music.MainActivity$Connect.doInBackground(MainActivity.java:126)
01-15 13:50:01.620: W/System.err(2098):     at com.example.e_music.MainActivity$Connect.doInBackground(MainActivity.java:1)
01-15 13:50:01.620: W/System.err(2098):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-15 13:50:01.620: W/System.err(2098):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-15 13:50:01.640: W/System.err(2098):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-15 13:50:01.640: W/System.err(2098):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-15 13:50:01.650: W/System.err(2098):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-15 13:50:01.650: W/System.err(2098):     at java.lang.Thread.run(Thread.java:841)
01-15 13:50:01.670: W/System.err(2098): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
01-15 13:50:01.670: W/System.err(2098):     at libcore.io.Posix.getaddrinfo(Native Method)
01-15 13:50:01.670: W/System.err(2098):     at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
01-15 13:50:01.670: W/System.err(2098):     at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
01-15 13:50:01.670: W/System.err(2098):     ... 18 more
01-15 13:50:01.680: E/Buffer Error(2098): Error converting result java.lang.NullPointerException: lock == null
01-15 13:50:01.680: E/JSON Parser(2098): Error parsing data org.json.JSONException: End of input at character 0 of 
01-15 13:50:01.680: W/dalvikvm(2098): threadid=12: thread exiting with uncaught exception (group=0xb3a22ba8)
01-15 13:50:01.750: E/AndroidRuntime(2098): FATAL EXCEPTION: AsyncTask #2
01-15 13:50:01.750: E/AndroidRuntime(2098): Process: com.example.e_music, PID: 2098
01-15 13:50:01.750: E/AndroidRuntime(2098): java.lang.RuntimeException: An error occured while executing doInBackground()
01-15 13:50:01.750: E/AndroidRuntime(2098):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
01-15 13:50:01.750: E/AndroidRuntime(2098):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
01-15 13:50:01.750: E/AndroidRuntime(2098):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
01-15 13:50:01.750: E/AndroidRuntime(2098):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
01-15 13:50:01.750: E/AndroidRuntime(2098):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-15 13:50:01.750: E/AndroidRuntime(2098):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-15 13:50:01.750: E/AndroidRuntime(2098):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-15 13:50:01.750: E/AndroidRuntime(2098):     at java.lang.Thread.run(Thread.java:841)
01-15 13:50:01.750: E/AndroidRuntime(2098): Caused by: java.lang.NullPointerException
01-15 13:50:01.750: E/AndroidRuntime(2098):     at com.example.e_music.MainActivity$Connect.doInBackground(MainActivity.java:129)
01-15 13:50:01.750: E/AndroidRuntime(2098):     at com.example.e_music.MainActivity$Connect.doInBackground(MainActivity.java:1)
01-15 13:50:01.750: E/AndroidRuntime(2098):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-15 13:50:01.750: E/AndroidRuntime(2098):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-15 13:50:01.750: E/AndroidRuntime(2098):     ... 4 more
Will
  • 24,082
  • 14
  • 97
  • 108
  • You would want to look at your stacktrace for the error. I see a couple problems here though. One is that you have `onPostExecute()` and `onProgressUpdate()` taking `String`s but you aren't overriding their methods. Another problem is you are trying to show `Toast`s in `doInBackground()`. You may want to refer to [Using AsyncTask](http://stackoverflow.com/questions/18898039/using-asynctask/18898105#18898105) and read over the documentation again. – codeMagic Jan 15 '16 at 18:49
  • no dear, I didn't use **onPostExecute()** nor **onProgressUpdate()** – Ahmad Yousef Jan 15 '16 at 19:02
  • and **Toast** work SUCCESSFULLY! – Ahmad Yousef Jan 15 '16 at 19:04
  • First problem is `Caused by: java.lang.NullPointerException 01-15 13:50:01.750: E/AndroidRuntime(2098): at com.example.e_music.MainActivity$Connect.doInBackground(MainActivity.java:129)` but then you still have the others I mentioned above – codeMagic Jan 15 '16 at 19:05
  • @AhmadYousef since you posted your mysql password (and username), PLEASE CHANGE THEM before someone gets unexpected access to your server – petey Jan 15 '16 at 19:18

2 Answers2

1

Remove your Toast from doInBackground(), AsyncTask is working independently from your UI activity, so if you want to call Toast in it, you should at least run it inside this block:

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                       "Your code is looking very bad!",
                                       Toast.LENGTH_LONG);
                    }
                });

Another problem is, that your getJSONFromUrl() function might return null if any exception will occur in it, because you are doing nothing in your exception handlers to prevent it from returning null.
Inside doInBackground() method you are trying to catch JSONException, but it likely will be a NullPointerException because of getJSONFromUrl() might return null. You need to review your code briefly. Consider using isEmpty() instead of comparing to empty strings, handle exceptions properly.
You get clear UnknownHostException for mwssong.esy.es, did you add http:// to it?

petey
  • 16,914
  • 6
  • 65
  • 97
Bio-Matic
  • 793
  • 1
  • 8
  • 20
0
where I should search when appear FATAL EXCEPTION: AsyncTask #2 error

Usually look at lines directly after for the caused by which will give you a file and line number of where this went wrong

Caused by: java.lang.NullPointerException
01-15 13:50:01.750: E/AndroidRuntime(2098): at
   com.example.e_music.MainActivity$Connect.doInBackground(MainActivity.java:129)

Don't update the ui from a background thread. To fix separate your long running operation (the login check) and ui update (the toast) into the appropriate methods, doInBackground & onPostExecute respectively by returning a string in doInBackground for use in onPostExecute

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

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username.getText().toString()));
            params.add(new BasicNameValuePair("password", password.getText().toString()));


            try {
                JSONObject json = JSONParser.getJSONFromUrl(loginURL, params);
                String login = json.getString(sTag_Login);
                if ("Admin".equals(login)) {
                    return "Welcome Admin";
                } else if ("Customer".equals(login)) {
                    return "Welcome";
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return "error";
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
        }
}
petey
  • 16,914
  • 6
  • 65
  • 97
  • @5624627 maybe your android device has no access to that host. And that would be another question since it is outside the scope of THIS post/question "where I should search when appear FATAL EXCEPTION" as this has been answered here. – petey Jan 15 '16 at 19:52
  • this problem happened : 01-17 06:42:42.027: E/JSON(1339): Customer 01-17 06:42:42.027: E/JSON Parser(1339): Error parsing data org.json.JSONException: Value Customer of type java.lang.String cannot be converted to JSONObject – Ahmad Yousef Jan 17 '16 at 12:02
  • It gave me "Customer" and this's true result, but how can I convert it to object!! what shall I do?! – Ahmad Yousef Jan 17 '16 at 12:10
  • @AhmadYousef sorry, This question ("where I should search when appear FATAL EXCEPTION") has now been answered as well as code fixes for your original crash and _hopefully_ you might find this answer ACCEPTABLE (hint hint). I feel that **"how can I convert it to object"** is another new question that you should ask. – petey Jan 18 '16 at 13:59