如何修复 Android Studio / SQLite 中的“空对象引用”错误? [复制]

Posted

技术标签:

【中文标题】如何修复 Android Studio / SQLite 中的“空对象引用”错误? [复制]【英文标题】:How to fix 'null object reference' error in Android Studio / SQLite? [duplicate] 【发布时间】:2017-04-24 12:09:08 【问题描述】:

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

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_
    android:layout_
    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_
        android:layout_
        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_
        android:layout_
        android:layout_centerHorizontal="true"
        android:layout_below="@id/title"
        android:layout_marginTop="70dp"
        android:
        android:textAlignment="center"
        android:fontFamily="sans-serif-condensed"
        android:background="#5BC0EB"
        />

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

    <Button
        android:layout_
        android:layout_
        android:layout_centerHorizontal="true"
        android:layout_below="@id/password_register"
        android:layout_marginTop="40dp"
        android:
        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();
    

【问题讨论】:

您的提交按钮没有在 XML 布局文件中设置 android:id 属性。这对我来说似乎可能是错误的,尽管它可能不是您的错误背后的原因。 我没有看到 openDB 被调用。 【参考方案1】:

我不确定它是否有效, 在您的 RegisterActivity 调用 UserHelper.openDB(this) 之前调用 UserHelper.CreateUser(username, password);

因此代码将是:-

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

【讨论】:

以上是关于如何修复 Android Studio / SQLite 中的“空对象引用”错误? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

如何在android studio中修复CameraSource预览方向

如何使用 Android Studio 3.3 修复即时应用程序

ANDROID STUDIO:如何修复我的 ScrollView?

如何修复错误:从android studio运行时flutter中的processDebugMainManifest DEBUG

如何修复 Android Studio / SQLite 中的“空对象引用”错误? [复制]

如何修复 Android Studio 中的 React Native 应用程序错误?