I’m new to android development and I’m trying to make a simple application where i can add and view my records. I can successfully add data and view them in a table, it works ever time i run the program. (I’m following this tutorial) But every time i close Eclipse and try to add new data and view them, the previous information I entered was gone. it seems like when I close eclipse, it doesn’t save my database. Here is the sample code I’m following.
package com.example.hotornot;
import java.sql.Statement;
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;
public class Example {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_NUM = "number";
public static final String DATABASE_NAME = "dbTry";
public static final String DATABASE_TABLE = "tblSamp";
public static final int DATABASE_VERSION = 1;
public DbHelper ourhelper;
public final Context ourcontext;
public SQLiteDatabase ourdatabase;
class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER, " + KEY_NAME + " NULL, " + KEY_NUM + " NULL);");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
arg0.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE);
onCreate(arg0);
}
}
public Example(Context c)
{
ourcontext = c;
}
public Example open() throws SQLException
{
ourhelper = new DbHelper(ourcontext);
ourdatabase = ourhelper.getWritableDatabase();
return this;
}
public void close()
{
ourhelper.close();
}
public long createEntry(String name, String num)
{
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_NUM, num);
return ourdatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID,KEY_NAME, KEY_NUM};
Cursor c = ourdatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iNum = c.getColumnIndex(KEY_NUM);
for (c.moveToFirst(); ! c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +c.getString(iName) + " " + c.getString(iNum) + "\n";
}
return result;
}
}
You must be overwriting the existing database or uninstalling the app
please check your code
on Activity onCreate event check for the existence of db file if exist do not overwrite and skip the process definitely you will get the old records