0

I have followed this link in making an app that lets users log in with database http://www.mybringback.com/tutorial-series/13239/android-mysql-php-json-part-6-json-parsing-and-android-design/

But after logging in it crashes. I have searched for hours and have read some questions that have the same problem but none of the solutions worked for me.

I am trying to run it in the android emulator.

Login.java

    package com.example.mysqltest;

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener {

    private EditText user, pass;
    private Button mSubmit, mRegister;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class


    // php login script location:

    // localhost :
    // testing on your device
    // put your local ip instead, on windows, run CMD > ipconfig
    // or in mac's terminal type ifconfig and look for the ip under en0 or en1
    // private static final String LOGIN_URL =
    // "http://xxx.xxx.x.x:1234/webservice/login.php";

    // testing on Emulator:



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        // setup input fields
        user = (EditText) findViewById(R.id.username);
        pass = (EditText) findViewById(R.id.password);

        // setup buttons
        mSubmit = (Button) findViewById(R.id.login);
        mRegister = (Button) findViewById(R.id.register);

        // register listeners
        mSubmit.setOnClickListener(this);
        mRegister.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.login:
            new AttemptLogin().execute();
            break;
        case R.id.register:
            Intent i = new Intent(this, Register.class);
            startActivity(i);
            break;

        default:
            break;
        }
    }

    class AttemptLogin extends AsyncTask<String, String, String> {
        private static final String LOGIN_URL = "http://127.0.0.1:1234/webservice/login.php";

        // testing from a real server:
        // private static final String LOGIN_URL =
        // "http://www.mybringback.com/webservice/login.php";

        // JSON element ids from repsonse of php script:
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_MESSAGE = "message";
        boolean failure = false;
        String username, password;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
             username = user.getText().toString();
                password = pass.getText().toString();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;
            JSONParser jsonParser = new JSONParser();
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));

                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                        params);

                // check your log for json response
                Log.d("Login attempt", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Login Successful!", json.toString());
                    // save user data
                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(Login.this);
                    Editor edit = sp.edit();
                    edit.putString("username", username);
                    edit.commit();

                    Intent i = new Intent(Login.this, ReadComments.class);
                    finish();
                    startActivity(i);
                    return json.getString(TAG_MESSAGE);
                } else {
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }

        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null) {
                Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
            }

        }

    }

}

Config.inc.php

<?php 

    // These variables define the connection information for your MySQL database 
    // This is also for the Xampp example,  if you are hosting on your own server,
    //make the necessary changes (mybringback_travis, etc.)


$username = "root"; 
$password = ""; 
$host = "127.0.0.1"; 
$dbname = "webservice"; 

    // UTF-8 is a character encoding scheme that allows you to conveniently store 
    // a wide varienty of special characters, like ¢ or €, in your database. 
    // By passing the following $options array to the database connection code we 
    // are telling the MySQL server that we want to communicate with it using UTF-8 
    // See Wikipedia for more information on UTF-8: 
    // http://en.wikipedia.org/wiki/UTF-8 
    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 

    // A try/catch statement is a common method of error handling in object oriented code. 
    // First, PHP executes the code within the try block.  If at any time it encounters an 
    // error while executing that code, it stops immediately and jumps down to the 
    // catch block.  For more detailed information on exceptions and try/catch blocks: 
    // http://us2.php.net/manual/en/language.exceptions.php 
    try 
    { 
        // This statement opens a connection to your database using the PDO library 
        // PDO is designed to provide a flexible interface between PHP and many 
        // different types of database servers.  For more information on PDO: 
        // http://us2.php.net/manual/en/class.pdo.php 
        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
    } 
    catch(PDOException $ex) 
    { 
        // If an error occurs while opening a connection to your database, it will 
        // be trapped here.  The script will output an error and stop executing. 
        // Note: On a production website, you should not output $ex->getMessage(). 
        // It may provide an attacker with helpful information about your code 
        // (like your database username and password). 
        die("Failed to connect to the database: " . $ex->getMessage()); 
    } 

    // This statement configures PDO to throw an exception when it encounters 
    // an error.  This allows us to use try/catch blocks to trap database errors. 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    // This statement configures PDO to return database rows from your database using an associative 
    // array.  This means the array will have string indexes, where the string value 
    // represents the name of the column in your database. 
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 

    // This block of code is used to undo magic quotes.  Magic quotes are a terrible 
    // feature that was removed from PHP as of PHP 5.4.  However, older installations 
    // of PHP may still have magic quotes enabled and this code is necessary to 
    // prevent them from causing problems.  For more information on magic quotes: 
    // http://php.net/manual/en/security.magicquotes.php 
    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) 
    { 
        function undo_magic_quotes_gpc(&$array) 
        { 
            foreach($array as &$value) 
            { 
                if(is_array($value)) 
                { 
                    undo_magic_quotes_gpc($value); 
                } 
                else 
                { 
                    $value = stripslashes($value); 
                } 
            } 
        } 

        undo_magic_quotes_gpc($_POST); 
        undo_magic_quotes_gpc($_GET); 
        undo_magic_quotes_gpc($_COOKIE); 
    } 

    // This tells the web browser that your content is encoded using UTF-8 
    // and that it should submit content back to you using UTF-8 
    header('Content-Type: text/html; charset=utf-8'); 

    // This initializes a session.  Sessions are used to store information about 
    // a visitor from one web page visit to the next.  Unlike a cookie, the information is 
    // stored on the server-side and cannot be modified by the visitor.  However, 
    // note that in most cases sessions do still use cookies and require the visitor 
    // to have cookies enabled.  For more information about sessions: 
    // http://us.php.net/manual/en/book.session.php 
    session_start(); 

    // Note that it is a good practice to NOT end your PHP files with a closing PHP tag. 
    // This prevents trailing newlines on the file from being included in your output, 
    // which can cause problems with redirecting users.



?>

Login.php

<?php

//load and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {
    //gets user's info based off of a username.
    $query = " 
            SELECT 
                id, 
                username, 
                password
            FROM users 
            WHERE 
                username = :username 
        ";

    $query_params = array(
        ':username' => $_POST['username']
    );

    try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {
        // For testing, you could use a die and message. 
        //die("Failed to run query: " . $ex->getMessage());

        //or just use this use this one to product JSON data:
        $response["success"] = 0;
        $response["message"] = "Database Error1. Please Try Again!";
        die(json_encode($response));

    }

    //This will be the variable to determine whether or not the user's information is correct.
    //we initialize it as false.
    $validated_info = false;

    //fetching all the rows from the query
    $row = $stmt->fetch();
    if ($row) {
        //if we encrypted the password, we would unencrypt it here, but in our case we just
        //compare the two passwords
        if ($_POST['password'] === $row['password']) {
            $login_ok = true;
        }
    }

    // If the user logged in successfully, then we send them to the private members-only page 
    // Otherwise, we display a login failed message and show the login form again 
    if ($login_ok) {
        $response["success"] = 1;
        $response["message"] = "Login successful!";
        die(json_encode($response));
    } else {
        $response["success"] = 0;
        $response["message"] = "Invalid Credentials!";
        die(json_encode($response));
    }
} else {
?>
        <h1>Login</h1> 
        <form action="login.php" method="post"> 
            Username:<br /> 
            <input type="text" name="username" placeholder="username" /> 
            <br /><br /> 
            Password:<br /> 
            <input type="password" name="password" placeholder="password" value="" /> 
            <br /><br /> 
            <input type="submit" value="Login" /> 
        </form> 
        <a href="register.php">Register</a>
    <?php
}

?> 

The Logcat report

 09-20 11:02:38.196: E/AndroidRuntime(913): FATAL EXCEPTION: AsyncTask #1
09-20 11:02:38.196: E/AndroidRuntime(913): Process: com.example.mysqltest, PID: 913
09-20 11:02:38.196: E/AndroidRuntime(913): java.lang.RuntimeException: An error occured while executing doInBackground()
09-20 11:02:38.196: E/AndroidRuntime(913):  at android.os.AsyncTask$3.done(AsyncTask.java:300)
09-20 11:02:38.196: E/AndroidRuntime(913):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
09-20 11:02:38.196: E/AndroidRuntime(913):  at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
09-20 11:02:38.196: E/AndroidRuntime(913):  at java.util.concurrent.FutureTask.run(FutureTask.java:242)
09-20 11:02:38.196: E/AndroidRuntime(913):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-20 11:02:38.196: E/AndroidRuntime(913):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-20 11:02:38.196: E/AndroidRuntime(913):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-20 11:02:38.196: E/AndroidRuntime(913):  at java.lang.Thread.run(Thread.java:841)
09-20 11:02:38.196: E/AndroidRuntime(913): Caused by: java.lang.NullPointerException
09-20 11:02:38.196: E/AndroidRuntime(913):  at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:131)
09-20 11:02:38.196: E/AndroidRuntime(913):  at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:1)
09-20 11:02:38.196: E/AndroidRuntime(913):  at android.os.AsyncTask$2.call(AsyncTask.java:288)
09-20 11:02:38.196: E/AndroidRuntime(913):  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-20 11:02:38.196: E/AndroidRuntime(913):  ... 4 more
  • that means your json is null, you need to investigate why – meda Sep 20 '14 at 15:25
  • I'm sorry what do you mean by my json is null? – insert_name_here Sep 20 '14 at 15:31
  • Use android volley instead, it's much mor effective and fast! http://developer.android.com/training/volley/index.html If you need heavy duty networking use download manager. I have answered here how to use it with JSON http://stackoverflow.com/questions/25948191/android-send-post-request-using-volley-and-receive-in-php/25948689#25948689 – Georgian Benetatos Sep 20 '14 at 15:33

1 Answers1

0

JSONParser is ur custom class for fetching and parsing right?

In any case, if there is exception in our custom class method, the response can be null right? But your not checking the object is null or not. without check directly ur printing the value json.tostring(); If ur json is null then it throws nullpointerexception only. Try changing below code and check once.

replace code from

JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                        params);

to

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
JSONObject json = null;
if(TextUtils.isEmpty(EntityUtils.toString(httpentity))) {
   Log.d("Login attempt", "Json is empty or null");
} else {
   json = new JSONObject(EntityUtils.toString(httpentity));
}
Harsha Vardhan
  • 3,324
  • 2
  • 17
  • 22