I'm trying to retrieve the data of sqlite database . and put it on a string to display it further but I'm getting this error , Kindly help me in solving the error !
here is the logcat data showing error
12-31 13:18:55.141: E/1.6(3833): 2222
12-31 13:18:55.191: E/1.2.2(3833): android.database.CursorIndexOutOfBoundsException: Index 9 requested, with a size of 9
12-31 13:18:55.191: E/1.7(3833): 2222
and here is the piece of code which is showing the error!
public String getdata() {
// TODO Auto-generated method stub
Log.e("1.1", "2222");
String[] column = new String[]{KEY_ROWID, KEY_NAME, KEY_HOTNESS };
Log.e("1.2", "2222");
Cursor c = ourDatabase.query(DATABASE_TABLE, column, null, null, null, null, null);
Log.e("1.3", "2222");
String result = "";
Log.e("1.4", "2222");
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
Log.e("1.5", "2222");
try{
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext());
{
Log.e("1.6", "2222");
result = result + c.getString(0) + " " + c.getString(1) + " " + c.getString(2) + "\n";
}
}catch(Exception e)
{
Log.e("1.2.2", e.toString());
}
Log.e("1.7", "2222");
return result;
}
Note : after putting the below code in try catch it's moving to next activity but not showing any result data
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext());
{
Log.e("1.6", "2222");
result = result + c.getString(0) + " " + c.getString(1) + " " + c.getString(2) + "\n";
}
next activity code :
TextView tv = (TextView) findViewById(R.id.textView3);
Log.e("1", "111111");
HotOrNot info = new HotOrNot(this);
Log.e("2", "111111");
info.open();
Log.e("3", "111111");
String data = info.getdata();
Log.e("4", "111111");
info.close();
Log.e("5", "111111");
tv.setText(data);
Log.e("6", "111111");
}
}
You have a semicolon too much:
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()); // look here :(
... so your for loop runs to the end of the cursor. Afterwards you try to get some data from the cursor, what fails, because you are already after the last entry.
Just use this one:
while(c != null && c.moveToNext())
{
Log.e("1.6", "2222");
result = result + c.getString(0) + " "
+ c.getString(1) + " "
+ c.getString(2) + "\n";
}
Most likely you can skip the c != null.
Related
I just learned to use sqlite on android. how to prevent duplicate data when it will be inserted .. so, when there is same data entry, it will overwrite the data?
here I attach the code snippet:
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FAVORIT_TABLE = "CREATE TABLE " + Constant.favoritDBtable + "("
+ Constant.id_postFav + " INTEGER PRIMARY KEY AUTOINCREMENT," + Constant.titleFav + " TEXT," + Constant.namaPerusahaanFav + " TEXT,"
+ Constant.lokasiFav + " TEXT," + Constant.kriteria_1Fav + " TEXT," + Constant.kriteria_2Fav
+ " TEXT," + Constant.kriteria_3Fav + " TEXT," + Constant.gajiFav + " TEXT," + Constant.img_logoFav
+ " TEXT," + Constant.tanggalFav + " TEXT);";
public String addFavorit(Favorit favorit){
SQLiteDatabase db = this.getWritableDatabase();
// long rows = 0;
ContentValues values = new ContentValues();
values.put(Constant.titleFav, favorit.getTitleFav());
values.put(Constant.namaPerusahaanFav, favorit.getNamaPerusahaanFav());
values.put(Constant.lokasiFav, favorit.getLokasiFav());
values.put(Constant.kriteria_1Fav, favorit.getKriteria_1Fav());
values.put(Constant.kriteria_2Fav, favorit.getKriteria_2Fav());
values.put(Constant.kriteria_3Fav, favorit.getKriteria_3Fav());
values.put(Constant.gajiFav, favorit.getGajiFav());
values.put(Constant.img_logoFav, favorit.getImg_logoFav());
values.put(Constant.tanggalFav, favorit.getTanggalFav());
db.insert(Constant.favoritDBtable, null, values,);
Log.d("Favorit saved: ", "Success 200 OK");
return null;
}
MainActivity.java
#Override
public void onClick(View v) {
if (job.getTitle() != null && job.getLokasi() != null){
saveToFavoritDB();
}
}
private void saveToFavoritDB() {
Favorit favorit = new Favorit();
favorit.setTitleFav(job.getTitle());
favorit.setGajiFav(job.getGaji());
Log.d(TAG, "gaji " + job.getGaji());
db.addFavorit(favorit);
List<Favorit> favList = db.getAllFavorit();
for (Favorit each : favList) {
String log = "ID: " + each.getTitleFav() + ", Name: " + each.getLokasiFav() + ", Phone: " + each.getGajiFav();
Log.d(TAG, "saveToFavoritDB: " + String.valueOf(db.getCountFavorit()));
Log.d(TAG, "Hasil: " + log);
}
}
hope you can help me
Before go through addFavorit method, you can add one method to check whether the data is already exists to prevent duplicate.
boolean check;
check = checkDuplicate(...,...,...,id_post); // check whether data exists
if(check == true) // if exists
{
Toast.makeText(MainActivity.this, " Data Already Exists", Toast.LENGTH_LONG).show();
}else{
db.addFavorit(favorit);
}
public static boolean checkDuplicate(String TableName,String dbfield, String fieldValue, int id_post) {
String Query = ".... WHERE "+ Constant.id_postFav +"="+ id_post; // your query
Cursor cursor = db.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
Crate a function to check row is in db or not
private static boolean CheckIsInDBorNot(String titleFav) {
String selectQuery = "SELECT * FROM " + Constant.favoritDBtable + " WHERE " + Constant.titleFav +"'"+titleFav "'";
final SQLiteDatabase db = open();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
than check
if (!CheckIsInDBorNot(commentOrderId, commentId)) {
db.insertOrThrow(Constant.favoritDBtable, null, cVal);
}
It will check and insert
Create method IsItemExist() in your DatabaseHelper class and call this method in you activity class like IsItemExist(name,mobile)
public boolean IsItemExist(String name,String mobile) {
try
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery("SELECT "+NAME+" FROM "+TABLE+" WHERE "+NAME+"=?",new String[]{name});
Cursor cursor1=db.rawQuery("SELECT "+MOBILE+" FROM "+TABLE+" WHERE "+MOBILE+"=?",new String[]{mobile});
if (cursor.moveToFirst() && cursor1.moveToFirst())
{
db.close();
Log.d("Record Already Exists", "Table is:"+TABLE+" ColumnName:"+NAME);
return true;//record Exists
}
Log.d("New Record ", "Table is:"+TABLE+" ColumnName:"+NAME+" Column Value:"+NAME);
db.close();
}
catch(Exception errorException)
{
Log.d("Exception occured", "Exception occured "+errorException);
// db.close();
}
return false;
}
I am using android call logs in my app and I would like to determine whether the last call was an incoming or out going call. This is what I have tried so far however int type gives me an error android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 284
Cursor managedCursor = context.getContentResolver().query( CallLog.Calls.CONTENT_URI,null, null,null, android.provider.CallLog.Calls.DATE + " DESC");
int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER );
int duration1 = managedCursor.getColumnIndex( CallLog.Calls.DURATION);
int type = Integer.parseInt(managedCursor.getString(managedCursor.getColumnIndex(CallLog.Calls.TYPE)));
Log.v("DialBroadcast Receiver", "Number is: " + type);
if( managedCursor.moveToFirst() == true ) {
String phNumber = managedCursor.getString( number );
callDuration = managedCursor.getString( duration1 );
String dir = null;
sb.append( "\nPhone Number:--- "+phNumber +" \nCall duration in sec :--- "+callDuration );
sb.append("\n----------------------------------");
Log.i("*****Call Summary******","Call Duration is:-------"+sb);
Log.v("DialBroadcast Receiver", "Number is: " + callDuration);
}
Try this
public String getLastDialledNumber() {
String[] projection = {Calls.NUMBER};
Cursor cursor = mContext.getContentResolver().query(Calls.CONTENT_URI, projection,
Calls.TYPE + "=" + Calls.OUTGOING_TYPE, null, Calls.DEFAULT_SORT_ORDER +
" LIMIT 1");
if (cursor == null) return null;
if (cursor.getCount() < 1) {
cursor.close();
return null;
}
cursor.moveToNext();
int column = cursor.getColumnIndexOrThrow(Calls.NUMBER);
String number = cursor.getString(column);
cursor.close();
return number;
}
For details
How do I access call log for android?
you are get
int type = Integer.parseInt(managedCursor.getString(managedCursor.getColumnIndex(CallLog.Calls.TYPE)));
before chek if( managedCursor.moveToFirst()){}
that's why you get exeption.
put this line inside of if or try this method
private static String getCallDetails(Context context) {
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);
while (cursor.moveToNext()) {
String phNumber = cursor.getString(number);
String callType = cursor.getString(type);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = cursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
+ dir + " \nCall Date:--- " + callDayTime
+ " \nCall duration in sec :--- " + callDuration);
stringBuffer.append("\n----------------------------------");
}
cursor.close();
return stringBuffer.toString();
}
Inserting values into table using beans
public static void addGetAssessmentDetail(Context context,
GetAssessmentBean getassessmentDetail) {
DBHelper dbHelper = null;
SQLiteDatabase sqlDBRead = null;
SQLiteDatabase sqlDBWrite = null;
try {
dbHelper = new DBHelper(context, LektzDB.DB_NAME, null,
LektzDB.DB_VERSION);
sqlDBRead = dbHelper.getReadableDatabase();
sqlDBWrite = dbHelper.getWritableDatabase();
ContentValues book = new ContentValues();
book.put(TB_FinalAssessmentValues.CL_1_ID, getassessmentDetail.getId());
book.put(TB_FinalAssessmentValues.CL_2_USER_ID , getassessmentDetail.getUser_id());
book.put(TB_FinalAssessmentValues.CL_3_BOOK_ID, getassessmentDetail.getBook_id());
book.put(TB_FinalAssessmentValues.CL_4_CHAPTER_ID,
getassessmentDetail.getChapter_id());
book.put(TB_FinalAssessmentValues.CL_5_QUESTION_TYPE,
getassessmentDetail.getQuestion_type());
book.put(TB_FinalAssessmentValues.CL_6_QUESTION_ID,
getassessmentDetail.getQuestion_id());
book.put(TB_FinalAssessmentValues.CL_7_OPTION_ID,
getassessmentDetail.getOption_id());
book.put(TB_FinalAssessmentValues.CL_8_MARK,
getassessmentDetail.getMark());
book.put(TB_FinalAssessmentValues.CL_9_NOTES,
getassessmentDetail.getNotes());
book.put(TB_FinalAssessmentValues.CL_10_MATCH_OPTION, getassessmentDetail.getMatchOption());
book.put(TB_FinalAssessmentValues.CL_11_DRAG_VALUES,
getassessmentDetail.getDragValues());
book.put(TB_FinalAssessmentValues.CL_12_ADDED_TIME,
getassessmentDetail.getAdded_time());
Log.i("", "assessment values insertion success" );
} catch (Exception e) {
e.printStackTrace();
}
}
And trying to retrieve those table values into JSON array
public JSONArray getFullAssessmentData(Context mContext, String bookid,
int UserId) {
DBHelper dbh = new DBHelper(mContext, LektzDB.DB_NAME, null,
LektzDB.DB_VERSION);
SQLiteDatabase db = dbh.getReadableDatabase();
JSONArray resultSet = new JSONArray();
try {
Cursor c = db.rawQuery("SELECT * FROM " + TB_FinalAssessmentValues.NAME
+ " WHERE " + TB_FinalAssessmentValues.CL_3_BOOK_ID+ "='"+ bookid + "'", null);
Log.i("tag", "msg vachindi");
if (c.getCount() > 0) {
c.moveToFirst();
do {
c.moveToFirst();
while (c.isAfterLast() == false) {
int totalColumn = c.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (c.getColumnName(i) != null) {
try {
rowObject.put(c.getColumnName(i),
c.getString(i));
} catch (Exception e) {
}
}
}
resultSet.put(rowObject);
c.moveToNext();
}
c.close();
db.close();
}
while (c.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
}
return resultSet;
}
And finally trying to store those values into JSON array
JSONArray fullassessmentjson = rdb.getFullAssessmentData( getContext(), BookId, UserId);
Log.i("Tag123456","Finalcheck"+fullassessmentjson);
DBHelper
db.execSQL("CREATE TABLE IF NOT EXISTS " + TB_FinalAssessmentValues.NAME + "("
+ TB_FinalAssessmentValues.CL_1_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_2_USER_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_3_BOOK_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_4_CHAPTER_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_5_QUESTION_TYPE + " TEXT, "
+ TB_FinalAssessmentValues.CL_6_QUESTION_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_7_OPTION_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_8_MARK + " TEXT, "
+ TB_FinalAssessmentValues.CL_9_NOTES + " TEXT, "
+ TB_FinalAssessmentValues.CL_10_MATCH_OPTION + " TEXT, "
+ TB_FinalAssessmentValues.CL_11_DRAG_VALUES + " TEXT, "
+ TB_FinalAssessmentValues.CL_12_ADDED_TIME + " TEXT)");
and the error is its showing nothing in the Json array
Seems like you're adding the values to your ContentValues object, but do not perform the actual insert into the database.
(because of this you're basically querying an empty table)
You should call the insert() method of SQLiteDatabase at the end of addGetAssessmentDetail() to insert the data into your table:
sqlDBWrite.insert(TABLE_TO_INSERT, null, book);
I have an android Quote application in which I have used SQLite Database for storing quotes. I have launched the first version of the application with this DatabaseHelper.
public class DataBaseHandler extends SQLiteOpenHelper {
private static String DB_PATH;
private static String DB_NAME = "SuccessQuotes";
private SQLiteDatabase myDataBase;
private static int DATABASE_VERSION = 1;
private final Context myContext;
public DataBaseHandler(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH = context.getDatabasePath(DB_NAME).toString();
Log.e("path", DB_PATH);
}
// ==============================================================================
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// ==============================================================================
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
// ==============================================================================
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
// ==============================================================================
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
// ==============================================================================
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
// ==============================================================================
#Override
public void onCreate(SQLiteDatabase db) {
}
// ==============================================================================
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
and my Database Activity is :
public class DAO {
// All Static variables
private SQLiteDatabase database;
private DataBaseHandler dbHandler;
private static final String TABLE_QUOTES = "quotes";
private static final String TABLE_AUTHORS = "authors";
private static final String TABLE_SETTINGS = "settings";
// Pages Table Columns names
private static final String QU_ID = "_quid";
private static final String QU_TEXT = "qu_text";
private static final String QU_AUTHOR = "qu_author";
private static final String QU_FAVORITE = "qu_favorite";
private static final String QU_WEB_ID = "qu_web_id";
private static final String AU_ID = "_auid";
private static final String AU_NAME = "au_name";
private static final String AU_PICTURE = "au_picture";
private static final String AU_PICTURE_SDCARD = "au_picture_sdcard";
private static final String AU_WEB_ID = "au_web_id";
// ==============================================================================
public DAO(Context context) {
dbHandler = new DataBaseHandler(context);
try {
dbHandler.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHandler.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
// Log.e("path2", context.getDatabasePath("SuccessQuotes").toString());
// open();
}
// ==============================================================================
// Getting All Quotes
public Cursor getQuotes(String start) {
// Select All Query
String limit = "15";
if (start.equals("5000")) {
String query_count = "SELECT COUNT(" + QU_ID + ") AS count FROM "
+ TABLE_QUOTES;
Cursor c_count = database.rawQuery(query_count, null);
c_count.moveToFirst();
Integer count = c_count.getInt(c_count.getColumnIndex("count"));
limit = String.valueOf(count);
}
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
//Log.i("query",query);
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting All Quotes
public Cursor getFavoriteQuotes(String start) {
// Select All Query
String limit = "15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1"+" ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
//======================================================================
// Getting Fav Quote from ID
public String getFavQuotes(String strkey_id) {
// Select All Query
String fav = "";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1 AND " + QU_ID + " = " +strkey_id;
Cursor cursor = database.rawQuery(query, null);
if(cursor.getCount() != 0)
{
cursor.moveToFirst();
fav = cursor.getString(cursor.getColumnIndex(QU_FAVORITE));
}
return fav;
}
// ==============================================================================
// Getting All Author Quotes
public Cursor getAuthorQuotes(String authorID,String start) {
// Select All Query
String limit="15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_AUTHOR + " = " + authorID + " ORDER BY "+ QU_WEB_ID +" DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Selected Quote
public Cursor getOneQuote(String quoteID) {
// Select All Query
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_ID + " = '" + quoteID + "'";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public void addOrRemoveFavorites(String id, String value) {
ContentValues values = new ContentValues();
values.put(QU_FAVORITE, value);
// Update Row
// database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
}
// ==============================================================================
// Getting All Authors
public Cursor getAllAuthors() {
// Select All Query
String query = "SELECT *, COUNT(" + QU_AUTHOR + ") AS count FROM "
+ TABLE_AUTHORS + " LEFT JOIN " + TABLE_QUOTES + " ON " + AU_WEB_ID
+ " = " + QU_AUTHOR + " GROUP BY " + AU_NAME ;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Quotes Count
public Integer getQuotesCount() {
String query = "SELECT COUNT(" + QU_TEXT + ") AS count FROM "
+ TABLE_QUOTES;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer count = cursor.getInt(cursor.getColumnIndex("count"));
return count;
}
// ==============================================================================
// Getting Quote ID
public Integer getQotdId() {
String query = "SELECT " + QU_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY RANDOM() LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer id = cursor.getInt(cursor.getColumnIndex(QU_ID));
return id;
}
// ==============================================================================
public void updateSetting(String field, String value) {
open();
ContentValues values = new ContentValues();
values.put(field, value);
// Update Row
database.update(TABLE_SETTINGS, values, null, null);
}
// ==============================================================================
public Cursor getSettings() {
open();
String query = "SELECT * FROM " + TABLE_SETTINGS;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public int getLastAuthor() {
String query = "SELECT " + AU_WEB_ID + " FROM " + TABLE_AUTHORS
+ " ORDER BY " + AU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(AU_WEB_ID));
}
// ==============================================================================
public int getLastQuote() {
String query = "SELECT " + QU_WEB_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY " + QU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(QU_WEB_ID));
}
// ==============================================================================
public void addAuthor(String au_name, String au_picture, int au_web_id) {
open();
ContentValues v = new ContentValues();
v.put(AU_NAME, au_name);
v.put(AU_PICTURE, au_picture);
v.put(AU_PICTURE_SDCARD, 1);
v.put(AU_WEB_ID, au_web_id);
database.insert(TABLE_AUTHORS, null, v);
}
// ==============================================================================
public void addQuote(String qu_text, int qu_author, int qu_web_id) {
open();
ContentValues v = new ContentValues();
v.put(QU_TEXT, qu_text);
v.put(QU_AUTHOR, qu_author);
v.put(QU_FAVORITE, "0");
v.put(QU_WEB_ID, qu_web_id);
database.insert(TABLE_QUOTES, null, v);
}
// ==============================================================================
public void open() throws SQLException {
// database = dbHandler.getReadableDatabase();
database = dbHandler.getWritableDatabase();
}
// ==============================================================================
public void closeDatabase() {
dbHandler.close();
}
Now if I want to update application with more quotes, which changes should I make so that the new and old users don't face any issue ?
I know That Database Version Should Increased, I will it, but What should I put in onUpgrade method ?
I am not expert Android developer, so Please explain me little more if possible, I will very thankful for it.
Thanks
Thanks
Well the Java doc pretty much explains what needs to be done.
From Java doc
Called when the database needs to be upgraded. The implementation
should use this method to drop tables, add tables, or do anything else it
needs to upgrade to the new schema version.
What we do is , alter the tables whenever we have changed the table schema.
In addition you can also perform some data migration if required. Basically its a hook which you got and you can perform any kind of compatibility logic.
cheers,
Saurav
I've got an error I hope you can help me solve.
I'm returning a String, seperated by ':' from a method getdata();
Everything works fine on the emulator, but when running the app on my device, the method returns an empty string and I get an error: IndexOutOfBoundsException: length=1; index=2.`
Code:
Databaseengine info = new Databaseengine(this);
info.open();
String data = info.getdata();
info.close();
String[] values = null;
values = data.split(":");
tvans1.setText(values[4]);
tvans2.setText(values[5]);
tvans3.setText(values[6]);
tvans4.setText(values[7]);
The method looks like this:
public String getdata() {
// TODO Auto-generated method stub
String[] columns = new String [] { KEY_ROWID, KEY_CATEGORY, KEY_QUESTION, KEY_ANSWER, KEY_ALTONE, KEY_ALTTWO, KEY_ALTTHREE, KEY_ALTFOUR };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null , null , null, "RANDOM() LIMIT 1");
String result = "";
//The cursor will be looking for these columns:
int iRow = c.getColumnIndex(KEY_ROWID);
int iCat = c.getColumnIndex(KEY_CATEGORY);
int iQuiz = c.getColumnIndex(KEY_QUESTION);
int iAns = c.getColumnIndex(KEY_ANSWER);
int iAlt01 = c.getColumnIndex(KEY_ALTONE);
int iAlt02 = c.getColumnIndex(KEY_ALTTWO);
int iAlt03 = c.getColumnIndex(KEY_ALTTHREE);
int iAlt04 = c.getColumnIndex(KEY_ALTFOUR);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + ":"
+ c.getString(iCat) + ":" + c.getString(iQuiz) + ":"
+ c.getString(iAns) + ":" + c.getString(iAlt01) + ":"
+ c.getString(iAlt02) + ":" + c.getString(iAlt03) + ":"
+ c.getString(iAlt04) + "\n";
}
c.close();
return result;
}
Please help me, before I go mental here :-)
You should consider the length of the resulting array after splitting.
To ask for an index no. 7, length must be at least 8 elements:
if (values.length > 7) { ..do your work.. } else { ..throw exception.. }
The different behavior you're getting on emulator/device must be related to distinct data being parsed.
i am Not Sure But give it a try with this
values = data.split("\\:");
instead of
values = data.split(":");