Problem inserting rows in SQLite database - java

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.

Related

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.

android.database.sqlite.SQLiteException near ")"

Can anyone see what is wrong with this code please, this is the error given:
Caused by: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE scores(_id INTEGER PRIMARY KEY AUTOINCREMENT , scoreName TEXT , );
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "scores.db";
public static final String TABLE_SCORES = "scores";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_SCORENAME = "scoreName";
public MyDBHandler(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_SCORES + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT " +
COLUMN_SCORENAME + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_SCORES);
onCreate(db);
}
public void addScore(Scores score) {
ContentValues values = new ContentValues();
values.put(COLUMN_SCORENAME, score.get_scoreName());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_SCORES, null, values);
db.close();
}
public void deleteScore(String scoreName) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_SCORES + "WHERE " + COLUMN_SCORENAME + "=\"" + scoreName + "\";");
}
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_SCORES + "WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//move to first row in your results
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("scoreName")) != null) {
dbString += c.getString(c.getColumnIndex("scoreName"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
Seems problem in Query for creating table (comma is missing after AUTOINCREMENT). Try this
db.execSQL("CREATE TABLE " + TABLE_SCORES + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_SCORENAME + " TEXT" + ");");

Android SQLite helper - where should I close the connection?

I wrote a simple database helper class to make access to the DB from multiple activities more clean.
Here's the class:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "name";
private static final String TABLE_SCORES = "scores";
private static final String KEY_ID = "id";
private static final String KEY_SCORE = "score";
private static final String KEY_DATE = "date";
SQLiteDatabase database;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
database = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase database) {
String CREATE_SCORES_TABLE = "CREATE TABLE " + TABLE_SCORES + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_SCORE + " INTEGER,"
+ KEY_DATE + " TEXT" + ")";
database.execSQL(CREATE_SCORES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES);
onCreate(database);
}
void addScore(int score){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy", Locale.US);
String currentDateandTime = dateFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(KEY_SCORE, score);
values.put(KEY_DATE, currentDateandTime);
database.insert(TABLE_SCORES, null, values);
//database.close();
}
void delete(){
database.delete(TABLE_SCORES, null, null);
}
public List<Score> getAllScores(){
List<Score> scoresList = new ArrayList<Score>();
String selectQuery = "SELECT * FROM " + TABLE_SCORES + " ORDER BY " + KEY_SCORE +" DESC LIMIT 10";
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
Score score = new Score();
score.setId(Integer.parseInt(cursor.getString(0)));
score.setScore(Integer.parseInt(cursor.getString(1)));
score.setDate(cursor.getString(2));
scoresList.add(score);
} while (cursor.moveToNext());
}
return scoresList;
}
public int getHighscore() {
String selectQuery = "SELECT " + KEY_SCORE + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_SCORE +" DESC LIMIT 1";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return 0;
}
public int getLastScoreID(){
String selectQuery = "SELECT " + KEY_ID + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_ID + " DESC LIMIT 1";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return -1;
}
public int getLastScoreValue(){
String selectQuery = "SELECT " + KEY_SCORE + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return -1;
}
}
Here's the question:
where should I put database.close()? There's no such thing like destructor in Java (I really don't want to finalize() this one...).
Best regards.
Override the close() method of the SQLiteOpenHelper class
#Override
public synchronized void close() {
database.close();
super.close();
}

Retrieving all data from database

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

SQL database Columns error, or does not exist?

I am working on my sqldatabase, but i cannot move on because my program is giving me an error that there is no such column, even though the column is clearly defined at the top of my code under "KEY_NAME" If anybody can help me or needs me to post anymore code please tell me Thanks!
I've only posted my database.
******* recent logcat information
03-14 01:24:54.285: E/Database(26073): android.database.sqlite.SQLiteException: table PeopleTable has no column named persons_name: , while compiling: INSERT INTO PeopleTable(persons_hotness, persons_name) VALUES(?, ?);
public class HotOrNot {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "persons_name";
public static final String KEY_HOTNESS = "persons_hotness";
private static final String DATABASE_NAME = "HotOrNotDB";
private static final String DATABASE_TABLE = "PeopleTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
+ " TEXT NOT NULL, " + KEY_HOTNESS + " TEXT NOT NULL);");
// String sql = String.format("create table %s "
// + "(%s int primary key, %s int, %s text, %s text)",
// DATABASE_TABLE, KEY_ROWID, KEY_NAME, KEY_HOTNESS);
// db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public HotOrNot(Context c) {
ourContext = c;
}
public HotOrNot open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name, String hotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_HOTNESS };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iName)
+ " " + c.getString(iHotness) + "\n";
}
return result;
}
}
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT,KEY_NAME TEXT NOT NULL, " + KEY_HOTNESS + " TEXT NOT NULL);");
Try the above changes..I think the problem might be due to space added before KEY_NAME. Hope this helps u..
try replacing + "KEY_NAME" + with + KEY_NAME + (without double quotes). This line is inside public void onCreate(SQLiteDatabase db)
replace your db.execSQL query by this
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
+ " TEXT NOT NULL, " + KEY_HOTNESS + " TEXT NOT NULL);");

Categories