当我尝试在Room中插入元素时,为什么会有“空对象引用”异常?

时间:2019-08-21 15:25:24

标签: java android android-room

我正在尝试建立一个“联系人”会议室数据库,以了解是否可以将他们的对话保存在应用程序中以保存SMS对话,但是该数据库不起作用:当我想插入联系人时,该应用程序错误而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);
}

和contactrepository:

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工作...

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

@Database(entities = {Contact.class}, version = 1,exportSchema = false)
public abstract class ContactsDataBase  extends RoomDatabase {
private static ContactsDataBase INSTANCE;

public abstract ContactDAO showsDAO();
private static final Object sLock = new Object();

public static ContactsDataBase getInstance(Context context) {
    synchronized (sLock) {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                    ContactsDataBase.class, "contact.db")
                    .build();
        }
        return INSTANCE;
      }
   }
}

并将ContactRepository构造函数更改为以下

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