Showing strings from a SQL file in java - java

I have a SQL file with some data that I want to show in my app, the data will be shown in a list view.
I want to include the SQL file in the apk.
I have three questions:
Is including the SQL file with the apk is the best option or is there a better one?
If putting it in the apk is the best option, where do I put it?
How do I get the strings from the file and show them in the app?
Thanks for the help!

So am really sure what you truly need is an SQLite in android :
Now if that is so, then what you need is to create an adapter class as seen below :
package extension.yourappname.whatever;
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.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String TAG = "DBAdapter";
//public static final String DATABASE_NAME = "my_db";
//public static final String DATABASE_TABLE = "contacts";
//public static final int DATABASE_VERSION = 1;
public static final String START_TBL_CREATION = "create table "+Appiah.DATABASE_TABLE+" (_id integer primary key autoincrement, ";
public static final String [] TABLE_COLUMNS_TO_BE_CREATED = new String []{
KEY_NAME+" text not null, ",
KEY_EMAIL+" text not null"
};
public static final String END_TBL_CREATION = ");";
private static final String DATABASE_CREATE = START_TBL_CREATION
+ TABLE_COLUMNS_TO_BE_CREATED[0]
+ TABLE_COLUMNS_TO_BE_CREATED[1]
+ END_TBL_CREATION;
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter (Context ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);//there would be an error initially but just keep going...
}
private static class DatabaseHelper extends SQLiteOpenHelper{//after importing for "SQLiteOpenHelper", Add unimplemented methods
DatabaseHelper(Context context){
super (context, Appiah.DATABASE_NAME, null, Appiah.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 SQLiteException{
db = DBHelper.getWritableDatabase();
return this;
}
//closes the database
public void close(){
DBHelper.close();
}
//insert a contact into the database
public long insertContact(String name, String email){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EMAIL, email);
return db.insert(Appiah.DATABASE_TABLE, null, initialValues);
}
//deletes a particular contact
public boolean deleteContact(long rowId){
String whereClause = KEY_ROWID + "=" + rowId;
String[] whereArgs = null;
return db.delete(Appiah.DATABASE_TABLE, whereClause, whereArgs) > 0;
}
//retrieves all the contacts
public Cursor getAllContacts(){
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
return db.query(Appiah.DATABASE_TABLE, columns, selection, selectionArgs, groupBy, having, orderBy);
}
//retrieve a particular contact with ID as input
public Cursor getContact_with_ID(long rowId) throws SQLException {
boolean distinct = true;
String table = Appiah.DATABASE_TABLE;
String [] columns = new String []{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = KEY_ROWID + "=" + rowId;
String [] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
Cursor mCursor = db.query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor getContact_with_nameEntered(String name_str) throws SQLException {
boolean distinct = true;
String table = Appiah.DATABASE_TABLE;
String [] columns = new String []{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = KEY_NAME + "=" + name_str;//check again and do "%" thing to expand scope and increase chances of a name getting found or populated
String [] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
Cursor mCursor = db.query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
//update a contact
public boolean updateContact(long rowId, String name, String email){
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_EMAIL, email);
String table = Appiah.DATABASE_TABLE;
ContentValues values = args;
String whereClause = KEY_ROWID + "=" + rowId;
String []whereArgs = null;
return db.update(table, values, whereClause, whereArgs) > 0;
}
/*
TO USE ANY OF THE ABOVE METHODS :
1. type this before in your "onCreate()" : DBAdapter db = new DBAdapter(this);
2. in the special case of getting all contacts to display : do the ff :
db.open();
Cursor c = db.getAllContacts();
if(c.moveToFirst()){
do{
textView.setText("ID : " + c.getString(0) + "\nName : " + c.getString(1) + "\nEmail Address : " + c.getString(2) );
}while(c.moveToNext());//the "while" added ensures that, the looping process occurs
}
db.close();
*/
}

Related

Couldn't read row 0, col 3 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it

I am having difficulty inserting image in my sqlite database. There are no syntax errors in my code. After I run it, the app automatically force stops. The logcat shows:
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 3 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at com.synergy88studios.catalogapp.DatabaseHandler.getAllItemsInList(DatabaseHandler.java:86)
at com.synergy88studios.catalogapp.MainActivity.onCreate(MainActivity.java:56)
Here is my method in getAllItemsInList in my DatabaseHandler.class
public List<Item> getAllItemsInList() {
List<Item> itemList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.set_id(Integer.parseInt(cursor.getString(0)));
item.set_name(cursor.getString(1));
item.set_description(cursor.getString(2));
item.set_image(cursor.getBlob(3));
// Adding contact to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
In my MainActivity, I simply call the method.
items = db.getAllItemsInList();
EDIT
DatabaseHandler.class
public class DatabaseHandler extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "CatalogItems";
public static final String TABLE_ITEMS = "Items";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_DESC = "description";
public static final String KEY_IMAGE = "image";
public static final String[] ALL_KEYS = new String[] {KEY_ID, KEY_NAME, KEY_DESC};
//private static final String KEY_IMAGE = "image";
public DatabaseHandler(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db){
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "( "
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_DESC + " TEXT, " + KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_ITEMS);
onCreate(db);
}
public void addItems(Item item){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.get_name());
values.put(KEY_DESC, item.get_description());
values.put(KEY_IMAGE, item.get_image());
db.insert(TABLE_ITEMS, null ,values);
db.close();
}
Item getItem(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
KEY_NAME, KEY_DESC , KEY_IMAGE}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
Item item = new Item(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getBlob(3));
return item;
}
void deleteAllItems() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+ TABLE_ITEMS);
}
public List<Item> getAllItemsInList() {
List<Item> itemList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.set_id(Integer.parseInt(cursor.getString(0)));
item.set_name(cursor.getString(1));
item.set_description(cursor.getString(2));
item.set_image(cursor.getBlob(3));
// Adding contact to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
public Cursor getAllRows() {
SQLiteDatabase db = this.getWritableDatabase();
String where = null;
Cursor c = db.query(true, TABLE_ITEMS, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public int getItemsCount(){
String countQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
return cursor.getCount();
}
public int updateItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.get_name());
values.put(KEY_DESC, item.get_description());
values.put(KEY_IMAGE, item.get_image());
// updating row
return db.update(TABLE_ITEMS, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.get_id()) });
}
public void deleteContact(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEMS, KEY_ID + " = ?",
new String[] { String.valueOf(item.get_id()) });
db.close();
}
}
I hope someone can explain to me what happens. I can post my other classes for reference.
Don't store large data in an Android sqlite table. In particular, the CursorWindow only supports row data up to 2MB. If your row is larger, you can't access it.
Instead, store your blobs as files in the filesystem and store just the path in database.

How to read SQLite by cursor and display in textview

How to read and display "email" and "address" in HomeAcitivity TextView.
The database designed to be store only 1 row of data.
DatabaseHandler.java
package com.example.androidjhfong.library;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_database";
// Table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_ADDRESS = "address";
private static final String KEY_PHONE = "phone";
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_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_ADDRESS + " TEXT,"
+ KEY_PHONE + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_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_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String address, String phone, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_ADDRESS, address); // Address
values.put(KEY_PHONE, phone); // phone
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("address", cursor.getString(4));
user.put("phone", cursor.getString(5));
user.put("created_at", cursor.getString(6));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
/**
* Getting product status
**/
public String getData() {
String username;
String getdata = "SELECT name FROM " + TABLE_LOGIN;
//String[] columns = new String[]{ KEY_ID, KEY_NAME, KEY_ADDRESS, KEY_PHONE};
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(getdata, null);
cursor.moveToFirst();
username=cursor.getString(cursor.getColumnIndex("name"));
cursor.close();
db.close();
return username;
}
}
how to display the retrieve the data and display in HomeActivity correctly?
HomeActivity
public class HomeActivity extends Activity implements OnItemSelectedListener{
TextView inputname
TextView inputemail;
TextView inputaddress;
Button btnPurchase;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ADDRESS = "address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Home);
inputname= (TextView) findViewById(R.id.qrpurchaseitem);
inputaddress = (TextView) findViewById(R.id.qrtextpurchaseaddress);
inputemail = (TextView) findViewById(R.id.qrtextpurchasecomment);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String, String> key = db.getUserDetails();
String text= DatabaseHandler.getUserDetails();
}
in your HomeActivty add this both line
String email=db.getEmail()
String address=db.getAddress();
Now then you can use below method in you Database Handler class, just change variable name from below methods
public String getStartBal() {
Cursor cr=ourDatabase.rawQuery("SELECT "+KEY_START_BAL+" FROM "+DB_TABLE,null);
String sum="";
for(cr.moveToFirst();!cr.isAfterLast();cr.moveToNext()){
sum=cr.getString(cr.getColumnIndex(KEY_START_BAL));
}
cr.close();
return sum;
}

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.

NullPointerException at this.getReadableDatabase();

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.

SQLitedatabase crash after upgrade

I added 3 new columns to my Database from version 1 so I changed it to version 2 but now when I use an activity that uses my database my app crashes and shows this in the logcat.
04-02 18:41:09.013: E/AndroidRuntime(19171): FATAL EXCEPTION: main
04-02 18:41:09.013: E/AndroidRuntime(19171):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.fullfrontalgames.numberfighter/com.fullfrontalgames.numberfighter.AccountSettings}:
android.database.sqlite.SQLiteException: near "CREATE": syntax error
(code 1): , while compiling: create table NFDB( ID integer primary key
autoincrement,USERNAME text CREATE UNIQUE INDEX idx_keytype ON
tableName (USERNAME);USERNAME text,PASSWORD text,EMAIL
text,NUMBERINPUT text,SCORE text,FRIENDS text);
04-02 18:41:09.013: E/AndroidRuntime(19171): Caused by:
android.database.sqlite.SQLiteException: near "CREATE": syntax error
(code 1): , while compiling: create table NFDB( ID integer primary key
autoincrement,USERNAME text CREATE UNIQUE INDEX idx_keytype ON
tableName (USERNAME);USERNAME text,PASSWORD text,EMAIL
text,NUMBERINPUT text,SCORE text,FRIENDS text);
I can't see the syntax error anywhere and I have my DBHelper helperclass to drop my old table and make the new table.
here is my code of my DBAdapter and DBHelper classes
package com.fullfrontalgames.numberfighter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBAdapter
{
static final String DATABASE_NAME = "NFDB.db";
static final int DATABASE_VERSION = 2;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"NFDB"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text CREATE UNIQUE INDEX idx_keytype ON tableName (USERNAME);" +
"PASSWORD text,EMAIL text,NUMBERINPUT text,SCORE text,FRIENDS text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper DBHelper;
public DBAdapter(Context _context)
{
context = _context;
DBHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password,String email)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
newValues.put("EMAIL", email);
// Insert the row into your table
db.insert("NFDB", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String userName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("NFDB", where, new String[]{userName}) ;
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("NFDB", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("NFDB",updatedValues, where, new String[]{userName});
}
public String getData() {
String[] columns = new String[] { "ID", "USERNAME"};
Cursor c = db.query("NFDB", columns, null, null, null, null, null, null);
String result ="";
int iRow = c.getColumnIndex("ID");
int iName = c.getColumnIndex("USERNAME");
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iName) + "/n";
}
return result;
}
public String getUsername(String searchName) {
Cursor c = db.query("NFDB",
new String[] { "USERNAME" },
"USERNAME = ?",
new String[] { searchName },
null, null, null);
if (c.moveToNext())
return c.getString(0);
else
return "";
}
public void InsertScore(String Username,String Score)
{
ContentValues ScoreValues = new ContentValues();
ScoreValues.put("USERNAME", Username);
ScoreValues.put("SCORE", Score);
db.insert("NFDB", null, ScoreValues);
}
public String GetGameScore(String Username,String Score)
{
Cursor cursor = db.query("NFDB", null, "USERNAME",new String[]{Username,Score}, null, null, null);
cursor.moveToFirst();
cursor.close();
return Username;
}
public String GetAllScore()
{
String[] columns = new String[] {"ID","USERNAME","SCORE"};
Cursor cursor = db.query("NFDB", columns, null, null, null, null, null);
String result="";
int iRow = cursor.getColumnIndex("ID");
int iUsername = cursor.getColumnIndex("USERNAME");
int iScore = cursor.getColumnIndex("SCORE");
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
result = result + cursor.getString(iRow) + " " + cursor.getString(iUsername) + " " + cursor.getString(iScore) + "/n";
}
return result;
}
public void InsertNumber(String Username,String Number)
{
ContentValues NumberValues = new ContentValues();
NumberValues.put("USERNAME", Username);
NumberValues.put("NUMBERINPUT", Number);
db.insert("NFDB", null, NumberValues);
}
public String GetNumber(String Username,String Number)
{
Cursor cursor = db.query("NFDB", null, "USERNAME", new String[]{Username,Number}, null, null, null, null);
cursor.moveToFirst();
cursor.close();
return Username;
}
public String GetAllNumbers()
{
String[] columns = new String[] {"ID","USERNAME","NUMBERINPUT"};
Cursor cursor = db.query("NFDB", columns, null, null, null, null, null, null);
String result="";
int iRow = cursor.getColumnIndex("ID");
int iName = cursor.getColumnIndex("USERNAME");
int iNumber = cursor.getColumnIndex("NUMBERINPUT");
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
result = result + cursor.getString(iRow) + " " + cursor.getString(iName) + " " + cursor.getString(iNumber) + "/n";
}
return result;
}
public void InsertFriends (String Username,String Friends)
{
ContentValues FriendValues = new ContentValues();
FriendValues.put("USERNAME", Username);
FriendValues.put("FRIENDS", Friends);
db.insert("NFDB", null, FriendValues);
}
public int DeleteFriends(String Username,String Friends)
{
String where = "USERNAME=?,FRIENDS=?";
int numberOfEntriesDeleted = db.delete("NFDB", where, new String[]{Username,Friends});
return numberOfEntriesDeleted;
}
public String GetFriend(String Username,String Friend)
{
Cursor cursor = db.query("NFDB", null, "USERNAME", new String[]{Username,Friend}, null, null, null, null);
cursor.moveToFirst();
cursor.close();
return Username;
}
public String GetAllFriends()
{
String[] columns = new String[] {"ID","USERNAME","FRIENDS"};
Cursor cursor = db.query("NFDB", columns, null, null, null, null, null, null);
String result="";
int iRow = cursor.getColumnIndex("ID");
int iName = cursor.getColumnIndex("USERNAME");
int iFriends = cursor.getColumnIndex("FRIENDS");
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
result = result + cursor.getString(iRow) + " " + cursor.getString(iName) + " " + cursor.getString(iFriends) + "/n";
}
return result;
}
}
package com.fullfrontalgames.numberfighter;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// TODO Auto-generated constructor stub
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(DBAdapter.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "NFDB");
// Create a new one.
onCreate(_db);
}
}
Your DML statement is incorrect. Index creation cannot be used in CREATE TABLE statement. It must have its own statement.
You have to correct it like this:
DATABASE_CREATE = "create table NFDB("
+ "ID integer primary key autoincrement, "
+ "USERNAME text, PASSWORD text, "
+ "EMAIL text, NUMBERINPUT text, "
+ "SCORE text, FRIENDS text)";
and second statement:
CREATE_INDEX_KEYTYPE = "CREATE UNIQUE INDEX idx_keytype ON tableName(USERNAME)";
And finally, in your SQLiteOpenHelper subclass implementation perform following actions:
_db.execSQL(DBAdapter.DATABASE_CREATE);
_db.execSQL(DBAdapter.CREATE_INDEX_KEYTYPE);

Categories