如何修复' null对象引用' Android Studio / SQLite中的错误?

时间:2016-12-09 04:38:33

标签: java android database sqlite nullpointerexception

我正在编写一个简单的社交媒体应用,但我在向用户数据库注册新用户时遇到了问题。点击"提交"在activity_register.xml页面上的按钮,我收到此错误:"尝试调用虚方法' void com.example.kame3531.tuuner.DatabaseHandler.createUser(java.lang.String,java.lang.String )'在null对象引用"。我该如何解决这个问题?

activity_register.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_register"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@drawable/grad"
    tools:context="com.example.kame3531.tuuner.RegisterActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Register"
        android:fontFamily="sans-serif-condensed"
        android:textColor="#ffffff"
        android:textSize="90sp"
        android:layout_marginTop="85dp"/>\

    <EditText
        android:id="@+id/username_register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/title"
        android:layout_marginTop="70dp"
        android:width="200dp"
        android:textAlignment="center"
        android:fontFamily="sans-serif-condensed"
        android:background="#5BC0EB"
        />

    <EditText
        android:id="@+id/password_register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/username_register"
        android:layout_marginTop="15dp"
        android:width="180dp"
        android:textAlignment="center"
        android:fontFamily="sans-serif-condensed"
        android:background="#5BC0EB"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/password_register"
        android:layout_marginTop="40dp"
        android:width="180dp"
        android:text="Submit"
        android:textSize="20dp"
        android:fontFamily="sans-serif-condensed"
        android:background="#9BC53D"
        android:onClick="registerUser"
        />

</RelativeLayout>

RegisterActivity.java:

package com.example.kame3531.tuuner;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
    }

    protected void registerUser(View view) {
        // validate the form
        EditText usernameField = (EditText) findViewById(R.id.username_register);
        EditText passwordField = (EditText) findViewById(R.id.password_register);
        String username = usernameField.getText().toString();
        String password = passwordField.getText().toString();

        try {
            UserHelper.CreateUser(username, password);
            setResult(Activity.RESULT_OK, getIntent());
            // close intent, if not, Toast error
            this.finish();
        } catch (Exception e) {
            // Toast the exception
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}

UserHelper.java:

package com.example.kame3531.tuuner;

import android.content.Context;

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

import static com.example.kame3531.tuuner.LoginActivity.logged_username;

public class UserHelper {

    public static List<String> usernames = new ArrayList<String>();
    public static List<String> passwords = new ArrayList<String>();

    public static DatabaseHandler db;

    public static void openDB(Context context) {
        if(db == null) {
            db = new DatabaseHandler(context);
        }
    }

    // Creates a user with some logic, or throws the error
    public static void CreateUser(String username, String password) throws Exception {
        if(username.length() <5) {
            throw new Exception("Username needs to be 5 chars long");
        } else if(password.length() < 4) {
            throw new Exception("Password needs to be 4 chars long");
        } else if(password.equals(username)) {
            throw new Exception("Password cannot be the username");
        }
        db.createUser(username, password);
    }

    public static boolean AuthenticateUser(String username, String password) {
        User user = db.getUserByName(username);
        if(user != null && user.password.equals(password)) {
            // set username as static
            logged_username = user.username;
            return true;
        }
        return false;
    }

}

DatabaseHandler.java:

package com.example.kame3531.tuuner;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

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

import static com.example.kame3531.tuuner.LoginActivity.user_id_static;

/**
 * Created by Deakyu on 11/4/2016.
 */

public class DatabaseHandler extends SQLiteOpenHelper {
    public DatabaseHandler(Context context) {
        super(context, "Tuuner", null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // users table
        db.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "username TEXT, password TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public User getUserByName(String name) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM users WHERE username = '"
                + name + "'", null);
        if(cursor.moveToFirst()) {
            User user = new User(cursor.getString(1), cursor.getString(2));
            user_id_static = cursor.getInt(0);
            return user; // Found user
        }
        return null; // No user found
    }


    public void createUser(String username, String password) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("username", username);
        cv.put("password", password);

        // Write to database
        db.insert("users", null, cv);

        db.close();
    }
}

1 个答案:

答案 0 :(得分:0)

我不确定它会不会起作用, 在您的RegisterActivity中,在调用UserHelper.CreateUser(用户名,密码)之前调用UserHelper.openDB(this);

因此代码将是: -

try {       UserHelper.openDB(this)
            UserHelper.CreateUser(username, password);
            setResult(Activity.RESULT_OK, getIntent());
            // close intent, if not, Toast error
            this.finish();
        } catch (Exception e) {
            // Toast the exception
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }