No such table (Android SQLite) - java

I've been having a problem with my SQLite DB for quite some time now. Every so often something goes wrong and I get this error:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: android.database.sqlite.SQLiteException: no such table: photo (code 1): , while compiling: SELECT * FROM photo
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:686)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1420)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1359)
at com.example.sition.diggintemp.db.DigginSQLiteHelper.getAllPhotos(DigginSQLiteHelper.java:1102)
at com.example.sition.diggintemp.LoadActivity$LoadAllTask.doInBackground(LoadActivity.java:249)
at com.example.sition.diggintemp.LoadActivity$LoadAllTask.doInBackground(LoadActivity.java:243)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
at java.lang.Thread.run(Thread.java:856) 
When this happen I need to clear the entire DB, set version number one higher and remove all pictures from the server and the device (because they're kind of linked to the info in the DB).
Below is the AsyncTask in my LoadActivity (where I get this error), in this Activity I load the DB from the server and replace the old data from the SQLiteDB with the data from the online DB.
private class LoadAllTask extends AsyncTask<JSONArray,Void,Void> {
#Override
protected Void doInBackground(JSONArray... params) {
JSONArray jsonProjects = params[0];
JSONArray jsonPhotos = params[1];
JSONArray jsonVideos = params[2];
ArrayList<Photo> oldPhotos = db.getAllPhotos();
ArrayList<Video> oldVideos = db.getAllVideos();
db.clearDB();
try {
for (int i = 0; i < jsonProjects.length(); i++) {
JSONObject jsonProject = (JSONObject) jsonProjects.get(i);
Project project = new Project(jsonProject.getInt("id"), jsonProject.getString("title"), jsonProject.getInt("user_id"), jsonProject.getString("description"));
db.addProject(project);
JSONArray jsonWells = jsonProject.getJSONArray("wells");
for (int i2 = 0; i2 < jsonWells.length(); i2++) {
JSONObject jsonWell = (JSONObject) jsonWells.get(i2);
Well well = new Well(jsonWell.getInt("id"), jsonWell.getString("number"), jsonWell.getInt("project_id"), jsonWell.getString("description"));
db.addWell(well);
}
JSONArray jsonTracks = jsonProject.getJSONArray("tracks");
for (int i2 = 0; i2 < jsonTracks.length(); i2++) {
JSONObject jsonTrack = (JSONObject) jsonTracks.get(i2);
Track track = new Track(jsonTrack.getInt("id"), jsonTrack.getString("number"), jsonTrack.getString("description"));
boolean inDb = false;
for (Track t : db.getAllTracks()) {
if (t.toString().equals(track.toString())) {
inDb = true;
}
}
if (!inDb) {
db.addTrack(track);
}
Track_Well track_well = new Track_Well(db.getAllTrackWells().size() + 1, jsonTrack.getInt("id"), jsonTrack.getInt("well_id"));
db.addTrackWell(track_well);
}
JSONArray jsonSurfaces = jsonProject.getJSONArray("surfaces");
for (int i2 = 0; i2 < jsonSurfaces.length(); i2++) {
JSONObject jsonSurface = (JSONObject) jsonSurfaces.get(i2);
Surface surface = new Surface(jsonSurface.getInt("id"), jsonSurface.getString("number"), jsonSurface.getInt("well_id"), jsonSurface.getString("description"));
boolean inDb = false;
for (Surface s : db.getAllSurfaces()) {
if (s.toString().equals(surface.toString())) {
inDb = true;
}
}
if (!inDb) {
db.addSurface(surface);
}
Track_Surface track_surface = new Track_Surface(db.getAllTrackSurfaces().size() + 1, (!jsonSurface.isNull("track_id") ? jsonSurface.getInt("track_id") : 0), jsonSurface.getInt("id"));
db.addTrackSurface(track_surface);
}
JSONArray jsonProfiles = jsonProject.getJSONArray("profiles");
for (int i2 = 0; i2 < jsonProfiles.length(); i2++) {
JSONObject jsonProfile = (JSONObject) jsonProfiles.get(i2);
Profile profile = new Profile(jsonProfile.getInt("id"), jsonProfile.getString("number"), jsonProfile.getInt("well_id"), jsonProfile.getString("description"));
boolean inDb = false;
for (Profile p : db.getAllProfiles()) {
if (p.toString().equals(profile.toString())) {
inDb = true;
}
}
if (!inDb) {
db.addProfile(profile);
}
Track_Profile track_profile = new Track_Profile(db.getAllTrackProfiles().size() + 1, (!jsonProfile.isNull("track_id") ? jsonProfile.getInt("track_id") : 0), jsonProfile.getInt("id"));
db.addTrackProfile(track_profile);
}
JSONArray jsonFieldfinds = jsonProject.getJSONArray("fieldfinds");
for (int i2 = 0; i2 < jsonFieldfinds.length(); i2++) {
JSONObject jsonFieldfind = (JSONObject) jsonFieldfinds.get(i2);
int id = jsonFieldfind.getInt("id");
String number = jsonFieldfind.getString("number");
int project_id = (!jsonFieldfind.isNull("project_id") ? jsonFieldfind.getInt("project_id") : 0);
int well_id = (!jsonFieldfind.isNull("well_id") ? jsonFieldfind.getInt("well_id") : 0);
int track_id = (!jsonFieldfind.isNull("track_id") ? jsonFieldfind.getInt("track_id") : 0);
int surface_id = (!jsonFieldfind.isNull("surface_id") ? jsonFieldfind.getInt("surface_id") : 0);
int profile_id = (!jsonFieldfind.isNull("profile_id") ? jsonFieldfind.getInt("profile_id") : 0);
int user_id = jsonFieldfind.getInt("user_id");
String description = (jsonFieldfind.getString("description"));
Fieldfind fieldfind = new Fieldfind(id,number,project_id,well_id,track_id,surface_id,profile_id,user_id,description);
db.addFieldfind(fieldfind);
}
}
for (int i3 = 0; i3 < jsonPhotos.length(); i3++) {
JSONObject jsonPhoto = (JSONObject) jsonPhotos.get(i3);
File mainDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "Diggin");
boolean isPic = jsonPhoto.getString("image_path").contains("picture");
String pathStart = mainDir.getPath() + "/";
Photo photo = new Photo(jsonPhoto.getInt("id"), jsonPhoto.getInt("user_id"), jsonPhoto.getString("imageable_type"), jsonPhoto.getInt("imageable_id"), pathStart + jsonPhoto.getString("image_path"), jsonPhoto.getString("description"), jsonPhoto.getString("metadata"), jsonPhoto.getString("wind"));
photo.setImage_path(photo.getThumbnailFromImage_path());
String filename = photo.getDBImage_path();
File thumbDir = new File(mainDir, "thumbnails");
File thumbnailFile = new File(thumbDir, filename);
photo.setImage_path(thumbnailFile.toString());
if (!thumbnailFile.exists()) {
db.addPhoto(photo);
String image_str = jsonPhoto.getString("image");
byte[] byte_arr = Base64.decode(image_str, 0);
Bitmap bitmap = BitmapFactory.decodeByteArray(byte_arr, 0, byte_arr.length);
try {
createPicture(bitmap, photo);
} catch (IOException e) {
e.printStackTrace();
}
} else {
photo.setImage_path(photo.getImageFromThumbnail_path());
if(isPic) {
photo.setImage_path(thumbnailFile.toString());
}
db.addPhoto(photo);
}
}
for (int i4 = 0; i4 < jsonVideos.length(); i4++) {
JSONObject jsonVideo = (JSONObject) jsonVideos.get(i4);
File mainDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "Diggin");
boolean isVid = jsonVideo.getString("image_path").contains("video");
String pathStart = mainDir.getPath() + "/";
Video video = new Video(jsonVideo.getInt("id"), jsonVideo.getInt("user_id"), jsonVideo.getString("imageable_type"), jsonVideo.getInt("imageable_id"), pathStart + jsonVideo.getString("image_path"), jsonVideo.getString("description"), jsonVideo.getString("metadata"));
video.setImage_path(video.getThumbnailFromImage_path());
String filename = video.getDBImage_path();
File thumbDir = new File(mainDir, "thumbnails");
File thumbnailFile = new File(thumbDir, filename);
video.setImage_path(thumbnailFile.toString());
if (!thumbnailFile.exists()) {
db.addVideo(video);
String image_str = jsonVideo.getString("image");
byte[] byte_arr = Base64.decode(image_str, 0);
Bitmap bitmap = BitmapFactory.decodeByteArray(byte_arr, 0, byte_arr.length);
try {
createPicture(bitmap, video);
} catch (IOException e) {
e.printStackTrace();
}
} else {
video.setImage_path(video.getImageFromThumbnail_path());
if(isVid) {
video.setImage_path(thumbnailFile.toString());
}
db.addVideo(video);
}
}
for (Photo photo : oldPhotos) {
boolean stillExists = false;
for (Photo p : db.getAllPhotos()) {
if (p.getThumbnailFromImage_path().equals(photo.getThumbnailFromImage_path())) {
stillExists = true;
}
}
if (!stillExists) {
//Delete thumbnail picture
String deleteCmd = "rm -r " + photo.getThumbnailFromImage_path();
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(deleteCmd);
} catch (IOException e) {
e.printStackTrace();
}
}
}
for (Video video : oldVideos) {
boolean stillExists = false;
for (Video v : db.getAllVideos()) {
if (v.getThumbnailFromImage_path().equals(video.getThumbnailFromImage_path())) {
stillExists = true;
}
}
if (!stillExists) {
//Delete thumbnail picture
String deleteCmd = "rm -r " + video.getThumbnailFromImage_path();
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(deleteCmd);
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent(LoadActivity.this,MainActivity.class);
startActivity(intent);
}
}
Does somebody know what causes this, because I have no clue.
EDIT:
Here is some code from the DigginSQLiteHelper:
public class DigginSQLiteHelper extends SQLiteOpenHelper{
//region Database Version and Name
private static final int DATABASE_VERSION = 9;
private static final String DATABASE_NAME = "DigginTempDB";
//endregion Database Version and Name
//region Table names
private static final String TABLE_PROJECT = "project";
private static final String TABLE_WELL = "well";
private static final String TABLE_TRACK = "track";
private static final String TABLE_SURFACE = "surface";
private static final String TABLE_PROFILE = "profile";
private static final String TABLE_FIELDFIND = "fieldfind";
private static final String TABLE_TRACK_WELL = "track_well";
private static final String TABLE_TRACK_SURFACE = "track_surface";
private static final String TABLE_TRACK_PROFILE = "track_profile";
private static final String TABLE_PHOTO = "photo";
private static final String TABLE_VIDEO = "video";
//endregion Table names
//region Table Column names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_USER_ID = "user_id";
private static final String KEY_NUMBER = "number";
private static final String KEY_PROJECT_ID = "project_id";
private static final String KEY_WELL_ID = "well_id";
private static final String KEY_TRACK_ID = "track_id";
private static final String KEY_SURFACE_ID = "surface_id";
private static final String KEY_PROFILE_ID = "profile_id";
private static final String KEY_IMAGEABLE_TYPE = "imageable_type";
private static final String KEY_IMAGEABLE_ID = "imageable_id";
private static final String KEY_IMAGE_PATH = "image_path";
private static final String KEY_DESCRIPTION = "description";
private static final String KEY_METADATA = "metadata";
private static final String KEY_WIND = "wind";
//endregion
//region Table Columns
private static final String[] COLUMNS_PROJECT = {KEY_ID,KEY_TITLE,KEY_USER_ID,KEY_DESCRIPTION};
private static final String[] COLUMNS_WELL = {KEY_ID, KEY_NUMBER, KEY_PROJECT_ID,KEY_DESCRIPTION};
private static final String[] COLUMNS_TRACK = {KEY_ID, KEY_NUMBER,KEY_DESCRIPTION};
private static final String[] COLUMNS_SURFACE = {KEY_ID, KEY_NUMBER, KEY_WELL_ID,KEY_DESCRIPTION};
private static final String[] COLUMNS_PROFILE = {KEY_ID, KEY_NUMBER, KEY_WELL_ID,KEY_DESCRIPTION};
private static final String[] COLUMNS_FIELDFIND = {KEY_ID, KEY_NUMBER, KEY_PROJECT_ID, KEY_WELL_ID, KEY_TRACK_ID, KEY_SURFACE_ID, KEY_PROFILE_ID, KEY_USER_ID,KEY_DESCRIPTION};
private static final String[] COLUMNS_TRACK_WELL = {KEY_ID, KEY_TRACK_ID, KEY_WELL_ID};
private static final String[] COLUMNS_TRACK_SURFACE = {KEY_ID, KEY_TRACK_ID, KEY_SURFACE_ID};
private static final String[] COLUMNS_TRACK_PROFILE = {KEY_ID, KEY_TRACK_ID, KEY_PROFILE_ID};
private static final String[] COLUMNS_PHOTO = {KEY_ID,KEY_USER_ID,KEY_IMAGEABLE_TYPE,KEY_IMAGEABLE_ID,KEY_IMAGE_PATH,KEY_DESCRIPTION,KEY_METADATA,KEY_WIND};
private static final String[] COLUMNS_VIDEO = {KEY_ID,KEY_USER_ID,KEY_IMAGEABLE_TYPE,KEY_IMAGEABLE_ID,KEY_IMAGE_PATH,KEY_DESCRIPTION,KEY_METADATA};
//endregion
public DigginSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statements to create tables
String CREATE_PROJECT_TABLE =
"CREATE TABLE project ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, "+
"user_id INTEGER, " +
"description TEXT);";
String CREATE_WELL_TABLE =
"CREATE TABLE well ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"number TEXT, " +
"project_id INTEGER, " +
"description TEXT, " +
" FOREIGN KEY ("+KEY_PROJECT_ID+") REFERENCES "+TABLE_PROJECT+"("+KEY_ID+"));";
String CREATE_TRACK_TABLE =
"CREATE TABLE track ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"number TEXT, " +
"description TEXT);";
String CREATE_SURFACE_TABLE =
"CREATE TABLE surface ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"number TEXT, " +
"well_id INTEGER, " +
"description TEXT, " +
" FOREIGN KEY ("+KEY_WELL_ID+") REFERENCES "+TABLE_WELL+"("+KEY_ID+"));";
String CREATE_PROFILE_TABLE =
"CREATE TABLE profile ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"number TEXT, " +
"well_id INTEGER, " +
"description TEXT, " +
" FOREIGN KEY ("+KEY_WELL_ID+") REFERENCES "+TABLE_WELL+"("+KEY_ID+"));";
String CREATE_FIELDFIND_TABLE =
"CREATE TABLE fieldfind ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"number TEXT, " +
"project_id INTEGER, " +
"well_id INTEGER, " +
"track_id INTEGER, " +
"surface_id INTEGER, " +
"profile_id INTEGER, " +
"user_id INTEGER, " +
"description TEXT, " +
" FOREIGN KEY ("+KEY_PROJECT_ID+") REFERENCES "+TABLE_PROJECT+"("+KEY_ID+")," +
" FOREIGN KEY ("+KEY_WELL_ID+") REFERENCES "+TABLE_WELL+"("+KEY_ID+")," +
" FOREIGN KEY ("+KEY_TRACK_ID+") REFERENCES "+TABLE_TRACK+"("+KEY_ID+")," +
" FOREIGN KEY ("+KEY_SURFACE_ID+") REFERENCES "+TABLE_SURFACE+"("+KEY_ID+")," +
" FOREIGN KEY ("+KEY_PROFILE_ID+") REFERENCES "+TABLE_PROFILE+"("+KEY_ID+"));";
String CREATE_TRACK_WELL_TABLE =
"CREATE TABLE track_well ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"track_id INTEGER, " +
"well_id INTEGER, " +
" FOREIGN KEY ("+KEY_TRACK_ID+") REFERENCES "+TABLE_TRACK+"("+KEY_ID+")" +
" FOREIGN KEY ("+KEY_WELL_ID+") REFERENCES "+TABLE_WELL+"("+KEY_ID+"));";
String CREATE_TRACK_SURFACE_TABLE =
"CREATE TABLE track_surface ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"track_id INTEGER, " +
"surface_id INTEGER, " +
" FOREIGN KEY ("+KEY_TRACK_ID+") REFERENCES "+TABLE_TRACK+"("+KEY_ID+")" +
" FOREIGN KEY ("+KEY_SURFACE_ID+") REFERENCES "+TABLE_SURFACE+"("+KEY_ID+"));";
String CREATE_TRACK_PROFILE_TABLE =
"CREATE TABLE track_profile ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"track_id INTEGER, " +
"profile_id INTEGER, " +
" FOREIGN KEY ("+KEY_TRACK_ID+") REFERENCES "+TABLE_TRACK+"("+KEY_ID+")" +
" FOREIGN KEY ("+KEY_PROFILE_ID+") REFERENCES "+TABLE_PROFILE+"("+KEY_ID+"));";
String CREATE_PHOTO_TABLE =
"CREATE TABLE photo( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"user_id INTEGER, "+
"imageable_type TEXT, "+
"imageable_id INTEGER, "+
"image_path TEXT, "+
"description TEXT, "+
"metadata TEXT, "+
"wind TEXT );";
String CREATE_VIDEO_TABLE =
"CREATE TABLE video( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"user_id INTEGER, "+
"imageable_type TEXT, "+
"imageable_id INTEGER, "+
"image_path TEXT, "+
"description TEXT, "+
"metadata TEXT );";
// Create tables
db.execSQL(CREATE_PROJECT_TABLE);
db.execSQL(CREATE_WELL_TABLE);
db.execSQL(CREATE_TRACK_TABLE);
db.execSQL(CREATE_SURFACE_TABLE);
db.execSQL(CREATE_PROFILE_TABLE);
db.execSQL(CREATE_FIELDFIND_TABLE);
db.execSQL(CREATE_TRACK_WELL_TABLE);
db.execSQL(CREATE_TRACK_SURFACE_TABLE);
db.execSQL(CREATE_TRACK_PROFILE_TABLE);
db.execSQL(CREATE_PHOTO_TABLE);
db.execSQL(CREATE_VIDEO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
// Drop older tables if existed
db.execSQL("DROP TABLE IF EXISTS video");
db.execSQL("DROP TABLE IF EXISTS photo");
db.execSQL("DROP TABLE IF EXISTS fieldfind");
db.execSQL("DROP TABLE IF EXISTS track_surface");
db.execSQL("DROP TABLE IF EXISTS track_profile");
db.execSQL("DROP TABLE IF EXISTS track_well");
db.execSQL("DROP TABLE IF EXISTS profile");
db.execSQL("DROP TABLE IF EXISTS surface");
db.execSQL("DROP TABLE IF EXISTS track");
db.execSQL("DROP TABLE IF EXISTS well");
db.execSQL("DROP TABLE IF EXISTS project");
// Create fresh tables
this.onCreate(db);
}
}
public static int getDatabaseVersion() {
return DATABASE_VERSION;
}
/**
* Method that clears the SQLite DB
*/
public void clearDB() {
SQLiteDatabase db = getWritableDatabase();
// Drop older tables if existed
db.execSQL("DROP TABLE IF EXISTS video");
db.execSQL("DROP TABLE IF EXISTS photo");
db.execSQL("DROP TABLE IF EXISTS fieldfind");
db.execSQL("DROP TABLE IF EXISTS track_surface");
db.execSQL("DROP TABLE IF EXISTS track_profile");
db.execSQL("DROP TABLE IF EXISTS track_well");
db.execSQL("DROP TABLE IF EXISTS profile");
db.execSQL("DROP TABLE IF EXISTS surface");
db.execSQL("DROP TABLE IF EXISTS track");
db.execSQL("DROP TABLE IF EXISTS well");
db.execSQL("DROP TABLE IF EXISTS project");
// Create fresh tables
this.onCreate(db);
}
public ArrayList<Photo> getAllPhotos() {
ArrayList<Photo> photos = new ArrayList<>();
// 1. build the query
String query = "SELECT * FROM " + TABLE_PHOTO;
// 2. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// 3. go over each row, build project and add it to list
Photo photo;
if (cursor.moveToFirst()) {
do {
photo = new Photo(cursor.getInt(0),cursor.getInt(1),cursor.getString(2),cursor.getInt(3),cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getString(7));
// Add photo to photos
photos.add(photo);
} while (cursor.moveToNext());
}
cursor.close();
// return photos
return photos;
}
}

I just move my comment here since it's an actual solution
Seems like your clearDB method drops all the tables - why...? I'm not quite sure how the db engine works and behaves in this situation. Anyway, I'd suggest you to try DELETE FROM your tables instead of drop and create them. It doesn't make sense to have a method called 'clear' and perform operations like that.

Related

Error: Attempt to invoke virtual method on null object reference 'android.database.Cursor com.myapplication.DatabaseHeleper.getData()'

This the error
I have attached the error above after executing code below mentioned, the code given below is not full code but it targets the main code for which my question is.I am trying to send sms through a variable in which number is stored by fetching from sqlite database. So below code shows that I tried to fetch from dbhelper.java class and store in variable num in sendsms.java class but i think it is not fetching Hence i would request you to see the code and guide where i am wrong for improvement. I hope that now question is clear and sufficient description is given so please help.
sendsms.java
try {
Cursor cursor = databaseHelper.getdata();
while (cursor.moveToNext())
{
String num = cursor.getString(0);
String numm = cursor.getString(1);
String nummm = cursor.getString(2);
}
}
catch(Exception e){
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
public void run() {
sms.sendTextMessage(num, null, "Help! I've met with an accident at http://maps.google.com/?q=" + String.valueOf(latitude) + "" +
"," + String.valueOf(longitude), null, null);
dbhelper.java
public static final String TABLE_REGISTER = "signin";
public static final String COL_ID = "USER_ID";
public static final String COL_NAME = "NAME";
public static final String COL_PHONE = "PHONE_NUMBER";
public static final String COL_EMAIL = "EMAIL";
public static final String COL_PASSWORD = "PASSWORD";
public static final String COL_CONFIRM_PASSWORD = "CONFIRM_PASSWORD";
public static final String COL_NAMEone_CON = "NAMEONE";
public static final String COL_NUMBERone_CON = "NUMBERONE";
public static final String COL_NAMEtwo_CON = "NAMETWO";
public static final String COL_NUMBERtwo_CON = "NUMBERTWO";
public static final String COL_NAMEthree_CON = "NAMETHREE";
public static final String COL_NUMBERthree_CON = "NUMBERTHREE";
public SQLiteDatabase db;
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_REGISTER + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ COL_NAME + " TEXT , " + COL_PHONE + " LONG UNIQUE ," + COL_EMAIL + " VARCHAR UNIQUE," + COL_PASSWORD + " VARCHAR , "
+ COL_CONFIRM_PASSWORD + " VARCHAR ," + COL_NAMEone_CON + " TEXT , "
+ COL_NUMBERone_CON + " LONG UNIQUE ," + COL_NAMEtwo_CON + " TEXT ," + COL_NUMBERtwo_CON + " LONG UNIQUE , "
+ COL_NAMEthree_CON + " TEXT ," + COL_NUMBERthree_CON + " LONG UNIQUE " + ")");
}
public Cursor getdata(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select NUMBERONE, NUMBERTWO,NUMBERTHREE from signin ", null);
return cursor;
}
It seems that you have to call getReadableDatabase or getWritableDatabase before you need the data, this is because it takes time to create the database.So, you have to be aware of that.
Also, I wanted to remark that you must cursor.moveToFirst() before you do cursor.moveToNext() on sendsms.java
Please change your code like this:-
try {
Cursor cursor = databaseHelper.getdata();
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String num = cursor.getString(0);
String numm = cursor.getString(1);
String nummm = cursor.getString(2);
}
}
}
catch(Exception e){
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}

retrieveing image from the sqlite gives error?

I am trying to store image into SQLite and then retrieve the image back. I have searched other post related to it and got some clues and leads but now i am stuck and getting error which i do not know WHY ?
The image store into the SQLite Database Successfully but when i try to get the image i get the error
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Below is my code
SQL Helper Class
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLHelperClass extends SQLiteOpenHelper {
public static int DATABASE_VERSION = 12;
public static String DATABASE_NAME = "user_image_save.db";
public static String CREATE_TABLE = "CREATE TABLE";
public static String TEXT_TYPE = "TEXT";
public static String BLOB = "BLOB";
public static String INTEGER_TYPE = "INTEGER";
public static String DROP_TABLE = "DROP TABLE IF EXISTS" ;
public static String AUTOINCREMENT = "INTEGER PRIMARY KEY AUTOINCREMENT" ;
public SQLHelperClass(Context context ){
super(context , DATABASE_NAME , null , DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_TABLE + " " + SQL_Constants.SavedIntoSQL.TABLE_SQL_SAVE_IMAGE
+ " ( " + SQL_Constants.SavedIntoSQL._ID + " " + AUTOINCREMENT + " , "
+ SQL_Constants.SavedIntoSQL.COLUMN_OWNER_ID + " " + TEXT_TYPE + " , "
+ SQL_Constants.SavedIntoSQL.COLUMN_NAME + " " + TEXT_TYPE + " , "
+ SQL_Constants.SavedIntoSQL.COLUMN_EMAIL + " " + TEXT_TYPE + " , "
+ SQL_Constants.SavedIntoSQL.COLUMN_IMAGE + " " + BLOB+ ")" );
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL(DROP_TABLE);
onCreate(sqLiteDatabase);
}
}
Constant Class
import android.provider.BaseColumns;
import android.provider.BaseColumns;
public final class SQL_Constants {
public static abstract class SavedIntoSQL implements BaseColumns {
public static final String TABLE_SQL_SAVE_IMAGE = "imageSave";
public static final String ID_DATA = _ID ;
public static final String COLUMN_OWNER_ID = "owner_id";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_IMAGE = "user_image";
}
}
Storing Data into SQLite
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
resource.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
Toast.makeText(UpdatedUserProfile.this, "Download Complete", Toast.LENGTH_SHORT).show();
ContentValues contentValues = new ContentValues();
contentValues.put(SQL_Constants.SavedIntoSQL.COLUMN_OWNER_ID, App.getAppInstance().getCurrentUser().getProperty("ownerId").toString());
contentValues.put(SQL_Constants.SavedIntoSQL.COLUMN_NAME, App.getAppInstance().getCurrentUser().getProperty("name").toString());
contentValues.put(SQL_Constants.SavedIntoSQL.COLUMN_EMAIL, App.getAppInstance().getCurrentUser().getEmail());
contentValues.put(SQL_Constants.SavedIntoSQL.COLUMN_IMAGE, bytes);
sqLiteDatabase.insert(SQL_Constants.SavedIntoSQL.TABLE_SQL_SAVE_IMAGE, null, contentValues);
Getting The Data Back
sqlHelperClass = new SQLHelperClass(UpdatedUserProfile.this);
sqLiteDatabase = sqlHelperClass.getWritableDatabase();
sqLiteDatabase = sqlHelperClass.getReadableDatabase();
String projection [] = {
SQL_Constants.SavedIntoSQL.COLUMN_OWNER_ID ,
SQL_Constants.SavedIntoSQL.COLUMN_EMAIL ,
SQL_Constants.SavedIntoSQL.COLUMN_NAME ,
};
cursor = sqLiteDatabase.query(SQL_Constants.SavedIntoSQL.TABLE_SQL_SAVE_IMAGE , projection,
null , null , null , null , null);
cursor.moveToPosition(0);
int statusOwnerId = cursor.getColumnIndex(SQL_Constants.SavedIntoSQL.COLUMN_OWNER_ID);
int statusName = cursor.getColumnIndex(SQL_Constants.SavedIntoSQL.COLUMN_NAME);
int statusEmail = cursor.getColumnIndex(SQL_Constants.SavedIntoSQL.COLUMN_EMAIL);
int statusImage = cursor.getColumnIndex(SQL_Constants.SavedIntoSQL.COLUMN_IMAGE);
String ownerIdAgain = cursor.getString(statusOwnerId);
String name = cursor.getString(statusName);
String email = cursor.getString(statusEmail);
byte [] image = cursor.getBlob(statusImage);
String compareValueOwnerId = sharedPreferencesDatabaseActivity.getString("userId", "");
String compareValueUserName = sharedPreferencesDatabaseActivity.getString("userName", "");
String compareValueEmail = sharedPreferencesDatabaseActivity.getString("userEmail", "");
i am getting all other data i.e name , email , owner_id but when i comes to image i get the error
This is the line that causes error
byte [] image = cursor.getBlob(statusImage);
Any help is appreciated
Your projection does not have COLUMN_IMAGE so cursor.getColumnIndex(SQL_Constants.SavedIntoSQL.COLUMN_IMAGE) returns -1. Attempting to read column -1 causes this exception.
Adding the column to your projection helps if the image blobs are small enough. Android SQLite cursors have a limited-size window and in practice you cannot query rows larger than 2MB. If that's the case for you, consider refactoring your code so that you're not storing the images in the database. Rather store them in the file system and just store their paths in the database.

where clause is not working in sqlite database [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm new to Android. I want to add a column in my existing database which already contains some questions. I tried setting some code in the onUpgrade() method using the ALTER command but it is not working. It is gives an error:
ERROR:-
java.lang.RuntimeException: Unable to start activity
ComponentInfo
{com.example.chaitanya.myquiz/
com.example.chaitanya.myquiz.QuestionActivity}:
android.database.sqlite.SQLiteException: no such column: id (code 1):
, while compiling: SELECT * FROM quest where id = '1'
here is the code.
public class QuizHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "bcd";
// tasks table name
private static final String TABLE_QUEST = "quest";
// tasks Table Columns names
private static final String KEY_ID = "qid";
private static final String KEY_QUES = "question";
private static final String KEY_ANSWER = "answer"; // correct option
private static final String KEY_OPTA = "opta"; // option a
private static final String KEY_OPTB = "optb"; // option b
private static final String KEY_OPTC = "optc"; // option c
private static final String KEY_ID2 = "id";
private SQLiteDatabase dbase;
public QuizHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase = db;
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER + " TEXT, " + KEY_OPTA + " TEXT, "
+ KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT " + KEY_ID2 + " INTEGER)";
db.execSQL(sql);
addQuestion();
// db.close();
}
private void addQuestion() {
Question q1 = new Question("Who is the president of india ?", "narender modi", "hamid ansari", "pranab mukherji", "pranab mukherji",1);
this.addQuestion(q1);
Question q2 = new Question(" Name of the first university of India ?", "Nalanda University", "Takshshila University", "BHU", "Nalanda University",1);
this.addQuestion(q2);
Question q3 = new Question("Which college is awarded as Outstanding Engineering Institute North Award�", "Thapar University", "G.N.D.E.C", "S.L.I.E.T", "G.N.D.E.C",1);
this.addQuestion(q3);
Question q4 = new Question("Name of the first Aircraft Carrier Indian Ship ?", "Samudragupt", "I.N.S. Vikrant", "I.N.S Virat", "I.N.S. Vikrant",1);
this.addQuestion(q4);
Question q5 = new Question("In which town of Punjab the largest grain market of Asia is Available?", "Bathinda", "Khanna", "Ludhiana", "Khanna",1);
this.addQuestion(q5);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
if (newV > oldV) {
db.execSQL("ALTER TABLE " + TABLE_QUEST + " ADD COLUMN " + KEY_ID2 + " INTEGER DEFAULT 0");
}
onCreate(db);
}
// Adding new question
public void addQuestion(Question quest) {
// SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION());
values.put(KEY_ANSWER, quest.getANSWER());
values.put(KEY_OPTA, quest.getOPTA());
values.put(KEY_OPTB, quest.getOPTB());
values.put(KEY_OPTC, quest.getOPTC());
values.put(KEY_ID2,quest.getID());
// Inserting Row
dbase.insert(TABLE_QUEST, null, values);
}
public List<Question> getAllQuestions() {
List<Question> quesList = new ArrayList<Question>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUEST + " where " + KEY_ID2 + " = '1' ";
// + KEY_ID2 + " = 1"
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
Log.i("here",cursor.getCount()+"");
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Question quest = new Question();
quest.setID(cursor.getInt(0));
// Log.i("here",cursor.getInt(0)+"");
quest.setQUESTION(cursor.getString(1));
quest.setANSWER(cursor.getString(2));
quest.setOPTA(cursor.getString(3));
quest.setOPTB(cursor.getString(4));
quest.setOPTC(cursor.getString(5));
quesList.add(quest);
} while (cursor.moveToNext());
}
// return quest list
return quesList;
}
}
Log.i("here",cursor.getCount()+"") gives the 0 value in the output.
If you just want to add a single column into your existing table quest, then no need to call onCreate(db) from onUpgrade() method.
Modify onUpgrade() method as below:
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
if (newV > oldV) {
db.execSQL("ALTER TABLE " + TABLE_QUEST + " ADD COLUMN " + KEY_ID2 + " INTEGER DEFAULT 0");
}
}

How to fix IndexOutOfBoundsException : invalid index 0 size is 0

I am storing the response of yes|no|maybe into the userrelation table.
For that, I created a table in DBCONTRACT and get the values in a db helper Class.
when I get the values and store into another variable, it throws this error
This the SQL query for the userRelation table
public static abstract class RingeeUserRelationTable implements BaseColumns {
public static final String TABLE_NAME = "user_relation";
public static final String COL1_EVENT_USER_ID = "EVENT_USER_ID";
public static final String COL2_EVENT_ID = "EVENT_ID";
public static final String COL3_RINGEE_USER_ID = "RINGEE_USER_ID";
public static final String COL4_IS_ATTENDING = "IS_ATTENDING";
public static final String COL5_IS_DELETE = "IS_DELETE";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + _ID + " INTEGER PRIMARY KEY," + COL1_EVENT_USER_ID + INTEGER_TYPE + COMMA_SEP + COL2_EVENT_ID + INTEGER_TYPE
+ COMMA_SEP + COL3_RINGEE_USER_ID + INTEGER_TYPE + COMMA_SEP + COL4_IS_ATTENDING + INTEGER_TYPE + COMMA_SEP + COL5_IS_DELETE + INTEGER_TYPE + ")";
public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
public static final String RETRIVE_ALL_USER_DATA = "SELECT " + COL1_EVENT_USER_ID + COMMA_SEP + COL2_EVENT_ID + COMMA_SEP + COL3_RINGEE_USER_ID + COMMA_SEP + COL4_IS_ATTENDING + COMMA_SEP
+ COL5_IS_DELETE + " FROM " + TABLE_NAME;
}
This is the code for getting the value and set to userMOS list
public ArrayList<UserMO> getAllUserRelation() {
ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(DatabaseContract.RingeeUserRelationTable.RETRIVE_ALL_USER_DATA, null );
if (cursor.moveToFirst()) {
do {
UserMO userMO = new UserMO();
userMO.setEventUserId(cursor.getLong(1));
userMO.setEventId(cursor.getLong(2));
userMO.setRingeeUserId(cursor.getLong(3));
userMO.setIsAttending(cursor.getInt(4));
userMO.setIsDelete(cursor.getInt(5));
userMOs.add(userMO);
} while (cursor.moveToNext());
cursor.close();
}
return userMOs;
}
This is the code for getting the isattending value in the Fragment
context = getActivity().getApplicationContext();
dbHelper = new DatabaseHelper(context);
userMOs = dbHelper.getAllUserRelation();
// I got the error here there is no value in a table but in back end the values are stored
int isAttending = userMOs.get(position).getIsAttending();
I am using this isattending for setting the colour of the yes|no|maybe Button
switch(isAttending)
{
case 1:
yesBtn.setBackgroundColor(Color.YELLOW);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.BLUE);
break;
case 2:
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.YELLOW);
break;
case 0:
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.YELLOW);
maybeBtn.setBackgroundColor(Color.BLUE);
break;
}
When I run this project, I get an error: IndexOutOfBoundsException.
Please tell me what is the cause of the error and how to solve this issue
Indexes are 0 based.
Therefore, you need to rewrite your code like so:
public ArrayList<UserMO> getAllUserRelation() {
ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(DatabaseContract.RingeeUserRelationTable.RETRIVE_ALL_USER_DATA, null );
if (cursor.moveToFirst()) {
do {
UserMO userMO = new UserMO();
userMO.setEventUserId(cursor.getLong(0));
userMO.setEventId(cursor.getLong(1));
userMO.setRingeeUserId(cursor.getLong(2));
userMO.setIsAttending(cursor.getInt(3));
userMO.setIsDelete(cursor.getInt(4));
userMOs.add(userMO);
} while (cursor.moveToNext());
cursor.close();
}
return userMOs;
}
Write the following code as shown below:-
public ArrayList<UserMO> getAllUserRelation() {
ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(DatabaseContract.RingeeUserRelationTable.RETRIVE_ALL_USER_DATA, null );
if (cursor.moveToFirst()) {
do {
UserMO userMO = new UserMO();
userMO.setEventUserId(cursor.getLong(1));
userMO.setEventId(cursor.getLong(2));
userMO.setRingeeUserId(cursor.getLong(3));
userMO.setIsAttending(cursor.getInt(4));
userMO.setIsDelete(cursor.getInt(5));
userMos.add(userMO);
} while (cursor.moveToNext());
cursor.close();
}
return userMOs;
}
Its giving you a Array Index out of bound exception as you have not assign anything to your array list. which I had did by adding this line in your code above.
userMos.add(userMo);

Android application crashing when inserting row to SQlite?

This is the DBAdapter I'm using, and for some reason when I try to insert a row- the application crashes.
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
// Field Names:
static final String KEY_ROWID = "Row ID";
static final String NAME_COLUMN = "Name";
static final String EMAIL_COLUMN = "E-mail";
static final String PHONENUMBER_COLUMN = "Phone Number";
static final String ADDRESS_COLUMN = "Street Address";
static final String ZIP_COLUMN = "Zip Code";
static final String ARRIVAL_COLUMN = "Arrival Date";
static final String DEPARTURE_COLUMN = "Departure Date";
static final String ROOM_COLUMN = "Room Number";
static final String NOTES_COLUMN = "Notes Area";
public static final String[] ALL_KEYS = new String[] {NAME_COLUMN, EMAIL_COLUMN, PHONENUMBER_COLUMN, ADDRESS_COLUMN, ZIP_COLUMN, ARRIVAL_COLUMN, DEPARTURE_COLUMN, ROOM_COLUMN, NOTES_COLUMN};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_NAME = 1;
public static final int COL_EMAIL = 2;
public static final int COL_PHONENUMBER = 3;
public static final int COL_ADDRESS = 4;
public static final int COL_ZIP = 5;
public static final int COL_ARRIVAL = 6;
public static final int COL_DEPARTURE = 7;
public static final int COL_ROOM = 8;
public static final int COL_NOTES = 9;
// DataBase info:
static final String DATABASE_NAME = "Reservations.db";
static final String DATABASE_TABLE = "Reservations";
public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COLUMN + " TEXT NOT NULL, "
+ EMAIL_COLUMN + " TEXT"
+ PHONENUMBER_COLUMN + " TEXT NOT NULL, "
+ ADDRESS_COLUMN + " TEXT"
+ ZIP_COLUMN + " TEXT NOT NULL, "
+ ARRIVAL_COLUMN + " TEXT NOT NULL, "
+ DEPARTURE_COLUMN + " TEXT"
+ ROOM_COLUMN + " TEXT NOT NULL, "
+ NOTES_COLUMN + " TEXT"
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to be inserted into the database.
public long insertRow(String nameValue, String emailValue, String phoneValue, String addressValue, String zipValue, String arrivalValue, String departureValue, String roomValue, String notesValue) {
ContentValues initialValues = new ContentValues();
initialValues.put(NAME_COLUMN, nameValue);
initialValues.put(EMAIL_COLUMN, emailValue);
initialValues.put(PHONENUMBER_COLUMN, phoneValue);
initialValues.put(ADDRESS_COLUMN, addressValue);
initialValues.put(ZIP_COLUMN, zipValue);
initialValues.put(ARRIVAL_COLUMN, arrivalValue);
initialValues.put(DEPARTURE_COLUMN, departureValue);
initialValues.put(ROOM_COLUMN, roomValue);
initialValues.put(NOTES_COLUMN, notesValue);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String email, String phone, String address, String zipcode, String arrival, String departure, String room, String notes) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(NAME_COLUMN, name);
newValues.put(EMAIL_COLUMN, email);
newValues.put(ADDRESS_COLUMN, address);
newValues.put(ZIP_COLUMN, zipcode);
newValues.put(ARRIVAL_COLUMN, arrival);
newValues.put(DEPARTURE_COLUMN, departure);
newValues.put(ROOM_COLUMN, room);
newValues.put(NOTES_COLUMN, notes);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
Here's the code from my new reservation activity
public void createReservation(View view) {
db.open();
EditText nameText = (EditText)findViewById(R.id.nameText);
String nameValue = nameText.getText().toString();
EditText emailText = (EditText)findViewById(R.id.emailText);
String emailValue = emailText.getText().toString();
EditText phoneNumber = (EditText)findViewById(R.id.phoneNumber);
String phoneValue = phoneNumber.getText().toString();
EditText addressText = (EditText)findViewById(R.id.addressText);
String addressValue = addressText.getText().toString();
EditText zipNumber = (EditText)findViewById(R.id.zipNumber);
String zipValue = zipNumber.getText().toString();
EditText arrivalDate = (EditText)findViewById(R.id.arrivalDate);
String arrivalValue = arrivalDate.getText().toString();
EditText departureDate = (EditText)findViewById(R.id.departureDate);
String departureValue = departureDate.getText().toString();
EditText notesArea = (EditText)findViewById(R.id.notesText);
String notesValue = notesArea.getText().toString();
EditText roomNum = (EditText)findViewById(R.id.roomNum);
String roomValue = roomNum.getText().toString();
db.insertRow(nameValue, emailValue, phoneValue, addressValue, zipValue, arrivalValue, departureValue, roomValue, notesValue);
Toast toast = Toast.makeText(getApplicationContext(), "Creating Reservation", Toast.LENGTH_LONG);
toast.show();
db.close();
}
Any and all help is greatly appreciated. I've tried looking things up online, which is where I found the DBAdapter, but when I use this DBAdapter I feel like I may have messed something up. For example in Android Studio, the Column Numbers give me the inspection warning that the field is never used. However they were included in the original DBAdapter. I feel like I may have made a mistake when adjusting the DBAdapter to fit my needs, but I can't seem to figure out where I went wrong with it. I am very new to Android programming, and have only made one other application before. Any help is appreciated
Your CREATE TABLE actually doesn't create any table, because it's wrong:
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COLUMN + " TEXT NOT NULL, "
+ EMAIL_COLUMN + " TEXT"
+ PHONENUMBER_COLUMN + " TEXT NOT NULL, "
+ ADDRESS_COLUMN + " TEXT"
+ ZIP_COLUMN + " TEXT NOT NULL, "
+ ARRIVAL_COLUMN + " TEXT NOT NULL, "
+ DEPARTURE_COLUMN + " TEXT"
+ ROOM_COLUMN + " TEXT NOT NULL, "
+ NOTES_COLUMN + " TEXT"
+ ");";
Should be:
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COLUMN + " TEXT NOT NULL, "
+ EMAIL_COLUMN + " TEXT, " // Mind the comma
+ PHONENUMBER_COLUMN + " TEXT NOT NULL, "
+ ADDRESS_COLUMN + " TEXT, " // Mind the comma
+ ZIP_COLUMN + " TEXT NOT NULL, "
+ ARRIVAL_COLUMN + " TEXT NOT NULL, "
+ DEPARTURE_COLUMN + " TEXT, " // Mind the comma
+ ROOM_COLUMN + " TEXT NOT NULL, "
+ NOTES_COLUMN + " TEXT"
+ ");";
Please not that you don't need and shouldn't use hardcoded column indexes.
This is because if you do a SELECT * ... nobody can predict the column order inside the row.
So, maybe, on a query run the email field has index 2 and on another run it has index 5.
That's why it's bad to use fixed column indexes, better use column names with getColumnIndex.
This code lets me assume you are going to do something bad:
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_NAME = 1;
public static final int COL_EMAIL = 2;
public static final int COL_PHONENUMBER = 3;
public static final int COL_ADDRESS = 4;
public static final int COL_ZIP = 5;
public static final int COL_ARRIVAL = 6;
public static final int COL_DEPARTURE = 7;
public static final int COL_ROOM = 8;
public static final int COL_NOTES = 9;
Instead, use
cursor.getString(cursor.getColumnIndex(YOUR_COLUMN_NAME)); // I used getString, but you'd use the actual column type
Moreover, don't use spaces or hyphens in your column names!
This
// Field Names:
static final String KEY_ROWID = "Row ID";
static final String NAME_COLUMN = "Name";
static final String EMAIL_COLUMN = "E-mail";
static final String PHONENUMBER_COLUMN = "Phone Number";
static final String ADDRESS_COLUMN = "Street Address";
static final String ZIP_COLUMN = "Zip Code";
static final String ARRIVAL_COLUMN = "Arrival Date";
static final String DEPARTURE_COLUMN = "Departure Date";
static final String ROOM_COLUMN = "Room Number";
static final String NOTES_COLUMN = "Notes Area";
should be:
// Field Names:
static final String KEY_ROWID = "Row_ID";
static final String NAME_COLUMN = "Name";
static final String EMAIL_COLUMN = "eMail";
static final String PHONENUMBER_COLUMN = "Phone_Number";
static final String ADDRESS_COLUMN = "Street_Address";
static final String ZIP_COLUMN = "Zip_Code";
static final String ARRIVAL_COLUMN = "Arrival_Date";
static final String DEPARTURE_COLUMN = "Departure_Date";
static final String ROOM_COLUMN = "Room_Number";
static final String NOTES_COLUMN = "Notes_Area";

Categories