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.
Related
I have got stuck in the above-mentioned error message in Android Studio. My Database is a simple one
1st column: Name TEXT PRIMARY KEY
2nd column: Price TEXT
I have already gone through the answers to the same question in StackOverflow but couldn't resolve the error.
I am quoting my DataBaseHelper class and insertActivity here:
private static final String DATABASE_NAME = "ItemDatabase";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "Items";
private static final String COLUMN_NAME = "Name";
private static final String COLUMN_PRICE = "Price";
DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE_NAME + "(" + COLUMN_NAME + " TEXT NOT NULL PRIMARY KEY, " + COLUMN_PRICE + " TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME + ";";
sqLiteDatabase.execSQL(sql);
onCreate(sqLiteDatabase);
}
boolean addItem(String itemName, String itemPrice) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, itemName);
contentValues.put(COLUMN_PRICE, itemPrice);
SQLiteDatabase db = this.getWritableDatabase();
boolean b = db.insert(TABLE_NAME, null, contentValues) != -1;
db.close();
return b;
}
Cursor getPrice(String itemName) {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery(" SELECT Price FROM Items WHERE Name= ? ", new String[]{itemName});
}
Cursor updatePrice(String itemName, String itemPrice)
{
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery(" UPDATE Items SET Price= ? WHERE Name= ? ", new String[]{itemPrice,itemName});
}
public List<String> getName(){
List<String> list = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
}
public class insertActivity extends AppCompatActivity {
EditText itemName,itemPrice;
Button buttonInsert;
boolean b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
itemName= findViewById(R.id.itemName);
itemPrice= findViewById(R.id.itemPrice);
buttonInsert=findViewById(R.id.buttonInsert);
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
final DataBaseHelper dataBaseHelper =new DataBaseHelper(getApplicationContext());
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
b = dataBaseHelper.addItem(Name,Price);
}catch (Exception e)
{
e.printStackTrace();
}
if( b )
{
Toast.makeText(getApplicationContext(),"Item Inserted Successfully ",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getApplicationContext(),"Item Insertion Failed ",Toast.LENGTH_SHORT).show();
}
});
}
}
error:
W/System.err: at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:746)
W/System.err: at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:754)
at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1770)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1698)
at com.anirbit.anirbitadak.nirman.DataBaseHelper.addItem(DataBaseHelper.java:45)
W/System.err: at com.anirbit.anirbitadak.nirman.insertActivity$1.onClick(insertActivity.java:39)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25881)
W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)```
These lines:
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
assign to the variables Name and Price the text of the EditTexts itemName and itemPrice when the insertActivity loads (maybe they are just empty strings) and they are never changed.
So when you click the button the listener by calling dataBaseHelper.addItem(Name,Price) tries to insert the same values in the table and this results to the error you get because since the column Name is the Primary Key of the table it must be unique.
What you must do is move these lines inside the listener:
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
try {
................................................
}
so when you click the button the correct values are retrieved from the EditTexts and then inserted in the table.
Hi I am new to android development and I am attempting to make an app which stores appointments. My fragments and activities are all fine however I am trying to work out how to check my sqlite database that the string I am trying to enter isn't already stored as a unique string already, any help is much appreciated.
Here is my code for the database so far.
public class MyDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4;
private static final String DATABASE_NAME = "appointments.db";
public static final String TABLE_APPOINTMENTS = "appointments";
public static final String COLUMN_DAY = "day";
public static final String COLUMN_MONTH = "month";
public static final String COLUMN_YEAR = "year";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_TIME = "time";
public static final String COLUMN_DESCRIPTION = "details";
public MyDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_APPOINTMENTS
+ "(" + COLUMN_DAY + " INTEGER, " + COLUMN_MONTH + " INTEGER, " + COLUMN_YEAR + " INTEGER, "
+ COLUMN_TITLE + " TEXT NOT NULL UNIQUE, " + COLUMN_TIME + " TEXT, " + COLUMN_DESCRIPTION + " TEXT" + ")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_APPOINTMENTS);
onCreate(db);
}
public void addAppointment(Appointment app){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DAY, app.get_day());
values.put(COLUMN_MONTH, app.get_month());
values.put(COLUMN_YEAR, app.get_year());
values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
values.put(COLUMN_TIME, app.get_time());
values.put(COLUMN_DESCRIPTION, app.get_details());
db.insert(TABLE_APPOINTMENTS, null, values);
db.close();
}
}
Call this method and check return true mean its exist otherwise not.
public boolean checkAppointmentExist(String name){
booolean isExist = false;
String selection = COLUMN_TITLE + " = ? ";
String[] selectionArgs = new String[]{name};
Cursor cursor = database.query(TABLE_APPOINTMENTS, null, selection, selectionArgs, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
isExist = true;
}
}
return isExist;
}
public void addAppointment(Appointment app){
if(!checkAppointmentExist(app.get_title())){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DAY, app.get_day());
values.put(COLUMN_MONTH, app.get_month());
values.put(COLUMN_YEAR, app.get_year());
values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
values.put(COLUMN_TIME, app.get_time());
values.put(COLUMN_DESCRIPTION, app.get_details());
db.insert(TABLE_APPOINTMENTS, null, values);
db.close();
}
}
This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 7 years ago.
I have two tables: user and balance.
User DAO:
public class NewUserDAO {
public static final String TAG = "NewUserDAO";
public static final String TABLE_NEWUSER = "newUser";
//database fields
private SQLiteDatabase mDataBase;
private DatabaseHandler mDbHelper;
private Context mContext;
private String [] mAllColumns = {
DatabaseHandler.COLUMN_NEWUSER_ID,
DatabaseHandler.COLUMN_NEWUSER_NAME, DatabaseHandler.COLUMN_NEW_USER_PASSWORD,
DatabaseHandler.COLUMN_NEW_USER_AGE };
public NewUserDAO(Context context){
this.mContext = context;
mDbHelper = new DatabaseHandler(context);
try{
open();
} catch (SQLException e){
Log.e(TAG,"SQLexception on opening database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException{
mDataBase = mDbHelper.getWritableDatabase();
}
public void close(){
mDbHelper.close();
}
public void createNewUser(NewUserTable newUserTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_NEWUSER_NAME,newUserTable.getName());
values.put(DatabaseHandler.COLUMN_NEW_USER_PASSWORD, newUserTable.getPassword());
values.put(DatabaseHandler.COLUMN_NEW_USER_AGE, newUserTable.getAge());
mDataBase.insert(TABLE_NEWUSER, null, values);
mDataBase.close();
}
}
balance DAO:
public class BalanceDAO {
public static final String TAG = "BalanceDAO";
public static final String TABLE_BALANCE = "balanceOfUser";
private Context mContext;
//Database fields
private SQLiteDatabase mDatabase;
private DatabaseHandler mDhelper;
private String[] mAllColumns = {
DatabaseHandler.COLUMN_BALANCE_ID,
DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,
DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,
DatabaseHandler.COLUMN_BALANCE_NEW_USER_ID
};
public BalanceDAO (Context context){
mDhelper = new DatabaseHandler(context);
this.mContext = context;
try{
open();
}
catch (SQLException e){
Log.e(TAG, "SQLException on openning database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDhelper.getWritableDatabase();
}
public void close(){
mDhelper.close();
}
public void createBalance (BalanceTable balanceTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,balanceTable.getDollarBalance());
values.put(DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,balanceTable.getRubBalance());
mDatabase.insert(TABLE_BALANCE, null, values);
mDatabase.close();
}
}
And SQLiteOpenHelper class:
public class DatabaseHandler extends SQLiteOpenHelper {
//COLUMNS OF THE NEW USER TABLE
public static final String TABLE_NEWUSER = "newUser";
public static final String COLUMN_NEWUSER_ID = "id";
public static final String COLUMN_NEWUSER_NAME = "name";
public static final String COLUMN_NEW_USER_PASSWORD = "password";
public static final String COLUMN_NEW_USER_AGE = "age";
//COLUMNS OF THE BALANCE TABLE
public static final String COLUMN_BALANCE_ID = "id";
public static final String TABLE_BALANCE = "balanceOfUser";
public static final String COLUMN_BALANCE_DOLLARBALANCE = "dollarBalance";
public static final String COLUMN_BALANCE_RUBBALANCE = "rubBalance";
public static final String COLUMN_BALANCE_NEW_USER_ID = "newUserId";
private static final String DATABASE_NAME = "webStore";
private static final int DATABASE_VERSION = 1;
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_NEWUSER = "CREATE TABLE " + TABLE_NEWUSER + "("
+ COLUMN_NEWUSER_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_NEWUSER_NAME + " TEXT not null,"
+ COLUMN_NEW_USER_PASSWORD + " TEXT not null,"
+ COLUMN_NEW_USER_AGE + " INTEGER"
+ ")";
db.execSQL(SQL_CREATE_NEWUSER);
String SQL_CREATE_BALANCE = "CREATE TABLE " + TABLE_BALANCE + "("
+ COLUMN_BALANCE_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_BALANCE_DOLLARBALANCE + " INTEGER,"
+ COLUMN_BALANCE_RUBBALANCE + " INTEGER,"
+ COLUMN_BALANCE_NEW_USER_ID + " INTEGER," + "FOREIGN KEY("+COLUMN_BALANCE_NEW_USER_ID+") REFERENCES "
+ TABLE_NEWUSER + "(id) "+ ")" ;
db.execSQL(SQL_CREATE_BALANCE);
onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWUSER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BALANCE);
}
}
I want to join user and balance tables. How can i do? When i call Create Method, i have exception.
public void CreateUser(View view) {
etName = (EditText)findViewById(R.id.etName);
etPassword = (EditText)findViewById(R.id.etPassword);
etAge = (EditText)findViewById(R.id.etAge);
String name = String.valueOf(etName.getText());
String password = String.valueOf(etPassword.getText());
int age = Integer.parseInt(String.valueOf(etAge.getText()));
BalanceTable balanceTable = new BalanceTable(0,0);
NewUserTable newUserTable = new NewUserTable(name,password,age);
//write to database of user from our edit texts
DatabaseHandler databaseHandler = new DatabaseHandler(this);
Log.d("Insert: ", "Inserting ..");
NewUserDAO dbForUser = new NewUserDAO(this);
dbForUser.createNewUser(newUserTable);
BalanceDAO balanceDAO = new BalanceDAO(this);
balanceDAO.createBalance(balanceTable);
}
From edit text i take data. Help please
There are a few types if join, inner (which I think is what you want) which shows the data that matches, left showing all data from the first table and any additional data from the second table that meets the on condition or right which is shows all from the second table and any form the right that matches.
to Join two table you must use a statement such as
"SELECT <all the values you want> "+
" FROM users" +
" left join balance" +
" ON users.id=balance.userid " +
" where <some condition> "+
" order by gmttimestamp ;"; "
this will give you result set of mixed tables
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.
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.