Java在从Room数据库查询用户时出现空指针异常

huangapple go评论74阅读模式
英文:

Java NullPointerException when querying user from Room database

问题

以下是翻译好的内容:

@Entity(tableName = "users")
public class UserEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private String username;
    private String password;
    private String email;
}

@Query("SELECT * FROM users WHERE username= :usr AND password= :pwd LIMIT 1")
LiveData<UserEntity> getuserLogin(String usr, String pwd);

public class UserEntity {
    // ...
    public UserEntity(int id, String username, String password, String email) {
        // ...
    }
    @Ignore
    public UserEntity(String username, String password, String email) {
        // ...
    }
    // ...
}

@Dao
public interface UserDao {
    @Query("SELECT * FROM users")
    LiveData<List<UserEntity>> getAll();
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertUser(UserEntity userEntity);
    @Update(onConflict = OnConflictStrategy.REPLACE)
    void updateUser(UserEntity userEntity);
    @Delete
    void deleteUser(UserEntity userEntity);
    @Query("DELETE FROM users")
    void deleteAll();
    @Query("SELECT * FROM users WHERE username= :usr AND password= :pwd LIMIT 1")
    LiveData<UserEntity> getuserLogin(String usr, String pwd);
}

public class UserRepositery {
    // ...
    public LiveData<List<UserEntity>> getAllusers() {
        return allusers;
    }
    LiveData<UserEntity> getuserLogin(String usr, String pwd) {
        return userDao.getuserLogin(usr, pwd);
    }
    // ...
}

public class UserViewModel extends AndroidViewModel {
    // ...
    LiveData<UserEntity> getuserLogin(String usr, String pwd) {
        return repositery.getuserLogin(usr, pwd);
    }
    // ...
}

public class MainActivity extends AppCompatActivity {
    // ...
    viewModel.getuserLogin(username, password).observe(this, new Observer<UserEntity>() {
        @Override
        public void onChanged(UserEntity userEntity) {
            user.setUsername(userEntity.getUsername());
            user.setEmail(userEntity.getEmail());
            user.setPassword(userEntity.getPassword());
        }
    });
    // ...
}

请注意,我已经根据你的要求进行了翻译,并删除了代码之外的所有内容。如果你需要进一步的帮助,请随时提问。

英文:

I am trying to handle a login
I have this Entity in my android project

@Entity(tableName = &quot;users&quot;)
public class UserEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private String username;
    private String password;
    private String email;
}

In the userDao

@Query(&quot;SELECT * FROM users WHERE username= :usr AND password= :pwd LIMIT 1&quot;)
LiveData &lt; UserEntity &gt; getuserLogin(String usr, String pwd);

I'm using an MVVM Architecture.
In my main view I have added an empty UserEntity user and observing the LiveData in the view model with the method LiveData&lt;UserEntity&gt; getuserLogin(String usr,String pwd), I set the empty user in the main view and compare it to the inputs every time the users click the button.

However every time I get NullPointerException.

This is the code:
UserEntity

import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;

import java.util.Date;

@Entity(tableName = &quot;users&quot;)
public class UserEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private String username;
    private String password;
    private String email;

    public UserEntity(int id, String username, String password, String email) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
    }
    @Ignore
    public UserEntity(String username, String password, String email) {
        this.username = username;
        this.password = password;
        this.email = email;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

UserDao

import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;

import java.util.List;

@Dao
public interface UserDao {
    @Query(&quot;SELECT * FROM users&quot;)
    LiveData &lt; List &lt; UserEntity &gt;&gt; getAll();
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertUser(UserEntity userEntity);
    @Update(onConflict = OnConflictStrategy.REPLACE)
    void updateUser(UserEntity userEntity);
    @Delete
    void deleteUser(UserEntity userEntity);
    @Query(&quot;DELETE FROM users&quot;)
    void deleteAll();
    @Query(&quot;SELECT * FROM users WHERE username= :usr AND password= :pwd LIMIT 1&quot;)
    LiveData &lt; UserEntity &gt; getuserLogin(String usr, String pwd);
}

UserRepository

import android.app.Application;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import java.util.List;

public class UserRepositery {
    private UserDao userDao;
    private LiveData &lt; List &lt; UserEntity &gt;&gt; allusers;

    public UserRepositery(Application application) {
        AppDatabase database = AppDatabase.getsInstance(application);

        this.userDao = database.userDao();
        this.allusers = userDao.getAll();
    }

    public void insert(UserEntity userEntity) {
        new insertUserAsyncTask(userDao).execute(userEntity);
    }

    public void update(UserEntity userEntity) {
        new updateUserAsyncTask(userDao).execute(userEntity);
    }

    public void deleteUser(UserEntity userEntity) {
        new deleteUserAsyncTask(userDao).execute(userEntity);
    }

    public void deleteAllUsers() {
        new deleteAllUserAsyncTask(userDao).execute();
    }

    public LiveData &lt; List &lt; UserEntity &gt;&gt; getAllusers() {
        return allusers;
    }
    LiveData &lt; UserEntity &gt; getuserLogin(String usr, String pwd) {
        return userDao.getuserLogin(usr, pwd);
    }

    public static class insertUserAsyncTask extends AsyncTask &lt; UserEntity, Void, Void &gt; {
        private UserDao userDao;

        public insertUserAsyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected Void doInBackground(UserEntity...userEntities) {
            userDao.insertUser(userEntities[0]);

            return null;
        }

    }

    public static class updateUserAsyncTask extends AsyncTask &lt; UserEntity, Void, Void &gt; {
        private UserDao userDao;

        public updateUserAsyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected Void doInBackground(UserEntity...userEntities) {
            userDao.updateUser(userEntities[0]);

            return null;
        }

    }

    public static class deleteUserAsyncTask extends AsyncTask &lt; UserEntity, Void, Void &gt; {
        private UserDao userDao;

        public deleteUserAsyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected Void doInBackground(UserEntity...userEntities) {
            userDao.deleteUser(userEntities[0]);

            return null;
        }

    }

    public static class deleteAllUserAsyncTask extends AsyncTask &lt; UserEntity, Void, Void &gt; {
        private UserDao userDao;

        public deleteAllUserAsyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected Void doInBackground(UserEntity...userEntities) {
            userDao.deleteAll();

            return null;
        }

    }
}

UserViewModel

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;

import java.util.List;

public class UserViewModel extends AndroidViewModel {
    private UserRepositery repositery;
    private LiveData &lt; List &lt; UserEntity &gt;&gt; allusers;


    public UserViewModel(@NonNull Application application) {
        super(application);
        this.repositery = new UserRepositery(application);
        this.allusers = repositery.getAllusers();
    }
    public void insert(UserEntity userEntity) {
        repositery.insert(userEntity);

    }
    LiveData &lt; UserEntity &gt; getuserLogin(String usr, String pwd) {
        return repositery.getuserLogin(usr, pwd);
    }
    public void update(UserEntity userEntity) {
        repositery.update(userEntity);
    }
    public void delete(UserEntity userEntity) {
        repositery.deleteUser(userEntity);
    }
    public void deleteAll() {
        repositery.getAllusers();
    }

    public LiveData &lt; List &lt; UserEntity &gt;&gt; getAllusers() {
        return allusers;
    }
}

MainActivity

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    Button login;
    Button register;
    EditText usinp;
    EditText passinp;
    UserViewModel viewModel;
    UserEntity user;
    List &lt; UserEntity &gt; allo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        usinp = (EditText) findViewById(R.id.user_inp);
        passinp = (EditText) findViewById(R.id.pass_inp);
        login = (Button) findViewById(R.id.login_but);

        register = (Button) findViewById(R.id.register_but);
        viewModel = ViewModelProviders.of(this).get(UserViewModel.class);
        //initializing an input to try something
        String username = &quot;user&quot;;
        String password = &quot;user&quot;;
        viewModel.getuserLogin(username, password).observe(this, new Observer &lt; UserEntity &gt; () {
            @Override
            public void onChanged(UserEntity userEntity) {
                user.setUsername(userEntity.getUsername());
                user.setEmail(userEntity.getEmail());
                user.setPassword(userEntity.getPassword());
            }
        });
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Comparing the inputs with user object and oppening other activity
            }
        });
    }
}

activity_main.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        tools:context=&quot;.MainActivity&quot;&gt;
    &lt;TextView
            android:id=&quot;@+id/textView2&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;Hello Please Sign in&quot;
            android:textAppearance=&quot;?android:attr/textAppearanceMedium&quot;
            android:textSize=&quot;32sp&quot;
            android:textStyle=&quot;bold&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintHorizontal_bias=&quot;0.496&quot;
            app:layout_constraintLeft_toLeftOf=&quot;parent&quot;
            app:layout_constraintRight_toRightOf=&quot;parent&quot;
            app:layout_constraintTop_toTopOf=&quot;parent&quot;
            app:layout_constraintVertical_bias=&quot;0.023&quot; /&gt;
    &lt;TextView
            android:id=&quot;@+id/textView&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_marginTop=&quot;69dp&quot;
            android:text=&quot;TextView&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintStart_toStartOf=&quot;@+id/textView2&quot;
            app:layout_constraintTop_toBottomOf=&quot;@+id/textView2&quot;
            app:layout_constraintVertical_bias=&quot;0.0&quot; /&gt;
    &lt;EditText
            android:id=&quot;@+id/user_inp&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_marginTop=&quot;9dp&quot;
            android:ems=&quot;10&quot;
            android:inputType=&quot;textPersonName&quot;
            android:text=&quot;aw&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toEndOf=&quot;parent&quot;
            app:layout_constraintHorizontal_bias=&quot;0.0&quot;
            app:layout_constraintStart_toStartOf=&quot;@+id/textView&quot;
            app:layout_constraintTop_toBottomOf=&quot;@+id/textView&quot;
            app:layout_constraintVertical_bias=&quot;0.0&quot; /&gt;
    &lt;TextView
            android:id=&quot;@+id/textView3&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_marginTop=&quot;220dp&quot;
            android:text=&quot;TextView&quot;
    
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toEndOf=&quot;parent&quot;
            app:layout_constraintHorizontal_bias=&quot;0.186&quot;
            app:layout_constraintStart_toStartOf=&quot;parent&quot;
            app:layout_constraintTop_toBottomOf=&quot;@+id/textView2&quot;
            app:layout_constraintVertical_bias=&quot;0.0&quot; /&gt;
    &lt;EditText
            android:id=&quot;@+id/pass_inp&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_marginTop=&quot;12dp&quot;
            android:ems=&quot;10&quot;
            android:inputType=&quot;textPassword&quot;
            android:text=&quot;aw&quot;
            app:layout_constraintStart_toStartOf=&quot;@+id/textView3&quot;
            app:layout_constraintTop_toBottomOf=&quot;@+id/textView3&quot; /&gt;
    &lt;Button
            android:id=&quot;@+id/login_but&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_marginTop=&quot;68dp&quot;
            android:text=&quot;Log in&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toEndOf=&quot;parent&quot;
            app:layout_constraintHorizontal_bias=&quot;0.383&quot;
            app:layout_constraintStart_toStartOf=&quot;parent&quot;
            app:layout_constraintTop_toBottomOf=&quot;@+id/pass_inp&quot;
            app:layout_constraintVertical_bias=&quot;0.33&quot; /&gt;
    &lt;Button
            android:id=&quot;@+id/register_but&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;Register&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toEndOf=&quot;@+id/login_but&quot;
            app:layout_constraintHorizontal_bias=&quot;0.0&quot;
            app:layout_constraintStart_toStartOf=&quot;@+id/login_but&quot;
            app:layout_constraintTop_toBottomOf=&quot;@+id/login_but&quot;
            app:layout_constraintVertical_bias=&quot;0.355&quot; /&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

Stack Trace

09-09 17:34:22.866 6085-6085/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example2.databse, PID: 6085
java.lang.NullPointerException
at com.example2.databse.MainActivity$1.onChanged(MainActivity.java:46)
at com.example2.databse.MainActivity$1.onChanged(MainActivity.java:43)
at androidx.lifecycle.LiveData.considerNotify(LiveData.java:131)
at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:149)
at androidx.lifecycle.LiveData.setValue(LiveData.java:307)
at androidx.lifecycle.LiveData$1.run(LiveData.java:91)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5426)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)

答案1

得分: -1

当然,这是空指针,因为这个类:

@Entity(tableName = "users")
public class UserEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private String username;
    private String password;
    private String email;

您需要像这样编辑:

@Entity(tableName = "users")
public class UserEntity {
    @ColumnInfo(name = "id")
    @PrimaryKey(autoGenerate = true)
    private int id;
    @ColumnInfo(name = "username")
    private String username;
    @ColumnInfo(name = "password")
    private String password;
    @ColumnInfo(name = "email")
    private String email;

您可以按照Google的这个教程进行操作:https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/#0

英文:

Of courese It's null pointer, because this class:

@Entity(tableName = &quot;users&quot;)
public class UserEntity {
@PrimaryKey(autoGenerate = true)
private int id;
private String username;
private String password;
private String email;

You must edit like this:

 @Entity(tableName = &quot;users&quot;)
public class UserEntity {
@ColumnInfo(name = &quot;id&quot;)
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = &quot;username&quot;)
private String username;
@ColumnInfo(name = &quot;password&quot;)
private String password;
@ColumnInfo(name = &quot;email&quot;)
private String email;

You can follow this tutorial of Google: https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/#0

huangapple
  • 本文由 发表于 2020年9月10日 00:07:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63815492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定