为什么在使用Room库插入数据库时​​出现异常?

时间:2019-03-21 19:05:19

标签: java android android-room

我已经使用Room库创建了本地数据库,以便在我的Android应用程序的users表中输入User信息。在活动类内部,我调用了UserDao的def setup @user = User.new(name: "Example User", email: "user@example,com") end 方法来插入用户数据。但是无论何时调用该方法,它都会引发addUser并导致应用程序崩溃。下面是我的代码:

createProfile.java:

IllegalStateException

User.java:

public class createProfile extends AppCompatActivity {    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_create_profile);
        }

        public void createProfileClick(View view)
        {
         //All variables initialized   
            new AsyncTask<String,Void,Void>()
            {
                @Override
                protected Void doInBackground(String... params) {
                    CourseLogDB courseLogDB = CourseLogDB.getInstance(getApplicationContext());
                    User user = new User();
                    user.setName(params[0]);
                    user.setUsername(params[1]);
                    user.setBatch(params[2]);
                    user.setPassword(params[3]);
                    user.setRoll_no(params[4]);
                    UserDao u = courseLogDB.userModel();
                    u.addUser(user); //exception is thrown at this line
                    Toast.makeText(getApplicationContext(),"profile created",Toast.LENGTH_SHORT).show();
                    return null;
                }
            }.execute(name.getText().toString(),username.getText().toString(),batch.getText().toString(),passwd.getText().toString(),roll_no.getText().toString());
            finish();
      }
    }

UserDao.java:

    @Entity(tableName = "users")
    public class User {
    @PrimaryKey(autoGenerate = true)
    private int id = 0;
    private String username;
    private String password;
    private String name;
    private String batch;
    private String roll_no;
    //getters and setters are also included

CourseLogDB.java

@Dao
public interface UserDao {
    @Insert
    void addUser(User users);
}

我的错误日志:

@Database(entities = {User.class},version = 1)
public abstract class CourseLogDB extends RoomDatabase {
    private static CourseLogDB instance;
    public abstract UserDao userModel();
    public static synchronized CourseLogDB getInstance(Context context)
    {
        if(instance==null)
        {
            instance = Room.databaseBuilder(context,CourseLogDB.class,"CourseLogDB").build();
        }
        return instance;
    }
}

0 个答案:

没有答案