Retrieving all data from database - java

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

Related

Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert [duplicate]

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.

Update a determinate field in a table

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.

SQLiteException: no such table Android Studio [duplicate]

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.

Inserting and updating data on multiple table on SQLite database

In my project, I created a SQLite database with using a class that extends SQLiteOpenHelper library in android to creating three tables in one database.
the problem is when in MainActivity class (comes below) I want to create and update a data row, instead of putting data in desired table, they saved only in "table3db" table and the other tables are still empty (I saw this condition with an application can browse SQLite databases), but I want to save each data in desired table. for example first and second data must be saved in first table and third must be in second table and fourth data integer must be save in third table.
what should I do to correct this problem??
for first step I created three Tables with below codes in DatabaseHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
private final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "db";
private static final int DATABASE_VERSION = 1;
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_VALUE = "value";
private static final String COLUMN_VALUE2 = "value2";
private static final String TABLE_NAME = "table1db";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
private static final String COLUMN_ID_2 = "_id";
private static final String COLUMN_NAME_2 = "name";
private static final String COLUMN_VALUE_2 = "value";
private static final String COLUMN_VALUE2_2 = "value2";
private static final String TABLE_NAME_2 = "table2db";
private static final String CREATE_TABLE_2 = "CREATE TABLE " + TABLE_NAME_2 + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME_2 + " INTEGER," +
COLUMN_VALUE_2 + " INTEGER," +
COLUMN_VALUE2_2 + " TEXT" +
");";
private static final String COLUMN_ID_3 = "_id";
private static final String COLUMN_NAME_3 = "name";
private static final String COLUMN_VALUE_3 = "value";
private static final String COLUMN_VALUE2_3 = "value2";
private static final String TABLE_NAME_3 = "table3db";
private static final String CREATE_TABLE_3 = "CREATE TABLE " + TABLE_NAME_3 + " (" +
COLUMN_ID_3 + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME_3 + " INTEGER," +
COLUMN_VALUE_3 + " INTEGER," +
COLUMN_VALUE2_3 + " TEXT" +
");";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_2);
Log.i(TAG, "editTexts Table created.");
db.execSQL(CREATE_TABLE);
Log.i(TAG, "Table created.");
db.execSQL(CREATE_TABLE_3);
Log.i(TAG, "Table created.");
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.i(TAG, "Object created.");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
newVersion=oldVersion+1;
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_2 + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_3 + ";");
onCreate(db);
}
public String getTableName(int tableNumber) {
String out="";
switch (tableNumber){
case 1:
out=TABLE_NAME;
case 2:
out=TABLE_NAME_2;
case 3:
out=TABLE_NAME_3;
}
return out;
}
public String getRowIdName(int tableNumber) {
String out="";
switch (tableNumber){
case 1:
out=COLUMN_ID;
case 2:
out=COLUMN_ID_2;
case 3:
out=COLUMN_ID_3;
}
return out;
}
}
Then I created this class to use DatabaseHelper class with following code by the name of DatabaseHandler
public class DatabaseHandler {
private final String TAG = "DatabaseHandler";
static final String NAME = "name";
static final String VALUE = "value";
static final String VALUE2 = "value2";
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
public DatabaseHandler(Context context) {
dbHelper = new DatabaseHelper(context);
Log.i(TAG, "DatabaseHelper Object created.");
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void insertCBox(int tableNumber, CBox checkBox) {
ContentValues cv = new ContentValues();
cv.put(NAME, checkBox.getName());
cv.put(VALUE, checkBox.getStatus());
cv.put(VALUE2, checkBox.getText());
database.insert(dbHelper.getTableName(tableNumber), NAME, cv);
Log.i(TAG, "Contact added successfully.");
}
public void deleteCheckBox(int tableNumber, int id) {
database.delete(dbHelper.getTableName(tableNumber), dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public void updateCheckBox(int tableNumber, int id,int name,int state, String text) {
ContentValues cv = new ContentValues();
cv.put(NAME, name);
cv.put(VALUE, state);
cv.put(VALUE2, text);
database.update(dbHelper.getTableName(tableNumber), cv, dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public CBox getCBox(int tableNumber, int id){
Log.i(TAG, "getCBOX started");
Cursor cursor = database.query(dbHelper.getTableName(tableNumber), null, null, null, null, null, null);
Log.i(TAG, "cursor query done");
cursor.moveToFirst();
cursor.moveToPosition(id-1);
Log.i(TAG, "cursor is here: "+ cursor.getPosition());
// cursor.moveToPosition(id--);
Log.i(TAG, "cursor moved to position successfully "+ id--);
CBox CBox = cursorToContact(cursor);
Log.i(TAG, "cursor to contact done");
cursor.close();
Log.i(TAG, "cursor closed");
return CBox;
}
public void clearTable(int tableNumber) {
database.delete(dbHelper.getTableName(tableNumber), null, null);
}
private CBox cursorToContact(Cursor cursor) {
CBox checkBox = new CBox();
Log.i(TAG, "cursor to contact > started");
checkBox.setId(cursor.getInt(0));
Log.i(TAG, "cursor to contact > getInt(0) done " + checkBox.getId());
checkBox.setName(cursor.getInt(1));
Log.i(TAG, "cursor to contact > getInt(1) done " + checkBox.getName());
checkBox.setStatus(cursor.getInt(2));
Log.i(TAG, "cursor to contact > getInt(2) done " + checkBox.getStatus());
checkBox.setText(cursor.getString(3));
Log.i(TAG, "cursor to contact > getString(3) done " + checkBox.getText());
return checkBox;
}
}
for 3rd step in my Mainactivity class I used following codes to use database and inserting and updating and saving data:
public class MainActivity extends Activity {
private DatabaseHandler dbHandler;
private static final int databaseTableNumber1=1;
private static final int databaseTableNumber2=2;
private static final int databaseTableNumber3=3;
private CBox cBox01;
private CBox cBox02;
private CBox cBox03;
private CBox cBox04;
private boolean firstRunPassed=false;
private SharedPreferences sharedperefs;
private String preferenceName = "Preferences";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.i(TAG, "On Create");
setContentView(R.layout.activity_main);
dbHandler = new DatabaseHandler(this);
final Button saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dbHandler.open();
int state;
String text;
CheckBox checkBox01= (CheckBox) findViewById(R.id.checkBox1);
if(checkBox01.isChecked()) state=1; else state=0;
dbHandler.updateCheckBox(databaseTableNumber1,1,R.id.checkBox1,state,"");
RadioGroup radioGroup01=(RadioGroup) findViewById(R.id.radioGroup1);
state= radioGroup01.getCheckedRadioButtonId();
dbHandler.updateCheckBox(databaseTableNumber1,2, R.id.radioGroup1, state,"");
EditText editText01=(EditText) findViewById(R.id.editText1);
text=editText01.getText().toString();
dbHandler.updateCheckBox(databaseTableNumber2,1, R.id.editText1,state,text);
ToggleButton toggleButton01 =(ToggleButton) findViewById(R.id.toggleButton1);
if(toggleButton01.isChecked()) state=1; else state=0;
dbHandler.updateCheckBox(databaseTableNumber3,1,R.id.toggleButton1,state,"");
dbHandler.close();
}
});
}
#Override
protected void onPause(){
super.onPause();
Log.i(TAG, "On Pause");
sharedperefs = getSharedPreferences(preferenceName, MODE_PRIVATE);
SharedPreferences.Editor editor =sharedperefs.edit();
firstRunPassed=true;
editor.putBoolean("firstRunPassed", firstRunPassed);
editor.commit();
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume");
sharedperefs=getSharedPreferences(preferenceName, MODE_PRIVATE);
firstRunPassed=sharedperefs.getBoolean("firstRunPassed", false);
dbHandler.open();
Log.i(TAG, "dbhandler opened");
if(firstRunPassed){
cBox01=new CBox();
cBox01=dbHandler.getCBox(databaseTableNumber1,1);
CheckBox checkBox01= (CheckBox) findViewById(R.id.checkBox1);
if(cBox01.getStatus()==1)
checkBox01.setChecked(true);
else
checkBox01.setChecked(false);
cBox02=new CBox();
cBox02=dbHandler.getCBox(databaseTableNumber1,2);
RadioGroup radioGroup01=(RadioGroup) findViewById(R.id.radioGroup1);
radioGroup01.check(cBox02.getStatus());
cBox03=new CBox();
cBox03=dbHandler.getCBox(databaseTableNumber2,4);
EditText editText01=(EditText) findViewById(R.id.editText1);
editText01.setText(cBox03.getText());
cBox04=new CBox();
cBox04=dbHandler.getCBox(databaseTableNumber3,1);
ToggleButton toggleButton01 =(ToggleButton) findViewById(R.id.toggleButton1);
if(cBox04.getStatus()==1)
toggleButton01.setChecked(true);
else
toggleButton01.setChecked(false);
} else {
cBox01 = new CBox(); cBox01.setId(1); cBox01.setName(R.id.checkBox1); cBox01.setStatus(0); cBox01.setText(""); dbHandler.insertCBox(databaseTableNumber1,cBox01);
cBox02 = new CBox(); cBox02.setId(2); cBox02.setName(R.id.radioGroup1); cBox02.setStatus(0); cBox02.setText(""); dbHandler.insertCBox(databaseTableNumber1,cBox02);
cBox03 = new CBox(); cBox03.setId(1); cBox03.setName(R.id.editText1); cBox03.setStatus(0); cBox03.setText("Start please"); dbHandler.insertCBox(databaseTableNumber2,cBox03);
cBox04 = new CBox(); cBox04.setId(1); cBox04.setName(R.id.toggleButton1); cBox04.setStatus(0); cBox04.setText(""); dbHandler.insertCBox(databaseTableNumber3,cBox04);
}
dbHandler.close();
Log.i(TAG, "dbhandler closed");
}
}
and the CBox is my last class, used for setting and getting data cells:
public class CBox {
private int id;
private int name;
private int Status;
private String text;
private String unit;
public long getId() {
return id;
}
public String getIdInString() {
return Long.toString(id);
}
public int getName() {
return name;
}
public int getStatus() {
return Status;
}
public String getText() {
return text;
}
public String getUnit() {
return unit;
}
public void setId(int id) {
this.id = id;
}
public void setName(int name) {
this.name = name;
}
public void setStatus(int status) {
this.Status = status;
}
public void setText(String text) {
this.text = text;
}
public void setUnit(String unit) {
this.unit = unit;
}
}
I did it at last. :D
I don't what was the problem but with changing the DatabaseHelper and Database Helperclass as below and changing input variable of functions used in this class to string, the problems had been eliminated.
here is the DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
private final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "database";
private static final int DATABASE_VERSION = 1;
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_VALUE = "value";
private static final String COLUMN_VALUE2 = "value2";
private static final String TABLE_NAME_1 = "table1db";
private static final String CREATE_TABLE_1 = "CREATE TABLE " + TABLE_NAME_1 + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
private static final String TABLE_NAME_2 = "table2db";
private static final String CREATE_TABLE_2 = "CREATE TABLE " + TABLE_NAME_2 + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
private static final String TABLE_NAME_3 = "table3db";
private static final String CREATE_TABLE_3 = "CREATE TABLE " + TABLE_NAME_3 + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_1); Log.i(TAG, "Table 1 created.");
db.execSQL(CREATE_TABLE_2); Log.i(TAG, "Table 2 created.");
db.execSQL(CREATE_TABLE_3); Log.i(TAG, "Table 3 created.");
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.i(TAG, "Object created.");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
newVersion=oldVersion+1;
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_1 + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_2 + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_3 + ";");
onCreate(db);
}
public String getTableName(String tableNumber) {
return tableNumber;
}
public String getRowIdName(String tableNumber) {
return COLUMN_ID;
}
}
and the Database Handler class:
public class DatabaseHandler {
private final String TAG = "DatabaseHandler";
static final String NAME = "name";
static final String VALUE = "value";
static final String VALUE2 = "value2";
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
public DatabaseHandler(Context context) {
dbHelper = new DatabaseHelper(context);
Log.i(TAG, "DatabaseHelper Object created.");
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void insertCBox(String tableNumber, CBox checkBox) {
ContentValues cv = new ContentValues();
cv.put(NAME, checkBox.getName());
cv.put(VALUE, checkBox.getStatus());
cv.put(VALUE2, checkBox.getText());
database.insert(dbHelper.getTableName(tableNumber), null, cv);
Log.i(TAG, "Contact added successfully.");
}
public void deleteCheckBox(String tableNumber, int id) {
database.delete(dbHelper.getTableName(tableNumber), dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public void updateCheckBox(String tableNumber, int id,int name,int state, String text) {
ContentValues cv = new ContentValues();
cv.put(NAME, name);
cv.put(VALUE, state);
cv.put(VALUE2, text);
database.update(dbHelper.getTableName(tableNumber), cv, dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public CBox getCBox(String tableNumber, int id){
Log.i(TAG, "getCBOX started");
Cursor cursor = database.query(true,dbHelper.getTableName(tableNumber), null, null, null, null, null, null, null);
Log.i(TAG, "cursor query done");
cursor.moveToPosition(id-1);
Log.i(TAG, "cursor is here: "+ cursor.getPosition());
// cursor.moveToPosition(id--);
Log.i(TAG, "cursor moved to position successfully "+ (id-1));
CBox CBox = cursorToContact(cursor);
Log.i(TAG, "cursor to contact done");
cursor.close();
Log.i(TAG, "cursor closed");
return CBox;
}
public void clearTable(String tableNumber) {
database.delete(dbHelper.getTableName(tableNumber), null, null);
}
private CBox cursorToContact(Cursor cursor) {
CBox checkBox = new CBox();
Log.i(TAG, "cursor to contact > started");
checkBox.setId(cursor.getInt(0));
Log.i(TAG, "cursor to contact > getInt(0) done " + checkBox.getId());
checkBox.setName(cursor.getInt(1));
Log.i(TAG, "cursor to contact > getInt(1) done " + checkBox.getName());
checkBox.setStatus(cursor.getInt(2));
Log.i(TAG, "cursor to contact > getInt(2) done " + checkBox.getStatus());
checkBox.setText(cursor.getString(3));
Log.i(TAG, "cursor to contact > getString(3) done " + checkBox.getText());
return checkBox;
}
}

Problem inserting rows in SQLite database

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.

Categories