This is the class that I´m using
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_FILE = "Database.db";
private static final String TABLE = "Estudiantes";
private static final String FIELD_ID = "id";
private static final String FIELD_NAME = "nombre";
private static final String FIELD_GRADE = "calificacion";
public DBHelper(Context context){
super(context, DB_FILE, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE + "(" +
FIELD_ID + " INTEGER PRIMARY KEY, " +
FIELD_NAME + " TEXT, " +
FIELD_GRADE + " INTEGER);";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS ?";
String[] params = {TABLE};
db.execSQL(query, params);
}
public void save(String nombre, int calificacion){
SQLiteDatabase db = getWritableDatabase();
ContentValues valores = new ContentValues();
valores.put(FIELD_NAME, nombre);
valores.put(FIELD_GRADE, calificacion);
db.insert(TABLE, null, valores);
}
public int delete(String nombre){
SQLiteDatabase db = getWritableDatabase();
String clause = FIELD_NAME + " = ?";
String[] args = {nombre};
return db.delete(TABLE, clause, args);
}
public int find(String nombre){
SQLiteDatabase db = getReadableDatabase();
String filtrito = FIELD_NAME + " = ?";
String[] args = {nombre};
Cursor c = db.query(TABLE, null, filtrito, args, null, null, null);
int result = -1;
if(c.moveToFirst()) {
result = c.getInt(2);
}
return result;
}
}
This is the error message I get:
E/SQLiteLog: (1) table Estudiantes has no column named calificacion
E/SQLiteDatabase: Error inserting calificacion=80 nombre=Fer
android.database.sqlite.SQLiteException:
table Estudiantes has no column named calificacion (code 1): , while compiling:
INSERT INTO Estudiantes(calificacion,nombre) VALUES (?,?)
It looks like that you added calificacion column later in the database.
I would do one of the following:
Uninstalling and re-installing your app.
The best and better approach is to drop and recreate Estudiantes table in onUpdate method, and increase the db version wheneveryou change the schema.
Related
Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
// Table Name
public static final String TABLE_NAME = "Contacts";
// Table columns
public static final String ID = "ID";
public static final String Contact_Name = "Contact_Name";
public static final String Phone_Number = "Phone_Number";
public static final String Favourites = "Favourites";
// Database Information
static final String DB_NAME = "MessagePlus_Contacts";
// database version
static final int DB_VERSION = 1;
// Creating table query
private static final String CREATE_TABLE = "Create Table " + TABLE_NAME + "(" + ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Contact_Name + " TEXT NOT NULL, " + Phone_Number + " INT NOT NULL, " + Favourites + " Boolean NOT NULL);";
private static final String Show_Table = "Select * From " + TABLE_NAME;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void showData(SQLiteDatabase db){db.execSQL(Show_Table);}
public void insertData(String contactName, String phoneNumber,String favourites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Contact_Name, contactName);
values.put(DatabaseHelper.Phone_Number, phoneNumber);
values.put(DatabaseHelper.Favourites, favourites);
db.insert(DatabaseHelper.TABLE_NAME, null, values);
// close db connection
db.close();
}
public int addToFavourites(String favourites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Favourites, favourites);
// updating row
return db.update(DatabaseHelper.TABLE_NAME, values, DatabaseHelper.Phone_Number + " = ?", new String[]{favourites});
}
public int getCount() {
String countQuery = "SELECT * FROM " + DatabaseHelper.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
Modal
public class FavouritesHelper {
public String Name;
public String PhoneNumber;
public boolean Favourites;
public FavouritesHelper() {
}
public FavouritesHelper(String Name, String PhoneNumber, Boolean Favourites) {
this.Name = Name;
this.PhoneNumber = PhoneNumber;
this.Favourites = Favourites;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
public boolean getFavourites() {
return Favourites;
}
public void setFavourites(boolean Favourites) {
this.Favourites = Favourites;
}
}
This is my database helper and I'm trying to fetch the table in logcat but I don't know how to do that. I know the code is Select * from <tablename> but how do i implement that. I want to see all the data in my table.
Soltion:
Please follow the following steps:
First Step:
Make the below method in DatabaseHelper class:
public List<FavouritesHelper> getAllData() {
List<FavouritesHelper> data = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + FavouritesHelper.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FavouritesHelper alldata = new FavouritesHelper();
alldata.setName(cursor.getString(cursor.getColumnIndex(FavouritesHelper.Name)));
alldata.setPhoneNumber(cursor.getString(cursor.getColumnIndex(FavouritesHelper.PhoneNumber)));
alldata.setFavourites(cursor.getBoolean(cursor.getColumnIndex(FavouritesHelper.Favourites)));
data.add(alldata);
} while (cursor.moveToNext());
}
// close db connection
db.close();
// return notes list
return data;
}
Second Step:
In your activity:
declare a global object: List<FavouritesHelper> AllData inside your class.
Third Step:
then, add this AllData = new List<FavouritesHelper>(); in your onCreate()
Fourth Step:
write this in your activity after inserting data: AllData = database.getAllData();
Fifth Step:
Print it in log using below statement:
for(FavouritesHelper helper : AllData) {
Log.e("values : ", helper.getName() + ", " + helper.getPhoneNumber() + ", " + helper.getFavourites());
}
That's it.
Try it out. Hope it Helps.
As #pskink suggested you can use dumpCursor like this
create this method inside your DatabaseHelper class
public void dumpCursorInLogCat() {
//here first getting the readable database
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(Show_Table, null);
//here is how you can Dump cursor
DatabaseUtils.dumpCursor(cursor);
cursor.close();
}
and call this method in your activity whenever you want to show data in logcat
call it inside your activity like
new DatabaseHelper(your_activity_name.this).dumpCursorInLogCat();
Hello I was working with SQlite on my phone with android studio
I have a simple database like this :
DATABASE 1 :
public class myDbAdapter {
myDbHelper myhelper;
public myDbAdapter(Context context) {
myhelper = new myDbHelper(context);
}
public long insertData(String name, String ip, String port, String rele) {
SQLiteDatabase dbb = myhelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(myDbHelper.NAME, name);
/* ... same for more items ...*/
long id = dbb.insert(TABLE_NAME, null, contentValues);
return id;
}
public String getData() {
SQLiteDatabase db = myhelper.getWritableDatabase();
String[] columns = {myDbHelper.UID, myDbHelper.NAME, myDbHelper.IP, myDbHelper.PORT, myDbHelper.RELE, myDbHelper.Hash};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
int i = 0;
while (cursor.moveToNext()) {
i++;
int cid = cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
String name = cursor.getString(cursor.getColumnIndex(myDbHelper.NAME));
String ipE = cursor.getString(cursor.getColumnIndex(myDbHelper.IPE));
/* ... same for more items ...*/
buffer.append("*" + cid + "-" + name + "-" + ipE + "-" + port + "-" + rele + "\n");
}
List1.colu = i;
return buffer.toString();
}
public int delete(String uid) {
SQLiteDatabase db = myhelper.getWritableDatabase();
String delgrp = "DELETE FROM " + TABLE_NAME + " WHERE _id='" + uid + "'";
db.execSQL(delgrp);
return 1;
}
static class myDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "myDatabase"; // Database Name
public static final String TABLE_NAME = "Data"; // Table Name
private static final int DATABASE_Version = 1; // Database Version
private static final String UID = "_id"; // Column I (Primary Key)
/* ... same for more items ...*/
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
" (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " VARCHAR(255) ," + IPE + " VARCHAR(255) ," + TEST1 + " VARCHAR(255) ," + TEST2 + " VARCHAR(255) ," + Hash + " VARCHAR(225));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
private Context context;
public myDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context = context;
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
// Message.message(context,""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
// Message.message(context,"OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (Exception e) {
// Message.message(context,""+e);
}
}
}
I Wanted to add another TABLE to same database (MyDataBase)
So i created another java class named MyDbAdapter2
Same codes as above just changed class names and Table name
helper = new myDbAdapter(this);
helper2 = new myDbAdapter2(this);
DATABASE 2 :
public class myDbAdapter2 {
myDbHelper myhelper;
public myDbAdapter2(Context context) {
myhelper = new myDbHelper(context);
}
public long insertData(String name, String ip) {
/*...*/
}
public String getData() {
SQLiteDatabase db = myhelper.getWritableDatabase();
String[] columns = {myDbHelper.UID, myDbHelper.ITEM, myDbHelper.SUBITEM};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
int i = 0;
while (cursor.moveToNext()) {
i++;
int cid = cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
String name = cursor.getString(cursor.getColumnIndex(myDbHelper.ITEM));
String ipe = cursor.getString(cursor.getColumnIndex(myDbHelper.SUBITEM));
buffer.append("*" + cid + "-" + name + "-" + ipe + "\n");
}
// List1.colu=i;
return buffer.toString();
}
static class myDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "myDatabase"; // Database Name
public static final String TABLE_NAME = "Data2"; // Table Name
private static final int DATABASE_Version = 1; // Database Version
private static final String UID = "_id"; // Column I (Primary Key)
/*...*/ //Column II
// ... // Column III
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
" (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ITEM + " VARCHAR(255) ," + SUBITEM + " VARCHAR(225));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
private Context context;
public myDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context = context;
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
// Message.message(context,""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
// Message.message(context,"OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
}catch (Exception e) {
// Message.message(context,""+e);
}
}
}
}
When i try to access the other (Data2) database it cause a error !
android.database.sqlite.SQLiteException: no such table: Data2 (Sqlite code 1): , while compiling: SELECT _id, Item, SubItem FROM Data2, (OS error - 2:No such file or directory)
I Saw this on Log :
09-13 09:31:05.788 18454-18454/com.example.discopc.yubismart I/HwSecImmHelper: mSecurityInputMethodService is null
09-13 09:31:06.468 18454-18604/com.example.discopc.yubismart E/SQLiteLog: (1)
09-13 09:31:06.571 18454-18604/com.example.discopc.yubismart I/Process: Sending signal. PID: 18454 SIG: 9
Whats the problem ? First database works fine but second one not ,
Thanks.... ?
As you said - I Wanted to add another TABLE to same database (MyDataBase)
You should not use two different class for creating two different table in sqlite database. While executing one single of your adapter classes its creating one table and if your db version is same / different in adapter classes then one of two table would not be created / would be deleted.
Here db version is same that's why second table is not creating.
Create as many as your required tables inside onCreate() of your myDbHelper class and inside onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) execute drop table code for each table.
When you need another new table just create table as above and write code for drop table inside onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion).
You just need to remember for creating new tables or any structural change inside your sqlite database would be reflected only after changing the VERSION CODE of database.
You have created a database once with name MyDataBase having table Data.
You are again trying to create same MyDataBase with table Data2 that is causing the problem.
"I Want to create only 1 database , changing name to MyDataBase2 will work but why ?"
When you are changing name to MyDataBase2 it works as this one is a completely new database and you can create the Data2 table in it.
So if you want to create Data2 in your first version of database you have to create the table Data2 in it but not a completely new data base. If you want to know more about it please find it here.
I believe this answered your question.
I am making an ExpenseManger app for android and I've inserted records and now I want those records to be displayed ordered by datewise. How to do that?
Here's my piece of code with database.
Please tell how to properly insert date of creation automatically in column and later use it in select * statement. Thanks.
public class Databasehelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "items.db";
public static final String TABLE_NAME = "items_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "TYPE";
public static final String COL_3 = "NAME";
public static final String COL_4 = "PRICE";
public Databasehelper (Context context)
{
super ( context , DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase)
{
sqLiteDatabase.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, TYPE TEXT, NAME TEXT, PRICE INTEGER);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + DATABASE_NAME);
onCreate(db);
}
public boolean insertData(String type, String name, String price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, type);
contentValues.put(COL_3, name);
contentValues.put(COL_4, price);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public boolean updateData(String id,String type,String name,String price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,type);
contentValues.put(COL_3,name);
contentValues.put(COL_4,price);
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}
public Integer deleteData (String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
}
There isn't a specific TIMESTAMP type in SQLite, so you have a choice of using, say, text and storing the date in a sortable form, such as YYYY-MM-DD HH:MM:SS, or as an integer and storing a timestamp value manually. Use date/time functions to generate the values and System.currentTimeMillis to create a unix-like timestamp.
DateFormat sortable = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = Calendar.getInstance().getTime();
String timestampish = sortable.format(now);
int timestamp = System.currentTimeMillis;
To use, add either a TEXT column or an INTEGER column to your table. See SQLite Date/Time functions also.
SELECT * FROM blah ORDER BY timestamp DESC
This will give you the most recent first, take out the DESC to get in chronological order.
I'm coding for the first time in Android (Java) an application using a sqlite database.
Two activities must save some informations so I use in both a MySQLiteHelper to access the database.
I read here that building SQLiteOpenHelper as static data member could be a good practice so I did this.
The static factory method ensures that there exists only one DatabaseHelper instance at any time.
I create in each activity a SQLiteOpenHelper that uses the method getWritableDatabase() but I don't know where to use the close() method.
Should I put this method after every modification or once at the end of the activity ?
Thank you =)
You need to create a class where you put all your common methods, constants, variables, etc.
And then you would have to move the "getWritableDatabase()" in this class and pls. I would advice that you always remember to close your db calls. with the "close()".
But the actually solution am using here : is as follows :
In my app I have different db adapters and this is just an example :
package com.app.android;
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);//pls. note : "Appiah" is the class in which all the common methods, variables, etc. are sitting.
}
#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();
*/
}
I hope this helps. It can get deeper but I do hope this helps. All the best.
In my application I want save data in database.
Here is my code of SQLiteHelper
public class UserSqliteHelper extends SQLiteOpenHelper {
private final String LOGCAT = "JBF/SQLite";
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "jbfjsonEntityDB";
private static final String TABLE_NAME = "jbfjsonEntity";
private static final String KEY_JSON = "json";
private static final String KEY_URL_PATH = "url_path";
private static final String KEY_TIME = "added_on";
public UserSqliteHelper(Context context) {
super(context, "dictionarysqlitehelper.db", null, 1);
Log.d(LOGCAT, "Created");
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_JSON + " TEXT, "
+ KEY_TIME + " TIMESTAMP NOT NULL DEFAULT current_timestamp, "
+ KEY_URL_PATH + " TEXT )";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS " + TABLE_NAME ;
db.execSQL(query); onCreate(db);
}
public void addJsonEntity(JsonEntity jsonEntity) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_JSON, jsonEntity.getJson());
values.put(KEY_URL_PATH, jsonEntity.getUrl_path());
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close();
}
public JSONObject getJsonByUrl(String url) {
String json = "";
SQLiteDatabase db = this.getReadableDatabase();
try {
// Cursor c = db.query(TABLE_NAME, null, KEY_URL_PATH + "=?", new String[]{url}, null, null, null);
String selectQuery = "SELECT * FROM " + TABLE_NAME + " where " + KEY_URL_PATH + "='"+url+"'";
Cursor c = db.rawQuery(selectQuery, null);
if (c == null) {
return null;
} else {
c.moveToFirst();
json =c.getString(c.getColumnIndex(KEY_JSON));
if (json != null) {
return new JSONObject(json);
} else {
return null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
When I call from my activity this
UserSqliteHelper sqliteHelper = new UserSqliteHelper(SplashActivity.this);
sqliteHelper.getWritableDatabase();
sqliteHelper.addJsonEntity(new JsonEntity(STRING_CONFIGS_URL,response.toString()));
System.out.println("json ==== "+sqliteHelper.getJsonByUrl(GET_USER_INFO_URL));
I always got this error
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
Could anyone tell me what I did wrong in here. Why I can't get my database values?
The query didn't match any data. moveToFirst() fails and the cursor doesn't point to a valid row. You should check that moveToFirst() succeeds - it returns a boolean.
Why it didn't match any data is because you're storing and retrieving data by different keys: STRING_CONFIGS_URL and GET_USER_INFO_URL.
instead of c==null try c.getColumnCount == 0