简体   繁体   中英

Whenever I run the android login application it just crashes an a series of error messages in log

I am currently working on an app that can use the website's database for its login credentials. Everytime I click the login button it crashes. I am not sure what causes the problem. I'm stock for hour. Here is my code:

LoginScreen.java:

package com.example.androidtest;

    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.os.AsyncTask;
    import android.os.Bundle;
    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 LoginScreen extends Activity implements OnClickListener{

    private EditText user, pass;
    private Button mSubmit;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    //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:
    private static final String LOGIN_URL = "http://lentech.site11.com/android/check_user.php";

    //testing from a real server:
    //private static final String LOGIN_URL = "http://www.yourdomain.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";

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

        //setup input fields
        user = (EditText)findViewById(R.id.login_userName);
        pass = (EditText)findViewById(R.id.login_passWord);

        //setup buttons
        mSubmit = (Button)findViewById(R.id.btnLogin);

        //register listeners
        mSubmit.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        new AttemptLogin().execute();
        /*switch (v.getId()) {
            case R.id.btnLogin:
                new AttemptLogin().execute();
            default:
                break;
        }*/
    }

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

        /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(LoginScreen.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;
            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());
                    Intent i = new Intent(LoginScreen.this, MainScreenActivity.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;

        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(LoginScreen.this, file_url, Toast.LENGTH_LONG).show();
            }
        }

    }
}

Here is the Log it always point out these lines it is in the LoginScreen.java:

        at com.example.androidhive.Login$AttemptLogin.doInBackground(Login.java:122)
        at com.example.androidhive.Login$AttemptLogin.doInBackground(Login.java:86)
        at com.example.androidhive.Login$AttemptLogin.onPreExecute(Login.java:100)
        at com.example.androidhive.Login.onClick(Login.java:77)

  01-02 23:58:30.078    1837-1837/com.example.androidhive I/art﹕ Not late-enabling -Xcheck:jni (already on)
01-02 23:58:32.755    1837-1837/com.example.androidhive D/﹕ HostConnection::get() New Host Connection established 0xa6c213a0, tid 1837
01-03 00:01:15.672    1837-2304/com.example.androidhive D/All Products:﹕ {"products":[{"pid":"1","firstname":"Kelvin","lastname":"Magtalas","username":"klvnsm024"},{"pid":"2","firstname":"Team","lastname":"Overnyt","username":"teamO"},{"pid":"3","firstname":"Rinni","lastname":"Pale","username":"Rino256"}],"success":1}
01-03 00:01:24.094    1837-1849/com.example.androidhive I/art﹕ Background sticky concurrent mark sweep GC freed 3700(188KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 5MB/5MB, paused 6.644ms total 88.620ms
01-03 00:01:24.828    1837-1837/com.example.androidhive I/Choreographer﹕ Skipped 144 frames!  The application may be doing too much work on its main thread.
01-03 00:25:05.893    2371-2371/com.example.androidhive D/﹕ HostConnection::get() New Host Connection established 0xae0fff30, tid 2371
01-03 00:25:08.891    2371-2371/com.example.androidhive I/Choreographer﹕ Skipped 46 frames!  The application may be doing too much work on its main thread.
01-03 00:25:37.424    2371-2371/com.example.androidhive D/InputEventConsistencyVerifier﹕ KeyEvent: ACTION_UP but key was not down.
    in android.widget.EditText{3e332cbb VFED..CL .F....ID 30,464-1050,608 #7f05000c app:id/login_passWord}
    0: sent at 1717943000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=1717943, downTime=1717815, deviceId=0, source=0x101 }
01-03 00:25:56.056    2371-2387/com.example.androidhive D/request!﹕ starting
01-03 00:25:56.647    2371-2371/com.example.androidhive I/Choreographer﹕ Skipped 34 frames!  The application may be doing too much work on its main thread.
01-03 00:25:57.443    2371-2387/com.example.androidhive E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
    --------- beginning of crash
01-03 00:25:57.462    2371-2387/com.example.androidhive E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.example.androidhive, PID: 2371
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
            at com.example.androidhive.Login$AttemptLogin.doInBackground(Login.java:122)
            at com.example.androidhive.Login$AttemptLogin.doInBackground(Login.java:86)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
01-03 00:42:06.320    2421-2421/com.example.androidhive D/﹕ HostConnection::get() New Host Connection established 0xae0bcf30, tid 2421
01-03 00:42:09.740    2421-2421/com.example.androidhive I/Choreographer﹕ Skipped 55 frames!  The application may be doing too much work on its main thread.
01-03 00:42:32.612    2421-2421/com.example.androidhive D/InputEventConsistencyVerifier﹕ KeyEvent: ACTION_UP but key was not down.
    in android.widget.EditText{3e332cbb VFED..CL .F....I. 30,464-1050,608 #7f05000c app:id/login_passWord}
    0: sent at 2732445000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=2732445, downTime=2732317, deviceId=0, source=0x101 }
01-03 00:42:57.603    2421-2437/com.example.androidhive D/request!﹕ starting
01-03 00:42:58.538    2421-2421/com.example.androidhive I/Choreographer﹕ Skipped 54 frames!  The application may be doing too much work on its main thread.
01-03 00:42:59.141    2421-2437/com.example.androidhive E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
01-03 00:42:59.142    2421-2437/com.example.androidhive E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.example.androidhive, PID: 2421
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
            at com.example.androidhive.Login$AttemptLogin.doInBackground(Login.java:122)
            at com.example.androidhive.Login$AttemptLogin.doInBackground(Login.java:86)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
01-03 00:43:03.759    2421-2421/com.example.androidhive E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.androidhive.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{2b062d20 V.E..... R.....I. 0,0-659,345} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:298)
            at com.example.androidhive.Login$AttemptLogin.onPreExecute(Login.java:100)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at com.example.androidhive.Login.onClick(Login.java:77)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
01-03 00:47:59.264    2421-2437/com.example.androidhive I/Process﹕ Sending signal. PID: 2421 SIG: 9
01-03 01:06:11.717    2641-2641/com.example.androidhive D/﹕ HostConnection::get() New Host Connection established 0xae0c5f80, tid 2641

01-03 01:06:15.531    2641-2641/com.example.androidhive I/Choreographer﹕ Skipped 64 frames!  The application may be doing too much work on its main thread.

hereis my check_user.php

<?php

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

if (isset($_POST["username"])) {
    $userName = $_POST["username"];
    //gets user's info based off of a username.
   /* $query = "SELECT 
                username, 
                password
            FROM bss_login 
            WHERE 
                username = :username 
        ";*/
        $query = "SELECT * FROM bss_login WHERE username = '$userName'";

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

    try {
        $stmt   = $db->prepare($query);   //here is line 23
        $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 {
        $response["success"] = 0;
        $response["message"] = "Require missing field(s)!";
        die(json_encode($response));
}

?>

Kindly help me out on this one. Thank you very much

As per your error messages:

01-03 00:25:57.443 2371-2387/com.example.androidhive E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject

<br><table is NOT JSON. Eg your fetched data is html, not json. Since it's not JSON, the json parser barfs, and here we are...

Before using a url in android async task Check it with chrome Rest client to know the response

Your url returns an error......

Fatal error: Call to a member function prepare() on a non-object in /home/a9008981/public_html/android/check_user.php on line 23

The exception is because the result is not a valid json. So when the following line tries to convert your response to jsonObject It throws null pointer exception

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

PHP error resolved

    try {

            $stmt   = $db->prepare(SELECT * FROM bss_login WHERE username = :username');   //here is line 23

            // bind the paramaters 
            $stmt->bindParam(':username', $username, PDO::PARAM_STR);

            // execute the prepared statement 
            $stmt->execute();

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM