javaphpandroidjsondatabase-server

JSONObject getInt(string) method causing java.lang.RuntimeException. Android Studio


I am trying to check if the user is entering the correct user id and password to log in to the app. My database is already deployed online. Everything runs smoothly until I am getting the results to check if the user is allowed to proceed. But the problem is I'm not getting any results. Instead I get a java.lang.RuntimeException on getInt(String) method of JSONObject. Here is my LoginActivity.java

public class LoginActivity extends AppCompatActivity {

    JSONParser jsonParser = new JSONParser();
    // single product url
    private static final String url_user_check_login = "####/android_connect/check_user_login.php?username=#### & password=#####";
     int success=0;
    String id="";
    String password="";
    private static final String TAG_SUCCESS = "success";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

//        Defining onClickListener for Login Button
        Button loginBtn=(Button) findViewById(R.id.login_btn);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Check credentials
                EditText phone=(EditText)findViewById(R.id.phone_txt);
                EditText pwd=(EditText)findViewById(R.id.password_txt);
                id=phone.getText().toString();
                password=pwd.getText().toString();
                new CheckUserLogin().execute();

            }
        });
    }

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

        protected String doInBackground(String... params) {


                    // Check for success tag

                    try {
                        // Building Parameters
                        List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                        params1.add(new BasicNameValuePair("id", id));
                        params1.add(new BasicNameValuePair("password", password));

                        JSONObject json = jsonParser.makeHttpRequest(
                                url_user_check_login, "GET", params1);


                        // json success tag
                        success = json.getInt(TAG_SUCCESS);//This is the line where i am getting the exception

                    } catch (JSONException e) {
                        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
            if (success == 1) {

                Intent intent=new Intent(getApplicationContext(), RideDetailsActivity.class);
                startActivity(intent);

            }
        }
    }
}

And here is the php files I am using.

db_connect.php

db_connect.php
<?php

/**
 * A class file to connect to database
 */
class DB_CONNECT {

    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }

    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }

    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';

        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

        // returing connection cursor
        return $con;
    }

    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }

}

?>

db_config.php

db_config.php
<?php

/*
 * All database connection variables
 */

define('DB_USER', "####"); // db user
define('DB_PASSWORD', "####"); // db password (mention your db password here)
define('DB_DATABASE', "####"); // database name
define('DB_SERVER', "###.###.###); // db server
?>

check_user_login.php

check_user_login.php
<?php

/*
 * Following code will check user credentials for log in
 * uid and password are used to check if the user has permission to log in
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_GET["id"]) && isset($_GET["password"])) {
    $id = $_GET['id'];
    $password = $_GET['password'];

    // get a product from products table
    $result = mysql_query("SELECT * FROM tb_login WHERE id = $id AND password = $password");

    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {

            // success
            $response["success"] = 1;
            $response["message"] = "User found";

            // echoing JSON response
            echo json_encode($response);
        } else {
            // no user found
            $response["success"] = 0;
            $response["message"] = "No user found";

            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no user found
        $response["success"] = 0;
        $response["message"] = "No user found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

Here is the stack trace for the exception

FATAL EXCEPTION: AsyncTask #4
                                                                   java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.NullPointerException
at com.heycabs.heycabs.LoginActivity$CheckUserLogin.doInBackground(LoginActivity.java:100)
at com.heycabs.heycabs.LoginActivity$CheckUserLogin.doInBackground(LoginActivity.java:59)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
at java.lang.Thread.run(Thread.java:838) 

Also I don't know so I am asking do i have to mention the port number for the database along with the IP address for the database server? I am completely new to php and using JSON in android. So please be considerate when pointing out any obvious mistakes. Thanks.


Solution

  • Check out this page. http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html Based on the tutorial you posted in the comments the JSONParser you're using seems to be the problem.

    Here is the code for the update JSONParser if you want to just try and plug it into your code and see if it solves your issue. If you want to read more click the link.

       import android.util.Log;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.HashMap;
    
    public class JSONParser {
    
        String charset = "UTF-8";
        HttpURLConnection conn;
        DataOutputStream wr;
        StringBuilder result;
        URL urlObj;
        JSONObject jObj = null;
        StringBuilder sbParams;
        String paramsString;
    
        public JSONObject makeHttpRequest(String url, String method,
                                          HashMap<String, String> params) {
    
            sbParams = new StringBuilder();
            int i = 0;
            for (String key : params.keySet()) {
                try {
                    if (i != 0){
                        sbParams.append("&");
                    }
                    sbParams.append(key).append("=")
                            .append(URLEncoder.encode(params.get(key), charset));
    
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                i++;
            }
    
            if (method.equals("POST")) {
                // request method is POST
                try {
                    urlObj = new URL(url);
    
                    conn = (HttpURLConnection) urlObj.openConnection();
    
                    conn.setDoOutput(true);
    
                    conn.setRequestMethod("POST");
    
                    conn.setRequestProperty("Accept-Charset", charset);
    
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(15000);
    
                    conn.connect();
    
                    paramsString = sbParams.toString();
    
                    wr = new DataOutputStream(conn.getOutputStream());
                    wr.writeBytes(paramsString);
                    wr.flush();
                    wr.close();
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            else if(method.equals("GET")){
                // request method is GET
    
                if (sbParams.length() != 0) {
                    url += "?" + sbParams.toString();
                }
    
                try {
                    urlObj = new URL(url);
    
                    conn = (HttpURLConnection) urlObj.openConnection();
    
                    conn.setDoOutput(false);
    
                    conn.setRequestMethod("GET");
    
                    conn.setRequestProperty("Accept-Charset", charset);
    
                    conn.setConnectTimeout(15000);
    
                    conn.connect();
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
    
            try {
                //Receive the response from the server
                InputStream in = new BufferedInputStream(conn.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
    
                Log.d("JSON Parser", "result: " + result.toString());
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            conn.disconnect();
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(result.toString());
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON Object
            return jObj;
        }
    }