php - 安卓崩溃: nullpoint exception

标签 php android mysql

我正在尝试使用 PHP 和 MYSQL 为 Android 制作一个登录应用程序,但每当我启动它时它就会崩溃。我读过类似的问题,但我仍然无法查明错误

logcat 报告

09-25 15:34:07.722: E/AndroidRuntime(2515): FATAL EXCEPTION: main
09-25 15:34:07.722: E/AndroidRuntime(2515): Process: com.learn2crack.tab, PID: 2515
09-25 15:34:07.722: E/AndroidRuntime(2515): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.learn2crack.tab/com.learn2crack.tab.Login}: java.lang.NullPointerException
09-25 15:34:07.722: E/AndroidRuntime(2515):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at android.os.Handler.dispatchMessage(Handler.java:102)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at android.os.Looper.loop(Looper.java:136)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at android.app.ActivityThread.main(ActivityThread.java:5017)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at java.lang.reflect.Method.invokeNative(Native Method)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at java.lang.reflect.Method.invoke(Method.java:515)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at dalvik.system.NativeStart.main(Native Method)
09-25 15:34:07.722: E/AndroidRuntime(2515): Caused by: java.lang.NullPointerException
09-25 15:34:07.722: E/AndroidRuntime(2515):     at com.learn2crack.tab.Login.onCreate(Login.java:76)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at android.app.Activity.performCreate(Activity.java:5231)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-25 15:34:07.722: E/AndroidRuntime(2515):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

我的登录.java 包 com.learn2crack.tab;

public class Login extends Activity implements OnClickListener {

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

    // Progress Dialog
    private ProgressDialog pDialog;

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

    // php login script location:

    
    private static final String LOGIN_URL = "http://10.0.2.2/webservice/login.php";

    
    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.activity_login);

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

        // 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> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            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;
            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, MainActivity.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();
            }

        }

    }

}

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 
                    
                    username, 
                    password
                FROM accounts 
                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
    }
    
    ?> 

最佳答案

使用逐步执行,并检查您的资源。

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

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

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

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

}

在 OnCreate 上切换断点。

检查:

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

关于php - 安卓崩溃: nullpoint exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26046951/

相关文章:

php - Laravel:左连接查询

php - 从 PHP 回显 RTF 时获取换行符而不是斜杠-f-s

php - 从mysql数据库中绘制

mysql - 在 DispatcherServlet 中未找到名称为 'headway' 的 URI [/com.headway/save] 的 HTTP 请求的映射

php - SQL 不会从 php 获取所有传递的变量

php - 为什么对引用值调用函数(例如 strlen、count 等)如此慢?

android - 如何处理 Android 中的主页按钮

android - Firestore 作为离线持久性机制有多可靠?

android - 在 Android 中创建上下文菜单

php - 使用php的mysql结果获取比较