尝试调用虚拟方法'long android.database.sqlite.SQLiteDatabase.insert [重复]
Posted
技术标签:
【中文标题】尝试调用虚拟方法\'long android.database.sqlite.SQLiteDatabase.insert [重复]【英文标题】:Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert [duplicate]尝试调用虚拟方法'long android.database.sqlite.SQLiteDatabase.insert [重复] 【发布时间】:2019-11-20 04:32:21 【问题描述】:我正在开发 android 项目并获得空对象引用
DatabaseHelper 类
package com.example.smartpmr;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper
// DATABASE NAME
private static final String DATABASE_NAME = "PMR";
// DATABASE VERSION
private static final int DATABASE_VERSION = 1;
// PATIENT TABLE
private static final String TABLE_PATIENT = "tblPatient";
// DOCTOR TABLE
private static final String TABLE_DOCTOR = "tblDoctor";
// PRESCRIPTION TABLE
private static final String TABLE_PRESCRIPTION = "tblPrescription";
// MEDICINE TABLE
private static final String TABLE_MEDICINES = "tblMedicines";
// PATIENT TABLE COLUMNS
public static final String PATIENT_ID = "PATIENT_ID";
public static final String PATIENT_NAME = "PATIENT_NAME";
public static final String PATIENT_EMAIL = "PATIENT_EMAIL";
public static final String PATIENT_PASSWORD = "PATIENT_PASSWORD";
public static final String PATIENT_AGE = "PATIENT_AGE";
public static final String PATIENT_CONTACT = "PATIENT_CONTACT";
public static final String PATIENT_ADDRESS = "PATIENT_ADDRESS";
// DOCTOR TABLE COLUMS
public static final String DOCTOR_ID = "DOCTOR_ID";
public static final String DOCTOR_NAME = "DOCTOR_NAME";
public static final String DOCTOR_EMAIL = "DOCTOR_EMAIL";
public static final String DOCTOR_PASSWORD = "DOCTOR_PASSWORD";
public static final String DOCTOR_CONTACT = "DOCTOR_CONTACT";
public static final String DOCTOR_SPECIALIZATION = "DOCTOR_SPECIALIZATION";
// PRESCRIPTION TABLE COLUMS
public static final String PRESCRIPTION_ID = "PRESCRIPTION_ID";
public static final String FK_PATIENT_ID = "PATIENT_ID";
public static final String PRESCRIPTION_DOCTOR_ID = "DOCTOR_ID";
public static final String PRESCRIPTION_DOCTOR_NAME = "DOCTOR_NAME";
public static final String DIAGNOSIS = "DIAGNOSIS";
public static final String PRECAUTION = "PRECAUTION";
public static final String ISSUE_DATE = "ISSUE_DATE";
// MEDICINE TABLE COLUMS
public static final String MEDICINE_ID = "MEDICINE_ID";
public static final String FK_PRESCRIPTION_ID = "FK_PRESCRIPTION_ID";
public static final String MEDICINE_NAME = "MEDICINE_NAME";
public static final String MEDICINE_TYPE = "MEDICINE_TYPE";
public static final String MEDICINE_DOSE = "MEDICINE_DOSE";
public static final String START_DATE = "START_DATE";
public static final String END_DATE = "END_DATE";
// CREATING PATIENT TABLE IN DATABASE
String CreatePatientTable = " CREATE TABLE " + TABLE_PATIENT + " ( " + PATIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ PATIENT_NAME + " TEXT , " + PATIENT_EMAIL + " TEXT , " + PATIENT_PASSWORD + " TEXT , " + PATIENT_AGE + " TEXT , "
+ PATIENT_CONTACT + " TEXT , " + PATIENT_ADDRESS + " TEXT ); ";
// CREATING DOCTOR TABLE IN DATABASE
String CreateDoctorTable = " CREATE TABLE " + TABLE_DOCTOR + " ( " + DOCTOR_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ DOCTOR_NAME + " TEXT , " + DOCTOR_EMAIL + " TEXT , " + DOCTOR_PASSWORD + " TEXT , " + DOCTOR_CONTACT + " TEXT ,"
+ DOCTOR_SPECIALIZATION + " TEXT ); ";
// CREATING PRESCRIPTION TABLES IN DATABASE
String CreatePrescriptionTable = " CREATE TABLE " + TABLE_PRESCRIPTION + " ( " + PRESCRIPTION_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , " +
FK_PATIENT_ID + " TEXT , " + " FOREIGN KEY ( " + FK_PATIENT_ID + ") REFERENCES " + TABLE_PATIENT + " ( " + PATIENT_ID + ")"
+ PRESCRIPTION_DOCTOR_ID + " TEXT , " + PRESCRIPTION_DOCTOR_NAME + " TEXT , " + DIAGNOSIS + " TEXT , " +
PRECAUTION + " TEXT , " + ISSUE_DATE + " TEXT );";
// CREATING MEDICINE TABLE IN DATABASE
String CreateMedicineTabel = " CREATE TABLE " + TABLE_MEDICINES + " ( " + MEDICINE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , " +
MEDICINE_NAME + " TEXT , " + MEDICINE_TYPE + " TEXT , " + MEDICINE_DOSE + " TEXT , " +
START_DATE + " TEXT , " + END_DATE + " TEXT , " + FK_PRESCRIPTION_ID + " INTEGER , " +
" FOREIGN KEY ( " + FK_PRESCRIPTION_ID + " ) REFERENCES " + TABLE_PRESCRIPTION + " ( " + PRESCRIPTION_ID + "));";
SQLiteDatabase db;
public DataBaseHelper(Context context)
super(context, DATABASE_NAME, null, DATABASE_VERSION);
@Override
public void onCreate(SQLiteDatabase db)
db.execSQL(CreatePatientTable);
db.execSQL(CreateDoctorTable);
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
db.execSQL(CreatePrescriptionTable);
db.execSQL(CreateMedicineTabel);
// METHOD FOR CHECKING IF EMAIL EXISTS OR NOT
public boolean CheckPatientMail(String patientEmail)
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(" SELECT * FROM " + TABLE_PATIENT + " WHERE " + PATIENT_EMAIL + " = ? ", new String[] patientEmail);
if(cursor.getCount() > 0) return false;
else return true;
// METHOD FOR REGISTER PATIENT
public boolean RegisterPatient(String patientName, String patientEmail, String patientPassword, String patientAge, String patientContact, String patientAddress)
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(PATIENT_NAME,patientName);
contentValues.put(PATIENT_EMAIL,patientEmail);
contentValues.put(PATIENT_PASSWORD,patientPassword);
contentValues.put(PATIENT_AGE,patientAge);
contentValues.put(PATIENT_CONTACT,patientContact);
contentValues.put(PATIENT_ADDRESS,patientAddress);
long insert = db.insert(TABLE_PATIENT,null,contentValues);
if(insert == -1 ) return false;
else return true;
// This getdata() method will be deleted later #reminder
public String getdata()
db = this.getReadableDatabase();
String[] Columns = PATIENT_ID,PATIENT_NAME,PATIENT_EMAIL,PATIENT_PASSWORD,PATIENT_AGE,PATIENT_CONTACT,PATIENT_ADDRESS;
Cursor cursor = db.query(TABLE_PATIENT,Columns,null,null,null,null,null);
String result = "";
int iRow = cursor.getColumnIndex(PATIENT_ID);
int ifname = cursor.getColumnIndex(PATIENT_NAME);
int imail = cursor.getColumnIndex(PATIENT_EMAIL);
int ipass = cursor.getColumnIndex(PATIENT_PASSWORD);
int iage = cursor.getColumnIndex(PATIENT_AGE);
int icontact = cursor.getColumnIndex(PATIENT_CONTACT);
int iaddress = cursor.getColumnIndex(PATIENT_ADDRESS);
for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext())
result = result + cursor.getString(iRow) + " \n " + cursor.getString(ifname) +
" \n " + cursor.getString(imail) + " \n " + cursor.getString(ipass) + " \n "
+ cursor.getString(iage) + " \n " + cursor.getString(icontact) +
" \n " + cursor.getString(iaddress) + "\n";
return result;
// METHOD FOR PATIENT LOGIN
public boolean CheckPatientLogin(String patientMail, String patientPass)
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(" SELECT * FROM " + TABLE_PATIENT + " WHERE " + PATIENT_EMAIL + " = ? AND " +
PATIENT_PASSWORD + " = ? ", new String[] patientMail,patientPass );
if(cursor.getCount() > 0) return true;
else return false;
// METHOD FOR CHECK EXISTING DOCTOR EMAIL
public boolean CheckDoctorEmail(String doctorEmail)
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(" SELECT * FROM " + TABLE_DOCTOR + " WHERE " + DOCTOR_EMAIL + " = ? ", new String[]doctorEmail);
if(cursor.getCount()>0) return false;
else return true;
// METHOD FOR DOCTOR REGISTRATION
public boolean RegisterDoctor(String doctorName, String doctorEmail, String doctorPassword, String doctorContact, String doctorSpecialization)
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DOCTOR_NAME,doctorName);
contentValues.put(DOCTOR_EMAIL,doctorEmail);
contentValues.put(DOCTOR_PASSWORD,doctorPassword);
contentValues.put(DOCTOR_CONTACT,doctorContact);
contentValues.put(DOCTOR_SPECIALIZATION,doctorSpecialization);
long insert = db.insert(TABLE_DOCTOR,null,contentValues);
if(insert == -1 ) return false;
else return true;
// METHOD FOR DOCTOR LOGIN
public boolean CheckDoctorLogin(String doctorEmail, String doctorPassword)
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(" SELECT * FROM " + TABLE_DOCTOR + " WHERE " + DOCTOR_EMAIL + " = ? AND " +
DOCTOR_PASSWORD + " = ? ", new String[]doctorEmail,doctorPassword);
if(cursor.getCount()>0) return true;
else return false;
// METHOD FOR GETTING PATIENT NAME AND ID IN PATIENT PORTAL
public Cursor getPatientNameAndId(String mail,String pass)
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(" SELECT " + PATIENT_ID + " , " + PATIENT_NAME + " FROM " + TABLE_PATIENT + " WHERE " + PATIENT_EMAIL + " = ? AND "
+ PATIENT_PASSWORD + "= ?", new String[] mail,pass );
return cursor;
public boolean insertPrescription(String patientID, String docId, String docName, String diagnosis, String precaution, String issueDate)
ContentValues cv = new ContentValues();
cv.put(FK_PATIENT_ID,patientID);
cv.put(PRESCRIPTION_DOCTOR_ID,docId);
cv.put(PRESCRIPTION_DOCTOR_NAME,docName);
cv.put(DIAGNOSIS,diagnosis);
cv.put(PRECAUTION,precaution);
cv.put(ISSUE_DATE,issueDate);
long insert = db.insert(TABLE_PRESCRIPTION,null,cv);
if(insert == -1)return false;
else return true;
public int getPrescriptionId(String issueDate)
int id = 0;
Cursor cursor = db.rawQuery(" SELECT " + PRESCRIPTION_ID + " FROM " + TABLE_PRESCRIPTION + " WHERE " + ISSUE_DATE + " = ?" , new String[]issueDate);
if(cursor.moveToFirst())
do
id = cursor.getInt(cursor.getColumnIndex(PRESCRIPTION_ID));
while(cursor.moveToNext());
return id;
public boolean saveMedicine(String medName, String type, String dose, String startDate, String endDate, int prescriptionid)
ContentValues cv = new ContentValues();
cv.put(MEDICINE_NAME,medName);
cv.put(MEDICINE_TYPE,type);
cv.put(MEDICINE_DOSE,dose);
cv.put(START_DATE,startDate);
cv.put(END_DATE,endDate);
cv.put(FK_PRESCRIPTION_ID,prescriptionid);
long insert = db.insert(TABLE_MEDICINES,null,cv);
if(insert == -1) return false;
else return true;
add_medicine 类
package com.example.smartpmr;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
public class add_medicine extends AppCompatActivity implements DatePickerDialog.OnDateSetListener
// widgets for popup medicine dialog
Button saveMedicine,newMedicine;
EditText medname,edtdose;
EditText enddate,startdate;
Spinner med_type_spinner;
// widgets for prescription
Button btnaddMedicine;
EditText edtdoctorId,edtdoctorName,edtdiagnosis,edtprecaution;
TextView tvselectDate,tvpatientId;
String PatientID,medType;
String[] medTypes = "Select","Syrup","Injection","Tablet","Capsule";
int prescriptionId = -1;
boolean insertMedicine;
String medName;
String type;
String dose;
String startDate;
String endDate;
DataBaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_medicine);
db = new DataBaseHelper(this);
findViewsOfPrescriptionWidgets();
Intent it = getIntent();
PatientID = it.getStringExtra("id");
tvpatientId.setText(PatientID);
tvselectDate.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
showDatePickerDialog();
);
// Button for save prescription data and popout medicine dialog
btnaddMedicine.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
String docId = edtdoctorId.getText().toString();
String docName = edtdoctorName.getText().toString();
String diagnosis = edtdiagnosis.getText().toString();
String precaution = edtdiagnosis.getText().toString();
String issueDate = tvselectDate.getText().toString();
boolean addPrescription = false;
if(addPrescription == false)
addPrescription = db.insertPrescription(PatientID,docId,docName,diagnosis,precaution,issueDate);
if(addPrescription = true)
Toast.makeText(add_medicine.this, "Prescription Added", Toast.LENGTH_SHORT).show();
if(prescriptionId == -1 )
prescriptionId = db.getPrescriptionId(issueDate);
Toast.makeText(add_medicine.this, "prescription id " + prescriptionId , Toast.LENGTH_SHORT).show();
if(prescriptionId != -1)
popout_addmed();
);
private void showDatePickerDialog()
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
this,
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.show();
private void findViewsOfPrescriptionWidgets()
tvpatientId = (TextView)findViewById(R.id.pid);
edtdoctorId = (EditText)findViewById(R.id.docid);
edtdoctorName = (EditText)findViewById(R.id.docname);
edtdiagnosis = (EditText)findViewById(R.id.diagnosis);
edtprecaution = (EditText)findViewById(R.id.precaution);
btnaddMedicine=(Button)findViewById(R.id.btnaddmed);
tvselectDate = (TextView)findViewById(R.id.prescriptiondate);
// Method for show popout for medicies
public void popout_addmed()
AlertDialog.Builder builder=new AlertDialog.Builder(this);
View mview=getLayoutInflater().inflate(R.layout.diaglog_layout,null);
medname=(EditText) mview.findViewById(R.id.edtmedicine);
med_type_spinner=(Spinner)mview.findViewById(R.id.spinermedtype);
edtdose = (EditText)mview.findViewById(R.id.edtdosage);
startdate=(EditText) mview.findViewById(R.id.edtSTARTDATE);
enddate=(EditText) mview.findViewById(R.id.edtENDDATE);
saveMedicine = (Button)mview.findViewById(R.id.btnsavemed);
newMedicine = (Button)mview.findViewById(R.id.btnnewMedicine);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,medTypes);
med_type_spinner.setAdapter(adapter);
med_type_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
int index = med_type_spinner.getSelectedItemPosition();
medType = medTypes[index];
@Override
public void onNothingSelected(AdapterView<?> parent)
);
builder.setView(mview);
builder.show();
newMedicine.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
medName = medname.getText().toString();
type = medType;
dose = edtdose.getText().toString();
startDate = startdate.getText().toString();
endDate = enddate.getText().toString();
insertMedicine = db.saveMedicine(medName,type,dose,startDate,endDate,prescriptionId);
if(insertMedicine == true)
Toast.makeText(add_medicine.this, "medicine added", Toast.LENGTH_SHORT).show();
clearMedicineField();
);
saveMedicine.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
medName = medname.getText().toString();
type = medType;
dose = edtdose.getText().toString();
startDate = startdate.getText().toString();
endDate = enddate.getText().toString();
insertMedicine = db.saveMedicine(medName,type,dose,startDate,endDate,prescriptionId);
if(insertMedicine == true)
Toast.makeText(add_medicine.this, "medicine added", Toast.LENGTH_SHORT).show();
clearMedicineField();
);
private void clearMedicineField()
medname.getText().toString();
edtdose.getText().toString();
startdate.getText().toString();
enddate.getText().toString();
med_type_spinner.setSelection(0);
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
month = month+1;
String date = dayOfMonth + "/" + month + "/" + year;
tvselectDate.setText(date);
Logcat
2019-07-10 18:10:44.548 9933-9933/com.example.smartpmr I/zygote: Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/com.example.smartpmr-PSqLLORH7vlTbHptFqzWmQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.smartpmr-PSqLLORH7vlTbHptFqzWmQ==/lib/x86, /system/lib, /vendor/lib]]
2019-07-10 18:10:44.549 9933-9933/com.example.smartpmr I/zygote: Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/com.example.smartpmr-PSqLLORH7vlTbHptFqzWmQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.smartpmr-PSqLLORH7vlTbHptFqzWmQ==/lib/x86, /system/lib, /vendor/lib]]
2019-07-10 18:10:44.550 9933-9933/com.example.smartpmr I/zygote: Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/com.example.smartpmr-PSqLLORH7vlTbHptFqzWmQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.smartpmr-PSqLLORH7vlTbHptFqzWmQ==/lib/x86, /system/lib, /vendor/lib]]
2019-07-10 18:10:49.431 9933-9933/com.example.smartpmr I/AssistStructure: Flattened final assist data: 2460 bytes, containing 1 windows, 8 views
2019-07-10 18:10:54.149 9933-9938/com.example.smartpmr I/zygote: Do partial code cache collection, code=29KB, data=28KB
2019-07-10 18:10:54.150 9933-9938/com.example.smartpmr I/zygote: After code cache collection, code=29KB, data=28KB
2019-07-10 18:10:58.221 9933-9938/com.example.smartpmr I/zygote: Do partial code cache collection, code=61KB, data=57KB
2019-07-10 18:10:58.229 9933-9938/com.example.smartpmr I/zygote: After code cache collection, code=61KB, data=57KB
2019-07-10 18:11:03.936 9933-9938/com.example.smartpmr I/zygote: Do full code cache collection, code=123KB, data=99KB
2019-07-10 18:11:03.938 9933-9938/com.example.smartpmr I/zygote: After code cache collection, code=117KB, data=69KB
2019-07-10 18:11:08.364 9933-9938/com.example.smartpmr I/zygote: Do partial code cache collection, code=123KB, data=90KB
2019-07-10 18:11:08.365 9933-9938/com.example.smartpmr I/zygote: After code cache collection, code=123KB, data=90KB
2019-07-10 18:11:10.528 9933-9933/com.example.smartpmr I/AssistStructure: Flattened final assist data: 3092 bytes, containing 1 windows, 10 views
2019-07-10 18:11:12.289 9933-9933/com.example.smartpmr E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.smartpmr, PID: 9933
java.lang.NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String, java.lang.String, android.content.ContentValues)' on a null object reference
at com.example.smartpmr.DataBaseHelper.insertPrescription(DataBaseHelper.java:229)
at com.example.smartpmr.add_medicine$2.onClick(add_medicine.java:78)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
【问题讨论】:
【参考方案1】:您没有在 insertPrescription()
和 saveMedicine()
方法中初始化 db
(就像您在其他方法中所做的那样):
db = this.getWritableDatabase();
所以db
在你使用的时候是空的。
【讨论】:
以上是关于尝试调用虚拟方法'long android.database.sqlite.SQLiteDatabase.insert [重复]的主要内容,如果未能解决你的问题,请参考以下文章
ViewPager Andorid:NullPointerException: 尝试调用虚拟方法
NullPointerException:尝试在空对象引用上调用虚拟方法 findViewById(int)'
致命异常: main ,尝试在空对象引用上调用虚拟方法 [重复]