java - 当我尝试在 Room 中插入元素时,为什么会出现 "null object reference"异常?

标签 java android android-room

我正在尝试创建一个联系人的房间数据库,以了解我是否可以将他们的对话保存在应用程序中以保存短信对话,但数据库不想工作:当我想插入联系人时,应用程序错误logcat 告诉我:

2019-08-21 16:48:34.865 16177-16215/com.galinette.enregistreursms E/AndroidRuntime: FATAL EXCEPTION: pool-1-thread-1
    Process: com.galinette.enregistreursms, PID: 16177
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.galinette.enregistreursms.database.contactDao.insertContact(com.galinette.enregistreursms.model.Contact)' on a null object reference
        at com.galinette.enregistreursms.database.contactRepository.insertContact(contactRepository.java:32)
        at com.galinette.enregistreursms.database.contactRepository.putAllContactFirstTime(contactRepository.java:60)

那为什么呢?

我确信我的方法 Contact.getContacts() 因为我创建了一种方法将每个联系人的描述放入文本文件中并且它有效...

一、联系方式:

@Entity (tableName = "Contact")
public class Contact {
    @PrimaryKey (autoGenerate = true)
    private long id;
    private String phoneNumber;
    private String contactName;
    private boolean isSavable;

    public Contact(String contactName, String phoneNumber) {
        this.phoneNumber = phoneNumber;
        this.contactName = contactName;
        this.isSavable = false;
    }
 public static List<Contact> getContacts(Context ctx) {
        List<Contact> list = new ArrayList<>();
        ContentResolver contentResolver = ctx.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                    InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(ctx.getContentResolver(),
                            ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));

                    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
                    Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

                    Bitmap photo = null;
                    if (inputStream != null) {
                        photo = BitmapFactory.decodeStream(inputStream);
                    }
                    while (cursorInfo.moveToNext()) {
                        Contact info = new Contact(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)),
                                cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) );
                       // info.photo = photo;
                       // info.photoURI= pURI;
                        list.add(info);
                    }

                    cursorInfo.close();
                }
            }
            cursor.close();
        }
        return list;
    }

道:

@Dao
public interface contactDao {
    @Insert
    public void insertContact(Contact contact);

    @Query("SELECT * FROM Contact")
    LiveData<List<Contact>> getAllContacts();

    @Update
    void updateContact(Contact contact);

    @Delete
    void deleteContact(Contact contact);
}

和联系人存储库:

public class contactRepository {


    private contactDatabase db;
    private contactDao contactDao;


    public contactRepository (Context context){
        db = contactDatabase.getInstance(context);
    }

    public void insertContact (Contact contact) {
        contactDao.insertContact(contact);
    }

    public void updateContact (Contact  contact) {
        db.contactDao().updateContact(contact);
    }

    public LiveData<List<Contact>> getAllContacts(){
        return contactDao.getAllContacts();
    }

    public void deleteContact (Contact contact) {
        db.contactDao().deleteContact(contact);
    }

    public void updateAllContacts (List <Contact> contactList){
        for(int i = 0; i<=contactList.size(); i++){
            db.contactDao().insertContact(contactList.get(i));
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void putAllContactFirstTime(){
        List<Contact> contactList = Contact.getContacts(EnregistreurSMS.getAppContext());
        for(int i = 0; i<contactList.size();i++) {
            this.insertContact(contactList.get(i));
        }

}

...

我只是想让 dao 工作......

感谢您的帮助!

最佳答案

从您提供的代码来看,contactRepository 中的 contactDao 似乎尚未实例化。除非您调用类似 contactDao = new ContactDao() 的内容,否则它将为 null。

关于java - 当我尝试在 Room 中插入元素时,为什么会出现 "null object reference"异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57594886/

相关文章:

java - 尝试将变量添加到新对象时发生InvocationTargetException

android - shaperenderer 矩形上的 Libgdx 着色器

android - 获取 java.lang.RuntimeException : Failed to call observer method from binding implementation method

android - 如何将 Room 库的 @Ignore 注释与 Kotlin 紧凑构造函数语法一起使用?

android - 使用 COUNT(*) AS 的 Room SQL 查询

java - 不同的情况是否相互压倒?我的世界

java - 为什么 JFrame 输出与其 .paint 方法不同,以及如何解决这个问题?

java - 无法使用 web3j 下载以太坊 Activity

android - 当我生成签名的 apk 时,将错误的数据保存到 Firebase 数据库

安卓索引滚动