NullPointerException at this.getReadableDatabase(); - java

Heyhey :)
I looked at several Questions to the same topic, but I found no solution to my problem.
A NullPointerException at this.getReadableDatabase(); appears...
Here's my Code:
public class DatabaseHandler extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "TODO_APP";
/*--------------------------- TABLE ITEMS START ---------------------------*/
private static final String TABLE_ITEMS = "items";
private static String KEY_ID_ITEMS = "id_items";
private static final String KEY_CATEGORY_ITEMS = "category";
private static final String KEY_DATETIME_ITEMS = "datetime";
private static String KEY_NAME_ITEMS = "name";
private static final String KEY_DESCRIPTION_ITEMS = "description";
private static final String KEY_ALARM_ITEMS = "alarm";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// create table ITEMS
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID_ITEMS + " INTEGER PRIMARY KEY," + KEY_CATEGORY_ITEMS
+ " INTEGER," + KEY_DATETIME_ITEMS
+ " TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + KEY_NAME_ITEMS
+ " TEXT," + KEY_DESCRIPTION_ITEMS + " TEXT," + KEY_ALARM_ITEMS
+ " INTEGER" + ");";
db.execSQL(CREATE_ITEMS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
// Create tables again
this.onCreate(db);
}
public void addItem(DB_Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY_ITEMS, item.getCategory());
values.put(KEY_NAME_ITEMS, item.getName());
values.put(KEY_DESCRIPTION_ITEMS, item.getDescription());
values.put(KEY_ALARM_ITEMS, item.getAlarm());
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
db.close(); // Closing database connection
}
public DB_Item getItem(String name) {
//!!!!! Here is one problem !!!!!
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID_ITEMS,
KEY_CATEGORY_ITEMS, KEY_DATETIME_ITEMS, KEY_NAME_ITEMS,
KEY_DESCRIPTION_ITEMS, KEY_ALARM_ITEMS },
KEY_NAME_ITEMS = " = ?", new String[] { String.valueOf(name) },
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
// DB_Item (int category, String name, String description, int
// alarm)
DB_Item item = new DB_Item(cursor.getInt(1), cursor.getString(3),
cursor.getString(4), cursor.getInt(5));
return item;
}
public List<DB_Item> getAllItems() {
List<DB_Item> itemList = new ArrayList<DB_Item>();
// SELECT ALL
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
//!!!!!!!!!! here is the other Problem
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
// go through all rows and then adding to list
if (cursor.moveToFirst()) {
do {
DB_Item item = new DB_Item();
item.setCategory(Integer.parseInt(cursor.getString(0)));
// TODO
// adding to list
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
[and so on, didn't copy the whole code]
Hope you can help me...
The error appears definitely at SQLiteDatabase db = this.getReadableDatabase();
Output:
09-03 08:34:17.863: E/AndroidRuntime(7074): java.lang.RuntimeException: Unable to start activity ComponentInfo{todo.todo_list/todo.view.StartApp}: java.lang.NullPointerException
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.database.DatabaseHandler.getAllItems(DatabaseHandler.java:144)
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.helper.SortItems.sortItemsCategory(SortItems.java:16)
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.view.StartApp.onCreate(StartApp.java:36)

chnage you class to something like this:
package com.mhp.example;
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;
public class DBAdapter {
/*--------------------------- TABLE ITEMS START ---------------------------*/
private static final String TABLE_ITEMS = "items";
private static String KEY_ID_ITEMS = "id_items";
private static final String KEY_CATEGORY_ITEMS = "category";
private static final String KEY_DATETIME_ITEMS = "datetime";
private static String KEY_NAME_ITEMS = "name";
private static final String KEY_DESCRIPTION_ITEMS = "description";
private static final String KEY_ALARM_ITEMS = "alarm";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "dbname";
private static final int DATABASE_VERSION = 1;
tring CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID_ITEMS + " INTEGER PRIMARY KEY," + KEY_CATEGORY_ITEMS
+ " INTEGER," + KEY_DATETIME_ITEMS
+ " TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + KEY_NAME_ITEMS
+ " TEXT," + KEY_DESCRIPTION_ITEMS + " TEXT," + KEY_ALARM_ITEMS
+ " INTEGER" + ");";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_ITEMS_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#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 contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public void addItem(DB_Item item) {
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY_ITEMS, item.getCategory());
values.put(KEY_NAME_ITEMS, item.getName());
values.put(KEY_DESCRIPTION_ITEMS, item.getDescription());
values.put(KEY_ALARM_ITEMS, item.getAlarm());
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
}
public DB_Item getItem(String name) {
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID_ITEMS,
KEY_CATEGORY_ITEMS, KEY_DATETIME_ITEMS, KEY_NAME_ITEMS,
KEY_DESCRIPTION_ITEMS, KEY_ALARM_ITEMS },
KEY_NAME_ITEMS = " = ?", new String[] { String.valueOf(name) },
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
// DB_Item (int category, String name, String description, int
// alarm)
DB_Item item = new DB_Item(cursor.getInt(1), cursor.getString(3),
cursor.getString(4), cursor.getInt(5));
return item;
}
public List<DB_Item> getAllItems() {
List<DB_Item> itemList = new ArrayList<DB_Item>();
// SELECT ALL
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
Cursor cursor = db.rawQuery(selectQuery, null);
// go through all rows and then adding to list
if (cursor.moveToFirst()) {
do {
DB_Item item = new DB_Item();
item.setCategory(Integer.parseInt(cursor.getString(0)));
// TODO
// adding to list
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
}
NOTE: when you create object from DBAdapter,you should open() db and after your work close() it.
DBAdapter db = new DBAdapter(contex);
db.open();
//do you work
db.close();

Just use getReadableDatabase() without this.

Related

SQLiteException: no such column error [duplicate]

This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 6 years ago.
I have looked through SO and found many people having this same error, but they seem to be forgetting to add the column into the create statement or missing whitespace, neither of which I believe I did.
My logcat is as follows:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gmd.referenceapplication, PID: 31988
android.database.sqlite.SQLiteException: no such column: QUANTITY (code 1): , while compiling: SELECT * FROM FTS WHERE (QUANTITY MATCH ?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
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:1316)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:400)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:294)
at com.gmd.referenceapplication.DatabaseTable.query(DatabaseTable.java:187)
at com.gmd.referenceapplication.DatabaseTable.getWordMatches(DatabaseTable.java:179)
at com.gmd.referenceapplication.SearchableActivity$1.onQueryTextChange(SearchableActivity.java:70)
at android.support.v7.widget.SearchView.onTextChanged(SearchView.java:1150)
at android.support.v7.widget.SearchView.access$2000(SearchView.java:103)
at android.support.v7.widget.SearchView$12.onTextChanged(SearchView.java:1680)
at android.widget.TextView.sendOnTextChanged(TextView.java:7991)
at android.widget.TextView.handleTextChanged(TextView.java:8053)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:10157)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1033)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:559)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:492)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:491)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:685)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:445)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:340)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
DatabaseTable class:
public static final String TAG = "ConstantDatabase";
//the columns included in the table
public static final String COL_QUANTITY = "QUANTITY";
public static final String COL_VALUE = "VALUE";
public static final String COL_UNCERTAINTY = "UNCERTAINTY";
public static final String COL_UNIT = "UNIT";
public static final String _id = "_id";
//name, tbale name, version
private static final String DATABASE_NAME = "CONSTANTS";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final DatabaseOpenHelper mDatabaseOpenHelper;
private final Context mcontext;
public DatabaseTable(Context context){
mDatabaseOpenHelper = new DatabaseOpenHelper(context);
mcontext = context;
}
private class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
private final MyDataProvider dp = new MyDataProvider(mcontext);
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +_id+ " INTEGER PRIMARY KEY,"+
COL_QUANTITY + " TEXT, " +
COL_VALUE + " TEXT," +
COL_UNCERTAINTY + " TEXT," +
COL_UNIT + " TEXT " + ")";
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
loadConstants();
Log.e("Database Operation", "DatabaseOpenHelper constructor called, constants loaded?");
mHelperContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
mDatabase.execSQL(FTS_TABLE_CREATE);
Log.e("Database Operation", "Constants Table Created ...");
loadConstants();
}
#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 SQLiteDatabase getmDatabase(){
return mDatabase;
}
private void loadConstants() {
new Thread(new Runnable() {
public void run() {
try {
loadConstantss();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
Log.e("Loading", "Constants Table Populated ...");
}
private void loadConstantss() throws IOException {
HashMap map = dp.getAllMap();
Iterator<Map.Entry<String, ListViewItem>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, ListViewItem> entry = entries.next();
Log.d("thing:", entry.getKey());
//addConstant(entry.getKey(), entry.getValue(), entry.getUncertainty(), entry.getUnit());
}
}
public long addConstant(String quantity, String value, String uncertainty, String unit) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(COL_QUANTITY, quantity);
initialValues.put(COL_VALUE, value);
initialValues.put(COL_UNCERTAINTY, uncertainty);
initialValues.put(COL_UNIT, unit);
db.insert(FTS_VIRTUAL_TABLE, null, initialValues);
return db.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
//database openhelper ends
}
public Cursor getWordMatches(String query, String[] columns) {
String selection = COL_QUANTITY + " MATCH ?";
String[] selectionArgs = new String[] {query+"*"};
return query(selection, selectionArgs, columns);
}
public Cursor query(String selection, String[] selectionArgs, String[] columns) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(FTS_VIRTUAL_TABLE);
Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
columns, selection, selectionArgs, null, null, null);
if (cursor == null) {
return null;
} else if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return cursor;
}
public Cursor getAllTitles(){
return mDatabaseOpenHelper.getmDatabase().query(FTS_VIRTUAL_TABLE, new String[] {
COL_QUANTITY,
COL_UNCERTAINTY,
COL_UNIT,
COL_VALUE},
null,
null,
null,
null,
null);
}
Thank you to anyone who can tell me why it is telling me the column "QUANTITY" is not being created, I really don't know.
If you change the schema you should increment DATABASE_VERSION so the database is upgraded.

ListView doesn't show anything in Android app

Ok so here is the whole code
This is MainActivity.java
package com.gobtron.database_test;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends ActionBarActivity {
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openDB();
populateListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
public void onClick_ViewData (View v){
openDB();
populateListView();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void populateListView() {
Cursor cursor = myDb.getAllRows();
// DatabaseUtils.dumpCursor(cursor);
String[] fromFieldNames = new String[] {DBAdapter.KEY_ROWID, DBAdapter.KEY_NOM};
int[] toViewIDs = new int[] {R.id.textView2, R.id.textView3};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.item_layout, cursor, fromFieldNames, toViewIDs, cursor.getCount());
ListView myList = (ListView) findViewById(R.id.listView);
myList.setAdapter(myCursorAdapter);
}
}
And this is the DPAdapter class code:
package com.gobtron.database_test;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_MORPH = "'morph'";
public static final String KEY_LONGFRONDE = "'long_fronde'";
public static final String KEY_FORMELIMBE = "'forme_limbe'";
public static final String KEY_DISPOSFRONDE = "'dispos_fronde'";
public static final String KEY_DESC = "'description'";
public static final String KEY_DESCHOIX = "'desc_choix'";
public static final String KEY_DESCHOIX2 = "'desc_choix2'";
public static final String KEY_NOM = "'nom'";
public static final String[] ALL_KEYS ={KEY_ROWID, KEY_MORPH, KEY_LONGFRONDE, KEY_FORMELIMBE, KEY_DISPOSFRONDE, KEY_DESC, KEY_DESCHOIX, KEY_DESCHOIX2, KEY_NOM};
public static final String[] ALL_KEYS2 = {"_id", "'long_fronde'"};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_MORPH = 1;
public static final int COL_LONGFRONDE = 2;
public static final int COL_FORMELIMBE = 3;
public static final int COL_DISPOSFRONDE = 4;
public static final int COL_DESC = 5;
public static final int COL_DESCHOIX = 6;
public static final int COL_DESCHOIX2 = 7;
public static final int COL_NOM = 8;
// DataBase info:
public static final String DATABASE_NAME = "fougeres_db";
public static final String DATABASE_TABLE = "mono_dimo";
public static final int DATABASE_VERSION = 3; // 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, "
+ KEY_NOM + " TEXT NOT NULL, "
+ KEY_DESC + " 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 task, String date) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NOM, task);
initialValues.put(KEY_MORPH, date);
// 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(DATABASE_TABLE, ALL_KEYS, where, null, null, null, null);
DatabaseUtils.dumpCursor(c);
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 task, String date) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NOM, task);
newValues.put(KEY_MORPH, date);
// 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);
}
}
}
I don't get why my cursor is empty... I think it opens the database correctly, and the table too.
Well... I'm new to java so it is probably something stupid i'm missing.
You are trying to insert a value with key KEY_MORTH, however there is no field with this Key in your table
this:
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY , "
+ KEY_NOM + " TEXT NOT NULL, "
+ KEY_DESC + " TEXT"
+ ");";
needs to be
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NOM + " TEXT NOT NULL, "
+ KEY_DESC + " TEXT, "
+ KEY_MORTH + " TEXT "
+ ");";
You will need to update your db version or clear your data for this to take effect
Ok, turns out that my database was simply put in the wrong place. I needed to open the Android Device Monitor, then go the File Explorer, then put my existing database to /data/data/my package name/databases/

Error parsing XML - not well formed (invalid token)

I have already checked the other XML files for errors, however this is the file that the error message is saying the error is in. There is also a message that pops up whenever I try to run the app that says, "Files under the build folder are generated and should not be edited".
package com.example.drive.drivercorder;
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;
public class DBAdapter {
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_DRIVETIME = "Drive Time";
public static final String KEY_NIGHTORDAY = "Time of Day";
public static final int COL_DRIVETIME = 1;
public static final int COL_NIGHTORDAY = 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_DRIVETIME, KEY_NIGHTORDAY, };
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_DRIVETIME + " integer not null, "
+ KEY_NIGHTORDAY + " text not null "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
public long insertRow(int drivetime, String nightorday) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DRIVETIME, Drive Time);
initialValues.put(KEY_NIGHTORDAY, Time of Day);
return db.insert(DATABASE_TABLE, null, initialValues);
}
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();
}
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;
}
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;
}
public boolean updateRow(long rowId, String drivetime, String nightorday) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_DRIVETIME, Drive Time);
newValues.put(KEY_NIGHTORDAY, Time of Day);
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!");
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(_db);
}
}
}
There is also a message that pops up whenever I try to run the app that says, "Files under the build folder are generated and should not be edited".
I think you are changing the .class file in debug/DDMS mode or something like that. Please check and make sure to edit your .java file instead.
Posting your relevant logcat messages and also the XML file in question might help understand the problem.

No data retrieved if open sqlite more than once

When I add data into sqlite and open it for the first time, the data inside will be displayed. However, if I try opening it again nothing will show up even though there is data inside. May I know what is the problem?
Class that performs the activity:
public class Watchlist extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DatabaseHandler.TABLE_ITEM;
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from sqlite");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
DatabaseHandler db = new DatabaseHandler(this.getApplicationContext());
newDB = db.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT * FROM " + tableName, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String pid = c.getString(c.getColumnIndex("id"));
String name = c.getString(c.getColumnIndex("name"));
String price = c.getString(c.getColumnIndex("price"));
String date = c.getString(c.getColumnIndex("created_at"));
Log.d("pid",pid);
results.add("Name: " + name + "\n Price: " + price + "\n Date posted: " + date);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
Database handler:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "itemManager";
// table name
public static final String TABLE_ITEM = "item";
// Item Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PRICE = "price";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_ITEM + "("
+ KEY_ID + " INTEGER PRIMARY KEY autoincrement,"
+ KEY_NAME + " TEXT, "
+ KEY_PRICE + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_ITEM_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEM);
// Create tables again
onCreate(db);
}
/**
* Storing item details in database
* */
public void addItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getName()); // item name
values.put(KEY_PRICE, item.getPrice()); // item price
values.put(KEY_CREATED_AT, item.getDate()); // Created At
// Inserting Row
db.insert(TABLE_ITEM, null, values);
db.close(); // Closing database connection
}
/**
* Getting item data from database
* */
public List<Items> getAllItems(){
List<Items> itemList = new ArrayList<Items>();
String selectQuery = "SELECT * FROM " + TABLE_ITEM;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
if (cursor.moveToFirst()) {
do {
Items item = new Items();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDate(cursor.getString(2));
// Adding item to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
/**
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_ITEM;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
// Updating item
public int updateItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getName());
values.put(KEY_PRICE, item.getPrice());
values.put(KEY_CREATED_AT, item.getDate());
// updating row
return db.update(TABLE_ITEM, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
}
// Deleting item
public void deleteItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEM, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
db.close();
}
}
Well, don't you delete all the records before closing the database?
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
That would explain that behaviour.

SQLite database works on emulator but not on device

I am using sqlite database in my android application. I am pre-creating the database in the databases folder in android. The databases is created and works fine in the emulator but when I run the same code in my phone I get errors.
Here is the code on how I pre-create the database in the databases folder.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SavingData.mainActivity = this;
try {
String destPath = "/data/data/" + getPackageName() + "/databases";
File f = new File(destPath);
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
// ---copy the db from the assets folder into
// the databases folder---
CopyDB(getBaseContext().getAssets().open("exercisedatedb"),
new FileOutputStream(destPath + "/ExerciseDateDB"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
// ---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
Here is the errors I get:
04-01 12:51:12.503: E/SQLiteLog(26823): (1) no such column: date
04-01 12:51:12.503: D/AndroidRuntime(26823): Shutting down VM
04-01 12:51:12.503: W/dalvikvm(26823): threadid=1: thread exiting with uncaught exception (group=0x40f722a0)
04-01 12:51:12.508: E/AndroidRuntime(26823): FATAL EXCEPTION: main
04-01 12:51:12.508: E/AndroidRuntime(26823): android.database.sqlite.SQLiteException: no such column: date (code 1): , while compiling: SELECT id, date FROM dates
04-01 12:51:12.508: E/AndroidRuntime(26823): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
04-01 12:51:12.508: E/AndroidRuntime(26823): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1013)
04-01 12:51:12.508: E/AndroidRuntime(26823): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:624)
Here is how I insert data to database:
public void insertDate(String date) {
// TODO Auto-generated method stub
db.open();
long id = db.insertDate(date);
db.close();
}
Here is my DBAdapter class:
public class DBAdapter {
static final String KEY_ROWID = "id";
static final String KEY_DATE = "date";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "ExerciseDateDB";
static final String DATABASE_TABLE = "dates";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE = "create table dates (id integer primary key autoincrement, "
+ "date text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#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 contacts");
onCreate(db);
}
}
// ---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close() {
DBHelper.close();
}
// ---insert a Date into the database---
public long insertDate(String date) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
return db.insert(DATABASE_TABLE, null, initialValues);
}
// ---deletes a particular date---
public boolean deleteDate(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
// ---retrieves all the score---
public Cursor getAllDate() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_DATE}, null, null, null, null, null);
}
// ---retrieves a particular score---
public Cursor getDate(long rowId) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_DATE}, KEY_ROWID + "= " + rowId + "",
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
// ---updates a score---
public boolean updateDate(long rowId, String date) {
ContentValues args = new ContentValues();
args.put(KEY_DATE, date);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
This is my database solution. It is all contained in one class.
Too call it the syntax is...
DatabaseManager mDatabase = DatabaseManager.getInstance();
public class DatabaseManager {
private static DatabaseManager instance;
private final String DB_NAME = "singoff_database";
private final int DB_VERSION = 1;
private final String GAME_TABLE_NAME = "game_table";
private final String GAME_ID = "gameid";
private final String GAME_OPPONENT_ID = "opponent";
private final String GAME_TRACK = "track";
private final String GAME_FILE_PATH = "filepath";
private final String GAME_PICTURE = "picture";
private final String GAME_GUESSES = "guesses";
private final String GAME_DATE = "date";
private SQLiteDatabase mDb;
private Context context;
private DatabaseManager(Context context) {
this.context = context;
//create new or open database
DatabaseHelper helper = new DatabaseHelper(context);
this.mDb = helper.getWritableDatabase();
}
public synchronized static DatabaseManager getInstance() {
if (instance == null) {
Context context = Main.getInstance();
instance = new DatabaseManager(context);
}
return instance;
}
//__________________________________________________________________________________________//
//GAME LIST HANDLING STATEMENTS
public synchronized void addGame(String gID, String oID, String track,
String path, byte[] thumb, String datetime) {
ContentValues values = new ContentValues();
values.put(GAME_ID, gID);
values.put(GAME_OPPONENT_ID, oID);
values.put(GAME_TRACK, track);
values.put(GAME_FILE_PATH, path);
values.put(GAME_PICTURE, thumb);
values.put(GAME_DATE, datetime);
mDb.insert(GAME_TABLE_NAME, null, values);
}
public synchronized List<File> getGames() {
List<File> games = new ArrayList<File>();
Cursor cursor;
cursor = mDb.query(
GAME_TABLE_NAME,
new String[]{GAME_FILE_PATH},
null, null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
File file = new File(cursor.getString(0));
games.add(file);
} while (cursor.moveToNext());
}
cursor.close();
return games;
}
public synchronized Game getGame(String filepath) {
Cursor cursor;
//Game game = null;
Bitmap picture = null;
byte[] blob;
cursor = mDb.query(
GAME_TABLE_NAME,
new String[]{
GAME_OPPONENT_ID,
GAME_FILE_PATH,
GAME_PICTURE,
GAME_DATE},
GAME_FILE_PATH + "=?",
new String[]{filepath},
null, null, null);
if (cursor.moveToNext()) {
blob = cursor.getBlob(2);
if (blob != null) {
picture = BitmapFactory.decodeByteArray(blob, 0, blob.length);
}
//game = new Game(mContext, new File(filepath), cursor.getString(0), picture);
}
return null;
}
public void updateGame(String filepath, gameColumn col,
Object object) {
ContentValues values = new ContentValues();
switch (col) {
case GAME_PICTURE:
Bitmap picture = (Bitmap) object;
ByteArrayOutputStream out = new ByteArrayOutputStream();
picture.compress(Bitmap.CompressFormat.PNG, 100, out);
values.put(GAME_PICTURE, out.toByteArray());
break;
default:
return;
}
mDb.update(GAME_TABLE_NAME, values, GAME_FILE_PATH + "=?", new String[]{filepath});
}
public synchronized void removeGame(String filepath) {
mDb.delete(GAME_TABLE_NAME, GAME_FILE_PATH + "=?", new String[]{filepath});
}
public enum gameColumn {
GAME_TABLE_NAME, GAME_OPPONENT_ID, GAME_FILE_PATH,
GAME_PICTURE, GAME_DATE
}
//__________________________________________________________________________________________//
//--------------------------------------------------------------------------------------------------
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createGameTableQuery = " CREATE TABLE IF NOT EXISTS "
+ GAME_TABLE_NAME + " ("
+ GAME_ID + " INTEGER, "
+ GAME_OPPONENT_ID + " VARCHAR(20), "
+ GAME_TRACK + " VARCHAR(30), "
+ GAME_FILE_PATH + " VARCHAR(50), "
+ GAME_PICTURE + " BLOB, "
+ GAME_GUESSES + " VARCHAR, "
+ GAME_DATE + " VARCHAR(50)"
+ ");";
//create game table
db.execSQL(createGameTableQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//TODO
}
}
}
Create a Database Object :
public class Database extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Exampe.db";
private static final int DATABASE_VERSION = 1;
public static final String ID = "_id";
public static final String NAME = "name";
public static final String UUID = "uuid";
public static final String TABLE_NAME = "Example Something";
private static final String DATABASE_CREATE = "create table "
+ TABLE_NAME + "( " + ID
+ " integer primary key autoincrement, " + NAME
+ " text not null, " + UUID
+ " text not null);";
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(Database.class.getName(), "Upgrading database from version " + oldVersion + "to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
}
Now where you call it
private SQLiteDatabase database;
private Database dbHelper;
private String[] allColumns = { Database.ID, Database.NAME};
public String ExampleSaveName(String name) {
database = dbHelper.getReadableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("uuid", uuid);
long insertId = database.insert(Database.TABLE_NAME, null, values);
Cursor cursor = database.query(Database.TABLE_NAME, allColumns, Database.ID + " = " + insertId, null,null, null, null);
cursor.moveToFirst();
return cursorToName(cursor);
}
}
The problem was solved by uninstalling the application from my device.

Categories