This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am working on android project and getting null object refrence
DatabaseHelper class
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 class
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)
You did not initialize db in the methods insertPrescription() and saveMedicine() (like you did correctly in the other methods):
db = this.getWritableDatabase();
so db is null when you use it.
Related
I want to modify a field of a determinate id, in my case the field is notify_datetime.
But when I run the app and try to do that, the app crashes giving this error.
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.msnma.movienotifier, PID: 4047
android.database.sqlite.SQLiteException: no such column: notify_datetime (Sqlite code 1): , while compiling: UPDATE MovieTypeTable SET notify_datetime=? WHERE notify_datetime = ?, (OS error - 2:No such file or directory)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:910)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:521)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:603)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1856)
at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1799)
at com.example.msnma.movienotifier.database.MovieDatabase.updateNotifyDate(MovieDatabase.java:299)
at com.example.msnma.movienotifier.adapter.MoviesAdapter$9.onClick(MoviesAdapter.java:445)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
The method is called updateNotifyDate and should modify notify_datetime.
MovieDatabase.java
package com.example.msnma.movienotifier.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.msnma.movienotifier.MainActivity;
import com.example.msnma.movienotifier.databaseModel.MovieDBModel;
import com.example.msnma.movienotifier.databaseModel.TypeDBModel;
import com.example.msnma.movienotifier.mapper.MovieMapper;
import com.example.msnma.movienotifier.model.Movie;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class MovieDatabase extends SQLiteOpenHelper {
private static final String LOG = "DatabaseHelper";
private static final String DATABASE_NAME = "movieDatabase";
private static final int DATABASE_VERSION = 1;
//Table Names
private static final String TABLE_MOVIE = "MovieTable";
private static final String TABLE_TYPE = "TypeTable";
private static final String TABLE_MOVIE_TYPE = "MovieTypeTable";
//Table Fields
private static final String MOVIE_ID ="movie_id";
public static final String TITLE ="title";
private static final String OVERVIEW = "overview";
private static final String POSTER_URL = "posterUrl";
private static final String BACKDROP_URL = "backdropUrl";
private static final String TRAILER_URL = "trailerUrl";
private static final String RELEASE_DATE = "releaseDate";
private static final String RATING = "rating";
private static final String ADULT = "adult";
private static final String TYPE_ID = "type_id";
private static final String TYPE_DESCR = "type_descr";
private static final String MOVIE_TYPE_ID = "movie_type_id";
private static final String M_ID = "movie_id";
private static final String T_ID = "type_id";
private static final String notify_datetime = "notify_datetime";
// Table Create Statements
private static final String CREATE_TABLE_MOVIE = "CREATE TABLE "
+ TABLE_MOVIE + "(" + MOVIE_ID + " INTEGER PRIMARY KEY," + TITLE + " TEXT,"
+ OVERVIEW + " TEXT," + POSTER_URL + " TEXT," + BACKDROP_URL + " TEXT," + TRAILER_URL + " TEXT,"
+ RATING + " REAL," + ADULT + " INTEGER," + RELEASE_DATE + " DATETIME," + notify_datetime + " DATETIME" + ")";
// Tag table create statement
private static final String CREATE_TABLE_TYPE = "CREATE TABLE " + TABLE_TYPE
+ "(" + TYPE_ID + " INTEGER PRIMARY KEY," + TYPE_DESCR + " TEXT" + ")";
// todo_tag table create statement
private static final String CREATE_TABLE_MOVIE_TYPE = "CREATE TABLE "
+ TABLE_MOVIE_TYPE + "(" + MOVIE_TYPE_ID + " INTEGER PRIMARY KEY,"
+ M_ID + " INTEGER," + T_ID + " INTEGER" + ")";
static SQLiteDatabase database;
public MovieDatabase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
database = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_MOVIE);
db.execSQL(CREATE_TABLE_TYPE);
db.execSQL(CREATE_TABLE_MOVIE_TYPE);
insertType(db); //NOTA: questo va chiamato solo la prima volta che instanziamo il DB, AGGIUNGERE CONTROLLO!
//in teoria onCreate verrà chiamato solo la prima volta...
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TYPE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIE_TYPE);
// create new tables
onCreate(db);
}
//questa funzione serve solo per inserire casualmente dai suggested movies, alcuni notify e watched movies
public static void saveMoviesOnDB(List<Movie> movies, String type){
MovieDatabase db = MainActivity.getMovieDatabase();
MovieMapper mapper = new MovieMapper();
List<MovieDBModel> moviesDB = mapper.toMovieDBModelList(movies);
Integer typeId = 0;
int index = 0;
if(type.equals("notify")){
typeId = 1;
}else if(type.equals("watched")){
typeId = 2;
index = index+5;
}else{
//todo catch invalid type Id exception
}
for(int a = index; a<index+5; a++){
insertMovie(moviesDB.get(a), typeId, db);
}
}
//open the database, maybe not useful...
public MovieDatabase open() throws SQLException
{
database = getWritableDatabase();
return this;
}
// closing database
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
//CRUDs
public static void insertMovie(MovieDBModel movie, Integer typeId, MovieDatabase db) {
SQLiteDatabase database = db.getWritableDatabase();
if(checkMovieUniqueness(movie.getTitle(), db)) { //NON VOGLIO INSERIRE PIù VOLTE LO STESSO FILM
ContentValues values = new ContentValues();
values.put(TITLE, movie.getTitle());
values.put(OVERVIEW, movie.getOverview());
values.put(POSTER_URL, movie.getPosterUrl());
values.put(BACKDROP_URL, movie.getBackdropUrl());
values.put(TRAILER_URL, movie.getTrailerUrl());
values.put(RELEASE_DATE, movie.getReleaseDate().toString());
values.put(RATING, movie.getRating());
values.put(ADULT, movie.isAdult());
//inizio nuovo codice
if(typeId == 1) {
values.put(notify_datetime, movie.getNotifyDate().toString());
Log.i("TYPEID", "Siamo dentro");
}
//else values.putNull(NOTIFY_TIME_DATE);
//fine nuovo codice
// insert row
long movieId = database.insert(TABLE_MOVIE, null, values);
insertMovieType(movieId, typeId, db);
}
}
public static void insertMovieType(Long movieId, Integer typeId, MovieDatabase db){
SQLiteDatabase database = db.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(M_ID, movieId.intValue());
values.put(T_ID, typeId);
database.insert(TABLE_MOVIE_TYPE, null, values);
}
private void insertType(SQLiteDatabase db){
ContentValues descr1 = new ContentValues();
descr1.put(TYPE_DESCR, "NOTIFY");
ContentValues descr2 = new ContentValues();
descr2.put(TYPE_DESCR, "WATCHED");
// insert row
db.insert(TABLE_TYPE, null, descr1);
db.insert(TABLE_TYPE, null, descr2);
}
private TypeDBModel getTypeByTypeDescr(String typeDescr) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_TYPE + " WHERE "
+ TYPE_DESCR + " = " + typeDescr;
Log.e(LOG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
TypeDBModel td = new TypeDBModel();
td.setId(c.getInt(c.getColumnIndex(TYPE_ID)));
td.setDescription((c.getString(c.getColumnIndex(TYPE_DESCR))));
return td;
}
private static boolean checkMovieUniqueness(String movieTitle, MovieDatabase db) {
SQLiteDatabase database = db.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE + " WHERE "
+ TITLE + " = " + "'"+ movieTitle + "'";
Log.e(LOG, selectQuery);
Cursor c = database.rawQuery(selectQuery, null);
if(c.moveToFirst()){
c.close();
return false;
}else{
c.close();
return true;
}
}
public List<MovieDBModel> getAllMovieByType(String typeDescr) throws ParseException {
List<MovieDBModel> movies = new ArrayList<MovieDBModel>();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE + " mv, "
+ TABLE_TYPE + " type, " + TABLE_MOVIE_TYPE + " tmt WHERE type."
+ TYPE_DESCR + " = '" + typeDescr + "'" + " AND type." + TYPE_ID
+ " = " + "tmt." + T_ID + " AND mv." + MOVIE_ID + " = "
+ "tmt." + M_ID;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
MovieDBModel td = new MovieDBModel();
td.setId(c.getInt((c.getColumnIndex(MOVIE_ID))));
td.setTitle((c.getString(c.getColumnIndex(TITLE))));
td.setOverview(c.getString(c.getColumnIndex(OVERVIEW)));
td.setPosterUrl(c.getString((c.getColumnIndex(POSTER_URL))));
td.setBackdropUrl((c.getString(c.getColumnIndex(BACKDROP_URL))));
td.setTrailerUrl(c.getString(c.getColumnIndex(TRAILER_URL)));
String dateString =c.getString((c.getColumnIndex(RELEASE_DATE)));
Date date = sdf3.parse(dateString);
td.setReleaseDate(date);
td.setRating((c.getFloat(c.getColumnIndex(RATING))));
int adult = c.getInt(c.getColumnIndex(ADULT));
if(adult == 0){
td.setAdult(true); //NOT sure if is the contrary
}else{
td.setAdult(false);
}
//nuovo codice
String datenotifyString = c.getString(c.getColumnIndex(notify_datetime));
if(datenotifyString != null)
{
Date datenotify = sdf3.parse(datenotifyString);
td.setNotifyDate(datenotify);
}
//fine nuovo codice
movies.add(td);
} while (c.moveToNext());
}
return movies;
}
public void deleteMovie(long tado_id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_MOVIE, MOVIE_ID + " = ?",
new String[] { String.valueOf(tado_id) });
}
public void deleteMovieType(long tado_id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_MOVIE_TYPE, M_ID + " = ?",
new String[] { String.valueOf(tado_id) });
}
public int updateMovieType(long id, long tag_id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(T_ID, tag_id);
// updating row
return db.update(TABLE_MOVIE_TYPE, values, M_ID + " = ?",
new String[] { String.valueOf(id) });
}
//da sistemare.
public int updateNotifyDate(long id, Date datetime ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notify_datetime,datetime.toString());
// updating row
return db.update(TABLE_MOVIE_TYPE, values, notify_datetime + " = ?",
new String[] { String.valueOf(id) });
}
public boolean isEmpty() throws ParseException {
boolean isEmpty = false;
List<MovieDBModel> movie1 = getAllMovieByType("NOTIFY");
List<MovieDBModel> movie2 = getAllMovieByType("WATCHED");
if(movie1.isEmpty() && movie2.isEmpty()){
isEmpty = true;
}
return isEmpty;
}
public static List<MovieDBModel> getAllMovies() throws ParseException {
List<MovieDBModel> movies = new ArrayList<MovieDBModel>();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE;
Log.e(LOG, selectQuery);
SQLiteDatabase db = database;
Cursor c = db.rawQuery(selectQuery, null);
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
MovieDBModel td = new MovieDBModel();
td.setId(c.getInt((c.getColumnIndex(MOVIE_ID))));
td.setTitle((c.getString(c.getColumnIndex(TITLE))));
td.setOverview(c.getString(c.getColumnIndex(OVERVIEW)));
td.setPosterUrl(c.getString((c.getColumnIndex(POSTER_URL))));
td.setBackdropUrl((c.getString(c.getColumnIndex(BACKDROP_URL))));
td.setTrailerUrl(c.getString(c.getColumnIndex(TRAILER_URL)));
String dateString =c.getString((c.getColumnIndex(RELEASE_DATE)));
Date date = sdf3.parse(dateString);
td.setReleaseDate(date);
td.setRating((c.getFloat(c.getColumnIndex(RATING))));
int adult = c.getInt(c.getColumnIndex(ADULT));
if(adult == 0){
td.setAdult(true); //NOT sure if is the contrary
}else{
td.setAdult(false);
}
movies.add(td);
} while (c.moveToNext());
}
return movies;
}
}
In MoviesAdapter.java only piece that call updateNotifyDate:
MovieDatabase md = new MovieDatabase(context);
Log.i("IDMOVIE","ID:"+movies.get(position).getId());
md.updateNotifyDate(movies.get(position).getId(),datatime);
}
Why it doesn't work? What am I wrong?
You're attempting to update MovieTypeTable but your image suggests the notify_datetime is in MovieTable so it's throwing SQLiteException: no such column.
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 6 years ago.
Where I made mistake?
When I try to insert data into database, I get Toast message that I inserter,but in LOG file i see error:
no such table: reservation (code 1): , while compiling: INSERT INTO reservation(phone,address,surname,name,start,destination) VALUES (?,?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
DBHelper.java
package com.example.demir.carsharing;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.TextView;
public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "carsharing.db";
public static final int DB_VERSION = 1;
public static final String USER_TABLE = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASS = "password";
public static final String RES_TABLE="reservation";
public static final String COLUMN_NAME="name";
public static final String COLUMN_SURNAME="surname";
public static final String COLUMN_ADDRESS="address";
public static final String COLUMN_PHONE="phone";
public static final String COLUMN_START="start";
public static final String COLUMN_DESTINATION="destination";
/*
create table users(
id integer primary key autoincrement,
email text,
password text);
*/
public static final String CREATE_TABLE_USERS = "CREATE TABLE " + USER_TABLE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_EMAIL + " TEXT,"
+ COLUMN_PASS + " TEXT);";
public static final String CREATE_TABLE_RESERVATION = "CREATE TABLE " + RES_TABLE + "("
+ COLUMN_NAME + " TEXT,"
+ COLUMN_SURNAME + " TEXT,"
+ COLUMN_ADDRESS + " TEXT,"
+ COLUMN_PHONE + " TEXT,"
+ COLUMN_START + " TEXT,"
+ COLUMN_DESTINATION + " TEXT);";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USERS);
db.execSQL(CREATE_TABLE_RESERVATION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST" + USER_TABLE);
onCreate(db);
db.execSQL("DROP TABLE IF EXIST" + RES_TABLE);
onCreate(db);
}
public void addUser(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_EMAIL, email);
values.put(COLUMN_PASS, password);
long id = db.insert(USER_TABLE, null, values);
db.close();
Log.d(TAG, "user inserted" + id);
}
public boolean getUser(String email, String pass) {
//HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "select * from " + USER_TABLE + " where " +
COLUMN_EMAIL + " = " + "'" + email + "'" + " and " + COLUMN_PASS + " = " + "'" + pass + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
// method for inserting data from method reservation
public void addReservation(String name, String surname, String address, String phone, String start, String destination) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_SURNAME, surname);
values.put(COLUMN_ADDRESS, address);
values.put(COLUMN_PHONE, phone);
values.put(COLUMN_START, start);
values.put(COLUMN_DESTINATION, destination);
long a = db.insert(RES_TABLE, null, values);
db.close();
Log.e(TAG, "Data insetred" + a);
}
//Get data from Reservation
public boolean getData(String name, String surname, String address, String phone, String start, String destination) {
String query = "select * from " + RES_TABLE + " where " +
COLUMN_NAME + " = " + "'" + name + "'" + " , " + COLUMN_SURNAME + " = " + "'" + surname + "'" +
COLUMN_ADDRESS + " = " + "'" + address + "'" + " , " + COLUMN_PHONE + " = " + "'" + phone + "'" +
COLUMN_START + " = " + "'" + start + "'" + " , " + COLUMN_DESTINATION + " = " + "'" + destination + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
//insert data iinto Reservation
public boolean insertReservation(String name, String surname, String address, String phone, String start, String destination) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name",name);
contentValues.put("surname",surname);
contentValues.put("address",address);
contentValues.put("phone",phone);
contentValues.put("start",start);
contentValues.put("destination",destination);
db.insert("reservation",null,contentValues);
return true;
}
}
Reservation.java
package com.example.demir.carsharing;
import android.content.Intent;
import android.database.SQLException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static com.example.demir.carsharing.R.id.etName;
public class ReservationActivity extends AppCompatActivity {
private Button save;
private EditText name, surname, address, phone, start, destination;
private DbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
db = new DbHelper(this);
name = (EditText) findViewById(etName);
surname = (EditText) findViewById(R.id.etSurname);
address = (EditText) findViewById(R.id.etAddress);
phone = (EditText) findViewById(R.id.etPhone);
start = (EditText) findViewById(R.id.etStart);
destination = (EditText) findViewById(R.id.etDestination);
save = (Button) findViewById(R.id.btnSave);
AddData();
}
public void AddData(){
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = db.insertReservation(name.getText().toString(),
surname.getText().toString(),
address.getText().toString(),
phone.getText().toString(),
start.getText().toString(),
destination.getText().toString());
if(isInserted==true)
Toast.makeText(ReservationActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(ReservationActivity.this,"Data not inserted",Toast.LENGTH_LONG).show();
}
});
}
}
You might have made changes to your helper class after creating the tables for the first time, in which case you must clear your app's data before you rerun, in your device/emulator go to App Info and the Clear Data "for >= Marshmallow go to App Info -> Storage -> Clear Data"
You don't have to delete and reinstall the whole app. that would be a waste of time.
Thank for reading my inquiry. I know this question has been asked before but I didn't find the answer I was looking for in the other responses. I hope I will ask the right question.
this code is for my DataBase Handler.
It houses all the methods that pertain to it, such as creating the table, adding and deleting entries and printing the database in my app.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class EmailDBHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "loginEntries.db";
public static final String TABLE_LOGINENTRIES = "loginEntries";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NICKNAME = "nickname";
public static final String COLUMN_EMAILADDRESS = "emailAddress";
public static final String COLUMN_PASSWORD = "password";
public static final String COLUMN_LASTNAME = "lastName";
public static final String COLUMN_FIRSTNAME = "firstName";
public EmailDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_LOGINENTRIES + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NICKNAME + " TEXT, " +
COLUMN_EMAILADDRESS + " TEXT, " +
COLUMN_PASSWORD + " TEXT, " +
COLUMN_LASTNAME + " TEXT, " +
COLUMN_FIRSTNAME + " TEXT " +
/*COLUMN_PHONENUMBER + " INTEGER " +*/
");";
db.execSQL(query);
String queryTwo = "INSERT INTO " + TABLE_LOGINENTRIES +
" (" + COLUMN_EMAILADDRESS + ", " +
COLUMN_NICKNAME + ", " +
COLUMN_PASSWORD + ", " +
COLUMN_FIRSTNAME + ", " +
COLUMN_LASTNAME + " " +
/* COLUMN_PHONENUMBER +*/ ")" + " VALUES " + " (\'email address\', \'nickname\', \'password\', \' First Name\', \'Last Name \');";
db.execSQL(queryTwo);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGINENTRIES);
onCreate(db);
}
public String logInCheck(String loginEmailEntry){
//used to find email and password in the database to compare to entered entries to confirm user
String passwordHolder;
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT " + COLUMN_PASSWORD + " FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_EMAILADDRESS + "=\"" + loginEmailEntry + "\"";
Cursor c = db.rawQuery(query, null);
passwordHolder = c.getString(c.getColumnIndex(COLUMN_PASSWORD));
db.close();
c.close();
return passwordHolder;
}
public boolean signUpEmailCheck(String emailEntry){
//checks if a new email entry already exists in the database
Integer holder;
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_EMAILADDRESS + "=\"" + emailEntry + "\"";
Cursor c = db.rawQuery(query,null);
holder = c.getColumnCount();
if (holder > 0) {
db.close();
c.close();
return true;
} else {
db.close();
c.close();
return false;
}
}
//add new row to Database
public void addEntry(LoginEntries entry){
ContentValues values = new ContentValues();
values.put(COLUMN_EMAILADDRESS,entry.get_emailAddress());
values.put(COLUMN_PASSWORD,entry.get_password());
values.put(COLUMN_FIRSTNAME,entry.get_firstName());
values.put(COLUMN_LASTNAME,entry.get_lastName());
values.put(COLUMN_NICKNAME,entry.get_nickname());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_LOGINENTRIES, null, values);
db.close();
}
//delete items from database
public void deleteEmailEntry(String emailEntry){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_EMAILADDRESS + "=\"" +
emailEntry + "\";");
}
public void deleteNickname(String nicknameEntry){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_NICKNAME + "=\"" +
nicknameEntry + "\";");
}
public void deletePasswordEntry(String passwordEntry){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_PASSWORD + "=\"" +
passwordEntry + "\";");
}
public void deleteLastNameEntry(String lastNameEntry){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_LASTNAME + "=\"" +
lastNameEntry + "\";");
}
public void deleteFirstNameEntry(String FirstNameEntry){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LOGINENTRIES + " WHERE " + COLUMN_FIRSTNAME + "=\"" +
FirstNameEntry + "\";");
}
//Print database as a string
public String emailDatabaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE 1";
//cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(COLUMN_EMAILADDRESS)) !=null){
dbString += c.getString(c.getColumnIndex(COLUMN_EMAILADDRESS));
dbString += "\n";
}c.moveToNext();
}
db.close();
c.close();
return dbString;
}
public String passwordDatabaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE 1";
//cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(COLUMN_PASSWORD)) != null){
dbString += c.getString(c.getColumnIndex(COLUMN_PASSWORD));
dbString += "\n";
}
c.moveToNext();
}
db.close();
c.close();
return dbString;
}
public String firstNameDatabaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE 1";
//cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(COLUMN_FIRSTNAME)) != null){
dbString += c.getString(c.getColumnIndex(COLUMN_FIRSTNAME));
dbString += "\n";
}
c.moveToNext();
}
db.close();
c.close();
return dbString;
}
public String lastNameDatabaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE 1";
//cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(COLUMN_LASTNAME)) != null){
dbString += c.getString(c.getColumnIndex(COLUMN_LASTNAME));
dbString += "\n";
}
c.moveToNext();
}
db.close();
c.close();
return dbString;
}
public String nicknameDatabaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGINENTRIES + " WHERE 1";
//cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(COLUMN_NICKNAME)) != null){
dbString += c.getString(c.getColumnIndex(COLUMN_NICKNAME));
dbString += "\n";
}
c.moveToNext();
}
db.close();
c.close();
return dbString;
}
}
This class is my sign up class, where I input new data into my database. Most of the if statements dictate the user if they are entering data incorrectly.
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SignUpMainClass extends AppCompatActivity{
EditText newEmailAddressInput;
EditText newPasswordInput;
EditText confirmNewPasswordInput;
TextView newFirstNameInput;
TextView newLastNameInput;
TextView newNickname;
TextView displayNickname;
TextView displayEmail;
TextView displayPassword;
TextView displayFirstName;
TextView displayLastName;
// EditText newPhoneNumberInput;
EmailDBHandler dbHandler;
//SignUpWelcomeScreen inputEntry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_main);
newEmailAddressInput = (EditText) findViewById(R.id.newEmailAddressInput);
newPasswordInput = (EditText) findViewById(R.id.newPasswordInput);
confirmNewPasswordInput = (EditText) findViewById(R.id.confirmNewPasswordInput);
newFirstNameInput = (TextView) findViewById(R.id.newFirstNameInput);
newLastNameInput = (TextView) findViewById(R.id.newLastNameInput);
newNickname = (TextView) findViewById(R.id.newNickname);
dbHandler = new EmailDBHandler(this, null, null, 1);
Bundle nameData = getIntent().getExtras();
if(nameData == null){
return;
}
String newFirstNameMessage =nameData.getString("newFirstNameMessage");
String newLastNameMessage =nameData.getString("newLastNameMessage");
String newNicknameMessage =nameData.getString("newNicknameMessage");
newFirstNameInput.setText(newFirstNameMessage);
newLastNameInput.setText(newLastNameMessage);
newNickname.setText(newNicknameMessage);
}
public void registerAccount(View view) {
LoginEntries emailEntry = new LoginEntries(newEmailAddressInput.getText().toString(), "", "", "", "");
String isTempEmail = newEmailAddressInput.getText().toString();
LoginEntries passwordEntry = new LoginEntries("", newPasswordInput.getText().toString(), "", "","");
String isTempPass = newPasswordInput.getText().toString();
String confirmPasswordHolder = confirmNewPasswordInput.getText().toString();
LoginEntries newFirstNameEntry = new LoginEntries("", "", newFirstNameInput.getText().toString(), "", "");
LoginEntries newLastNameEntry = new LoginEntries("", "", "", newLastNameInput.getText().toString(),"");
LoginEntries newNicknameEntry = new LoginEntries("", "", "", "", newNickname.getText().toString());
if (TextUtils.isEmpty(isTempEmail) && TextUtils.isEmpty(isTempPass)) {
Toast.makeText(this, "Enter Email and Password", Toast.LENGTH_LONG).show();
newEmailAddressInput.setText("");
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} else if (TextUtils.isEmpty(isTempEmail) && !TextUtils.isEmpty(isTempPass)) {
Toast.makeText(this, "Enter Email", Toast.LENGTH_LONG).show();
newEmailAddressInput.setText("");
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} else if (!TextUtils.isEmpty(isTempEmail) && TextUtils.isEmpty(isTempPass)) {
Toast.makeText(this, "Enter Password", Toast.LENGTH_LONG).show();
newEmailAddressInput.setText("");
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} /*Temporary while app is offline, when app will be operational, different prompt will search web to verify email address*/
else if (!isTempEmail.endsWith("#gmail.com") && !isTempEmail.endsWith("#yahoo.com") && !isTempEmail.endsWith("#aol.com") && !isTempEmail.endsWith("#hotmail.com")) {
Toast.makeText(this, "Not a valid email address, trying again", Toast.LENGTH_LONG).show();
newEmailAddressInput.setText("");
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} else if (!dbHandler.signUpEmailCheck(isTempEmail)) {
Toast.makeText(this, "Email used, please try again", Toast.LENGTH_LONG).show();
newEmailAddressInput.setText("");
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} else if (!confirmPasswordHolder.equals(isTempPass)) {
Toast.makeText(this, "Passwords don't match!", Toast.LENGTH_LONG).show();
newPasswordInput.setText("");
confirmNewPasswordInput.setText("");
} else{
Intent i = new Intent(this, SecondarySignUpClass.class);
String firstName = newFirstNameInput.getText().toString();
String lastName = newLastNameInput.getText().toString();
String nickname = newNickname.getText().toString();
i.putExtra("newFirstNameMessage",firstName);
i.putExtra("newLastNameMessage",lastName);
i.putExtra("newNicknameMessage", nickname);
startActivity(i);
Toast.makeText(this, "Saved!", Toast.LENGTH_LONG).show();
dbHandler.addEntry(emailEntry);// adds email to database
dbHandler.addEntry(passwordEntry);//adds password to database
dbHandler.addEntry(newFirstNameEntry);//adds First Name to database
dbHandler.addEntry(newLastNameEntry);//adds Last name to database
dbHandler.addEntry(newNicknameEntry);//adds Nickname to Database
printDatabase();
}
}
public void printDatabase(){
String dbEmailString = dbHandler.emailDatabaseToString();
String dbPasswordString = dbHandler.passwordDatabaseToString();
String dbFirstNameString = dbHandler.firstNameDatabaseToString();
String dbLastNameString = dbHandler.lastNameDatabaseToString();
String dbNicknameString= dbHandler.nicknameDatabaseToString();
displayEmail.setText(dbEmailString);
displayPassword.setText(dbPasswordString);
displayFirstName.setText(dbFirstNameString);
displayLastName.setText(dbLastNameString);
displayNickname.setText(dbNicknameString);
}
}
My input process is simple. It is meant to be a login in for a generic app, most likely a social app. User presses a sign up button, it takes him to the xml that the above class is attached to. The user puts in the data(first name, last name, email, password, nickname) and presses the Register button which is the associated with the Register account method. The information is then supposed to be entered into the database, from which I can later extract it. But it doesn't.
This is the error message I receive in my logcat when I try to extract data from the database. I assume that I missed something Small that plays a big part but I'm not sure what it is.
Process: com.example.vitaliy_2.emailpassworddatabasetrial, PID: 15139
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(App CompatViewInflater.java:275)
at android.view.View.performClick(View.java:5191)
at android.view.View$PerformClick.run(View.java:20916)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5972)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
at android.view.View.performClick(View.java:5191)
at android.view.View$PerformClick.run(View.java:20916)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5972)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.vitaliy_2.emailpassworddatabasetrial.SignUpMainClass.printDatabase(SignUpMainClass.java:165)
at com.example.vitaliy_2.emailpassworddatabasetrial.SignUpMainClass.registerAccount(SignUpMainClass.java:135)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
at android.view.View.performClick(View.java:5191)
at android.view.View$PerformClick.run(View.java:20916)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5972)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)at com.android.internal.os.Zygote
Init.main(ZygoteInit.java:1194)
Thank you for getting this far.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void android.widget.TextView.setText(java.lang.CharSequence)'
on a null object reference
TextView object is null .
At first you need to set all TextView id after setContentView(R.layout.signup_main);
displayNickname = (TextView) findViewById(R.id.Your_Id);
displayEmail = (TextView) findViewById(R.id.You_id);
.......// Call Rest of Textview //.............
Your display TextView objects don"t seem to have been initialized anywhere :
TextView displayNickname;
TextView displayEmail;
TextView displayPassword;
TextView displayFirstName;
TextView displayLastName;
I have encountered a problem while I was developing my Android application. I am trying to retrieve all the data from my Android application, but I don't exactly know how. Here is my DBAdapter.java class:
package com.example.foodsaver2;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.AvoidXfermode;
import android.util.Log;
import com.example.*;
public class DBAdapter {
public static final String KEY_ROWID = "rowid";
public static final String KEY_CUSTOMER = "customer";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_ADDRESS1 = "address1";
public static final String KEY_ADDRESS2 = "address2";
public static final String KEY_CITY = "city";
public static final String KEY_STATE = "state";
public static final String KEY_ZIP = "zipCode";
public static final String KEY_SEARCH = "searchData";
public static final String TOTAL_CARB = "carb";
public static final String FIBER = "fiber";
public static final String SUGAR = "sugar";
public static final String PROTEIN = "protein";
public static final String SODIUM = "salt";
public static final String TOTALCALORIES = "calories";
public static Context contextOfApplication;
private static final String TAG = "DBAdapter";
private DatabaseHelper mDbHelper;
public SQLiteDatabase mDb;
private static final String DATABASE_NAME = "Data";
private static final String FTS_VIRTUAL_TABLE = "Info";
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_CREATE1 =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3(" +
KEY_CUSTOMER + /*"INTEGER," + */ "," +
KEY_NAME + "," +
KEY_ADDRESS1 + "," +
KEY_ADDRESS2 + "," +
KEY_CITY + "," +
KEY_STATE + "," +
KEY_ZIP + "," +
KEY_SEARCH + "," +
TOTAL_CARB + "," +
FIBER + "," +
SUGAR + "," +
PROTEIN + "," +
SODIUM + "," +
TOTALCALORIES + "," +
" UNIQUE (" + KEY_CUSTOMER + "));";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE1);
db.execSQL(DATABASE_CREATE1);
}
public static Context getContextOfApplication(){
return contextOfApplication;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
}
public DBAdapter(Context ctx) {
this.mCtx = ctx;
}
public DBAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCustomer(String customer, String name, String address1, String address2, String city, String state, String zipCode, String carb, String fiber, String sugar, String protein, String sodium, String calories) {
ContentValues initialValues = new ContentValues();
String searchValue = customer + " " +
name + " " +
address1 + " " +
city + " " +
state + " " +
zipCode;
initialValues.put(KEY_CUSTOMER, customer);
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS1, address1);
initialValues.put(KEY_ADDRESS2, address2);
initialValues.put(KEY_CITY, city);
initialValues.put(KEY_STATE, state);
initialValues.put(KEY_ZIP, zipCode);
initialValues.put(KEY_SEARCH, searchValue);
initialValues.put(TOTAL_CARB, carb);
initialValues.put(FIBER, fiber);
initialValues.put(SUGAR, sugar);
initialValues.put(PROTEIN, protein);
initialValues.put(SODIUM, sodium);
initialValues.put(TOTALCALORIES, calories);
return mDb.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
public Cursor searchCustomer(String inputText) throws SQLException {
Log.w(TAG, inputText);
String query = "SELECT docid as _id," +
KEY_CUSTOMER + "," +
KEY_NAME + "," +
"(" + KEY_ADDRESS1 + "||" +
"(case when " + KEY_ADDRESS2 + "> '' then '\n' || " + KEY_ADDRESS2 + " else '' end)) as " + KEY_ADDRESS +"," +
KEY_ADDRESS1 + "," +
KEY_ADDRESS2 + "," +
KEY_CITY + "," +
KEY_STATE + "," +
KEY_ZIP + "," +
TOTAL_CARB + "," +
FIBER + "," +
SUGAR + "," +
PROTEIN + "," +
SODIUM + "," +
TOTALCALORIES +
" from " + FTS_VIRTUAL_TABLE +
" where " + KEY_SEARCH + " MATCH '" + inputText + "';";
Log.w(TAG, query);
Cursor mCursor = mDb.rawQuery(query,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean deleteAllCustomers() {
int doneDelete = 0;
doneDelete = mDb.delete(FTS_VIRTUAL_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
}
Here is my SendFeedback.java class, where I try to retrieve the data.
package com.example.foodsaver2;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/**
* Created by mother on 2/7/14.
*/
public class SendFeedback extends Activity {
private DBAdapter mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_feedback);
mDbHelper = new DBAdapter(this);
mDbHelper.open();
}
public void send (View v) {
Cursor c = mDbHelper.getData();
GmailSender sender = new GmailSender("omitted for privacy", "omitted for privacy");
try {
sender.sendMail("This is Subject",
"This is Body",
"omitted for privacy",
"omitted for privacy");
Toast.makeText(getApplicationContext(), "Sent!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Cannot send message!", Toast.LENGTH_SHORT).show();
}
}
}
I don't know how to do this. I have searched the internet and SO for a while, but I can't find a solution. I don't have any experience with SQLiteDatabases either. Any help regarding this problem is appreciated.
This is a good tutorial on sqlite databases on android:
http://www.vogella.com/tutorials/AndroidSQLite/article.html
take a look a this extract:
public List<Comment> getAllComments() {
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS, allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return comments;
}
And
private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
so for your app you could have:
public List getAllComments() {
List customers = new ArrayList();
Cursor cursor = database.query(FTS_VIRTUAL_TABLE, new String[]{"KEY_CUSTOMER", "KEY_NAME " , etc..}, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Customer customer = cursorToCustomer(cursor);
customers.add(comment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return customers;
}
And
private Customer cursorToCustomer(Cursor cursor) {
Customer customer = new Customer();
customer.setCustomer(cursor.getString(0));
customer.setName(cursor.getString(1));
customer.setAddress1(cursor.getString(2));
customer.setAddress2(cursor.getString(3));
customer.setCity(cursor.getString(4));
customer.setState(cursor.getString(5));
customer.setZipCode(cursor.getString(6));
customer.setSearchValue(cursor.getString(7));
customer.setCarb(cursor.getString(8));
customer.setFiber(cursor.getString(9));
customer.setSugar(cursor.getString(10));
customer.setProtein(cursor.getString(11));
customer.setSodium(cursor.getString(12));
customer.setCalories(cursor.getString(13));
return comment;
}
PS: You need to create your own class "Customer" to hold the data shown here
I am trying to insert rows into my database, but nothing gets persisted. Here is my helper class:
package com.android.cancertrials;
import java.util.Calendar;
import java.util.GregorianCalendar;
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{
public DataBaseHelper(Context context, String name) {
super(context, name, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
System.out.println("the database in onCreate: "+db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public void onOpen(SQLiteDatabase db) {
System.out.println("the database: "+db);
this.db=db;
super.onOpen(db);
}
public void insertRecordBean(RecordBean recordbean){
ContentValues content=new ContentValues();
content.put("TrialPhase", AdvanceSearchTab2.phaseOptions.toString());
content.put("TrialStatus", AdvanceSearchTab2.typeOptions.toString());
content.put("StudyType", AdvanceSearchTab2.statusOptions.toString());
content.put("ContactType", AdvanceSearchTab2.contactSpinner.toString());
content.put("MileRange", AdvanceSearchTab2.rangeSpinner.toString());
content.put("Location", AdvanceSearchTab2.locationSpinner.toString());
db.insert("tblClinicalTrial", null, content);
}
/*public void insertRecordResult(RecordBean recordbean){
ContentValues content1=new ContentValues();
content1.put("NCTID", recordbean.getNctId());
content1.put("Title", recordbean.getTitle());
content1.put("TrialPhase", recordbean.getTrialPhase());
content1.put("TrialStaus", recordbean.getTrialStatus());
content1.put("Summary", recordbean.getSummary());
content1.put("Conditions", recordbean.getConditions());
content1.put("Interventions", recordbean.getIntervention());
content1.put("Description", recordbean.getDescription());
content1.put("SponserName", recordbean.getSponsor());
content1.put("Inclusion", recordbean.getInclusionCriteria());
content1.put("Exclusion", recordbean.getExclusionCriteria());
content1.put("StudyPop", recordbean.getStudyPop());
content1.put("MinAge", recordbean.getMinimumAge());
content1.put("MaxAge", recordbean.getMaximumAge());
content1.put("Gender", recordbean.getGender());
content1.put("Hvolunteer", recordbean.getHealthyVolunteers());
content1.put("EnrollmentType", recordbean.getEnrollment());
content1.put("EnrollmentNum", recordbean.getEnrollment());
content1.put("VerifiedOn", recordbean.getVerifiedOn());
db.insert("tblResultItem", null, content1);
}*/
public void insertRecordBookmark(RecordBean recordbean){
ContentValues content2=new ContentValues();
content2.put("NCTID", recordbean.getNctId());
content2.put("Title", recordbean.getTitle());
content2.put("TrialPhase", recordbean.getTrialPhase());
content2.put("TrialStatus", recordbean.getTrialStatus());
content2.put("Summary", recordbean.getSummary());
content2.put("Conditions", recordbean.getConditions());
content2.put("Interventions", recordbean.getIntervention());
content2.put("Description", recordbean.getDescription());
content2.put("SponserName", recordbean.getSponsor());
content2.put("Inclusion", recordbean.getInclusionCriteria());
content2.put("Exclusion", recordbean.getExclusionCriteria());
content2.put("StudyPop", recordbean.getStudyPop());
content2.put("MinAge", recordbean.getMinimumAge());
content2.put("MaxAge", recordbean.getMaximumAge());
content2.put("Gender", recordbean.getGender());
content2.put("Hvolunteer", recordbean.getHealthyVolunteers());
content2.put("EnrollmentType", recordbean.getEnrollment());
content2.put("EnrollmentNum", recordbean.getEnrollment());
content2.put("VerifiedOn", recordbean.getVerifiedOn());
content2.put("UpdatedOn", recordbean.getUpdatedOn());
content2.put("LocationName", recordbean.getLocationName());
content2.put("LocationStatus", recordbean.getLocationStatus());
content2.put("City", recordbean.getCity());
content2.put("State", recordbean.getState());
content2.put("Country", recordbean.getCountry());
content2.put("Distance", recordbean.getLocationDist());
content2.put("Long", recordbean.getLongitude());
content2.put("lat", recordbean.getLatitude());
content2.put("Url", recordbean.getSourceUrl());
content2.put("Location_id", recordbean.getLocationId());
content2.put("Zip_code", recordbean.getZip());
db.insert("tblBookMarkItem", null, content2);
}
public Cursor getBookMarks(){
String[] columns={"_id","Title","Gender","TrialPhase","Zip_code","Location_id","NCTID"};
return db.query("tblBookMarkItem", columns, null, null, null, null, null);
}
public Cursor getRecent(){
String[] columns={"SearchString","ProfileDate","_id","years","Gender","TrialPhase","StudyType","TrialStatus","ContactType","MileRange","LocationZip","UrlParameter"};
return db.query("tblProfile", columns, null, null, null, null, null);
}
public void insertRecordProfile(String search,String url){
ContentValues content4=new ContentValues();
GregorianCalendar c=new GregorianCalendar();
content4.put("ProfileDate",c.get(GregorianCalendar.DATE)+"/"+(c.get(GregorianCalendar.MONTH)+1)+"/"+ c.get(GregorianCalendar.YEAR));
// content4.put("years", age);
//content3.put("ProfileType", AdvanceSearchTab2.typeOptions.toString());
//content4.put("months", AdvanceSearchTab1.ageEdit.getText().toString());
content4.put("SearchString", search);
// content4.put("Gender", gender);
// content4.put("TrialPhase", phase);
// content4.put("StudyType", study);
// content4.put("TrialStatus", status);
// content4.put("ContactType", contact);
// content4.put("MileRange", mile);
// content4.put("LocationZip", zip);
// //content4.put("searchString", AdvanceSearchTab1.edit_se.toString());
content4.put("UrlParameter", url);
db.insert("tblProfile", null, content4);
}
public void insertRecordMedical(RecordBean recordbean){
ContentValues content3=new ContentValues();
content3.put("years", AdvanceSearchTab1.ageEdit.toString());
content3.put("months", AdvanceSearchTab1.ageEdit.toString());
content3.put("searchString", AdvanceSearchTab1.edit_se.toString());
content3.put("Gender", AdvanceSearchTab1.hubSpinner.toString());
db.insert("tblMedicalProfile", null, content3);
}
public void deleteRecord(int id){
//_id=1;
db.delete("tblBookMarkItem", "_id="+id, null);
}
public void deleteRecent(int id){
//_id=1;
db.delete("tblProfile", "_id="+id, null);
}
private SQLiteDatabase db;
}
When I display it in my ListAdapter, it appears fine. As soon as I kill my application. My changes are not persisted. Why is this?
Where do you make your database? Also, you should be referencing aspects of your database with defined constants.
I don't see in your post where it is that you create your database. For example, in an app I have (link to the full file: http://code.devminded.com/score-it/src/56ac2292cfa3/src/com/devminded/scoreit/ScoreDbAdapter.java ) you can see my database class as such:
public class ScoreDbAdapter {
public static final String TAG = "com.devminded.scoreit.ScoreDbAdapter";
/**
* Keys for the player table. ID is incrementing value to
* reference the players.
*/
public static final String KEY_PLAYERS_ID = "_id";
public static final String KEY_PLAYERS_NAME = "name";
public static final String KEY_PLAYERS_ICON = "icon";
public static final String KEY_PLAYERS_SCORE = "score";
public static final String KEY_PLAYERS_ORDER = "turn";
/**
* Keys for the History table. Sequence is an increase value. Their order
* is the order the transactions were made.
*/
public static final String KEY_HISTORY_ID = "_id";
public static final String KEY_HISTORY_PLAYER = "player";
public static final String KEY_HISTORY_VALUE = "value";
public static final String KEY_HISTORY_NOTE = "note";
public static final String DATABASE_NAME = "scoreitdb";
public static final String TABLE_PLAYERS = "players";
public static final String TABLE_HISTORY = "history";
public static final String TRIGGER_UPDATE_NEW_SCORE = "update_new_score";
public static final String TRIGGER_UPDATE_SCORE = "update_score";
public static final String TRIGGER_DELETE_SCORE = "delete_score";
public static final String TRIGGER_DELETE_HISTORY = "delete_history";
public static final int DATABASE_VERSION = 25;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context mCtx;
private int mNumPlayers;
private static final String CREATE_TABLE_PLAYERS =
"create table " + TABLE_PLAYERS + " (" + KEY_PLAYERS_ID + " integer primary key autoincrement, "
+ KEY_PLAYERS_NAME + " text not null, " + KEY_PLAYERS_ICON + " long not null, " + KEY_PLAYERS_SCORE + " long not null, "
+ KEY_PLAYERS_ORDER + " long not null);";
private static final String CREATE_TABLE_HISTORY =
"create table " + TABLE_HISTORY + " (" + KEY_HISTORY_ID + " integer primary key autoincrement, "
+ KEY_HISTORY_PLAYER + " integer not null, " + KEY_HISTORY_NOTE + " text not null, "
+ KEY_HISTORY_VALUE + " integer not null);";
private static final String CREATE_TRIGGER_NEW_SCORE =
"create trigger " + TRIGGER_UPDATE_NEW_SCORE + " after insert on " + TABLE_HISTORY
+ " begin"
+ " update " + TABLE_PLAYERS + " set " + KEY_PLAYERS_SCORE + " = " + KEY_PLAYERS_SCORE + " + new." + KEY_HISTORY_VALUE + " where " + KEY_PLAYERS_ID + " = new. " + KEY_HISTORY_PLAYER + ";"
+ " end;";
private static final String CREATE_TRIGGER_UPDATE_SCORE =
"create trigger " + TRIGGER_UPDATE_SCORE + " after update on " + TABLE_HISTORY
+ " begin"
+ " update " + TABLE_PLAYERS + " set " + KEY_PLAYERS_SCORE + " = " + KEY_PLAYERS_SCORE + " + (new." + KEY_HISTORY_VALUE + " - old." + KEY_HISTORY_VALUE + ")"
+ " where " + KEY_PLAYERS_ID + " = new. " + KEY_HISTORY_PLAYER + ";"
+ " end;";
private static final String CREATE_TRIGGER_DELETE_SCORE =
"create trigger " + TRIGGER_DELETE_SCORE + " after delete on " + TABLE_HISTORY
+ " begin"
+ " update " + TABLE_PLAYERS + " set " + KEY_PLAYERS_SCORE + " = " + KEY_PLAYERS_SCORE + " - old." + KEY_HISTORY_VALUE
+ " where " + KEY_PLAYERS_ID + " = old." + KEY_HISTORY_PLAYER + ";"
+ " end;";
private static final String CREATE_TRIGGER_DELETE_HISTORY =
"create trigger " + TRIGGER_DELETE_HISTORY + " delete on " + TABLE_PLAYERS
+ " begin"
+ " delete from " + TABLE_HISTORY + " where " + KEY_HISTORY_PLAYER + " = old." + KEY_PLAYERS_ID + ";"
+ " end;";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PLAYERS);
db.execSQL(CREATE_TABLE_HISTORY);
db.execSQL(CREATE_TRIGGER_NEW_SCORE);
db.execSQL(CREATE_TRIGGER_DELETE_HISTORY);
db.execSQL(CREATE_TRIGGER_UPDATE_SCORE);
db.execSQL(CREATE_TRIGGER_DELETE_SCORE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TRIGGER IF EXISTS " + TRIGGER_DELETE_HISTORY);
db.execSQL("DROP TRIGGER IF EXISTS " + TRIGGER_UPDATE_NEW_SCORE);
db.execSQL("DROP TRIGGER IF EXISTS " + TRIGGER_UPDATE_SCORE);
db.execSQL("DROP TRIGGER IF EXISTS " + TRIGGER_DELETE_SCORE);
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PLAYERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
onCreate(db);
}
}
public ScoreDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public ScoreDbAdapter open() throws SQLException {
if (mDbHelper == null) {
mDbHelper = new DatabaseHelper(mCtx);
}
mDb = mDbHelper.getWritableDatabase();
countPlayers();
return this;
}
public void close() {
mDbHelper.close();
}
public long createPlayer(String name, int icon, long score) {
countPlayers();
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PLAYERS_NAME, name);
initialValues.put(KEY_PLAYERS_ICON, icon);
initialValues.put(KEY_PLAYERS_SCORE, score);
initialValues.put(KEY_PLAYERS_ORDER, mNumPlayers);
return mDb.insert(TABLE_PLAYERS, null, initialValues);
}
In create player you can see I am using the same functionality for adding that you are. I do not however see where you are creating the database. Can you present to us that similar functionality? Something is obviously amiss and we seem to be missing some aspect of the required information still.
Edit: Sorry, apparently my source somehow got a mixture of tabs and spaces in it, I guess I messed up an eclipse setting.