SQLite Database getting deleted in Android - android

Hello everyone,
I have built a sample app which takes input from user and save it in a table in a database.I have created my own database for my app and saved data in it. Every thing seems to be fine. The other day, I started Eclipse IDE and started running my application. I was not able to see any data in my application.
When I see in file explorer(DDMS), there was no database ( my database, table, data in it every thing lost). I heard that SQLite database is persistent. I used general syntax for creating database and table. Please any one suggest me why this has happened.
This is my MainActivity.java,
public class MainActivity extends Activity {
public final android.content.Context Context = MainActivity.this;
public String ReadingMode = "";
public String Value = "";
public String DialogStatus = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button saveWaterReadingToDB = (Button) findViewById(R.id.saveReading);
saveWaterReadingToDB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String TABLE_NAME = "WaterElectricity";
String COLUMN_NAME_READING_ID = "_Id";
String COLUMN_NAME_READING_MODE = "ReadingMode";
String COLUMN_NAME_PASTDATETIME = "StartDateTime";
String COLUMN_NAME_READINGVALUE = "ReadingValue";
final SQLiteDatabase DB = Context.openOrCreateDatabase(
"WaterElectricityReadingDataBase.db",
MODE_WORLD_READABLE, null);
final String CREATE_TABLE = "create table if not exists "
+ TABLE_NAME + " (" + COLUMN_NAME_READING_ID
+ " integer primary key autoincrement,"
+ COLUMN_NAME_READING_MODE + " text not null,"
+ COLUMN_NAME_PASTDATETIME + " date not null, "
+ "EndDateTime date not null, "
+ COLUMN_NAME_READINGVALUE + " integer not null" + ");";
DB.execSQL(CREATE_TABLE);
}
});
}
Thanks.

All databases may be deleted every time you restore/re-run your emulator.
Closing eclipse has nothing to do with your database deleting, as it's all saved in your emulators directory.
Your emulators database is actually stored on a piece of virtual memory. To see this (In windows) go to username/.android/avd and you will see all of your AVD's set up as directories (containing all files pertaining to that emulator)
Make sure this is unchecked:
File Path with Files:
SD Card img file (containing the actual db)?:
This is just me taking an educated guess on which file is the actual sdcard file. Someone feel free to correct me.

Related

near "/" syntax error in Android

The below code in my project calls a function in my database class to insert two values into my sqlite database
saveButton = (Button) findViewById(R.id.Save);
saveButton.setOnClickListener(new View.OnClickListener( ) {
#Override
public void onClick(View v) {
addCig = (EditText) findViewById(R.id.cigName );
myDbHelper1.insertNewCig(addCig.toString(), fileName );
}
});
Here is the insert into function. I am getting an error that reads (near "/": syntax error). Can anybody help me look into it and see what is wrong with my code.
public void insertNewCig(String name, String file)
{
//DB_PATH = "/data/data/com.example.newdb/databases/"
//DB_NAME = "cigarettes"
String myPath = DB_PATH + DB_NAME;
String row1 = "INSERT INTO " + myPath + " (" + KEY_FIRST + ", " + KEY_LAST + ") VALUES(" + name + ", " + file + ")";
myDataBase.execSQL(row1);
}
myPath should be the name of a table in your database, not the name and path of the database file. You also need to add single quotes around the values you are inserting, otherwise SQLite won't recognize that they are literal string values and not something else (e.g. column names). This is one of many reasons not to try to build raw SQL statements by hand in code.
Since you have a SQLiteDatabase, you may as well use its insert() methods instead of execSQL(). In that case you would give it a ContentValues instead of constructing a raw statement, which obviates the need to wrap the string values with single quotes.
ContentValues values = new ContentValues();
values.put(KEY_FIRST, name);
values.put(KEY_LAST, file);
myDataBase.insert(TABLE_NAME, null, values);

Android external database in assets folder not acces to db file

I have an android application that is supposed to read and expand a DataBase that is already created on SQLite...it works fine on emulator by putting database in data/data/(packagename)/database folder on the file explorer of emulator.
Now problem is occuring with the real device. Obviously it doesnt have the DataBase to open.I tried to put DataBase in assets folder but I am not getting to open it with the openhelper. how to access my database file form assets folder.will you please give me the right solution because i am new in Android and java .
this is my dbheperclass .
public class FoodDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "pkfood_calories.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+ Food.NewDishInfo.TABLE_NAME+"("
+ Food.NewDishInfo.DISH_NAME+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_QUANTITY+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_CALORIE+" INTEGER,"
+ Food.NewDishInfo.DISH_FAT+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_PROTEIN+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_SUGAR+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_VITAMINS+" TEXT NOT NULL);";
public FoodDbHelper(Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATION","Database created / opened...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATION","Table created...");
}
public void addInformations(String name ,String quantity, Integer calorie, String fat ,
String protein,String sugar,String vitamins, SQLiteDatabase db){
ContentValues contentValues = new ContentValues();
contentValues.put(Food.NewDishInfo.DISH_NAME,name);
contentValues.put(Food.NewDishInfo.DISH_QUANTITY,quantity);
contentValues.put(Food.NewDishInfo.DISH_CALORIE,calorie);
contentValues.put(Food.NewDishInfo.DISH_FAT,fat);
contentValues.put(Food.NewDishInfo.DISH_PROTEIN,protein);
contentValues.put(Food.NewDishInfo.DISH_SUGAR,sugar);
contentValues.put(Food.NewDishInfo.DISH_VITAMINS,vitamins);
db.insert(Food.NewDishInfo.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATION","one row inserted...");
}
public Cursor getInformations(SQLiteDatabase db){
Cursor cursor;
String[] projections = {Food.NewDishInfo.DISH_NAME,Food.NewDishInfo.DISH_QUANTITY,
Food.NewDishInfo.DISH_CALORIE,Food.NewDishInfo.DISH_FAT,Food.NewDishInfo.DISH_PROTEIN,
Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
cursor= db.query(Food.NewDishInfo.TABLE_NAME,projections,null,null,null,null,"DISH_NAME ASC");
return cursor;
}
please help me to short out from this problem..
First thing is your logic of reading from asset folder is correct.
But writing to assets folder may not be a better logic.
The asset folder is part of the APK
To read a file from asset folder
context.getAssets().open("pkfood_calories.DB")
Assuming that you placed that file in assets folder
You can get the internal memory location using
context.getFilesDir()
Refer creating file in internal memory Android create folders in Internal Memory
You cannot write anything to an APK. So, your db is in assert folder which can only be used for reading purpose.
You need to migrate that db file in external or internal memory(according to requirement) before doing some writing part on it.

Android simple SQLite database application

I downloaded a simple login page code in zip file from
http://bit.ly/saket_github_loginpage.
Please check this application and tell me where the database file is. And how can I see this? I also want to create some new tables. How can I do this? I have tried getting it to work with the following code:
public class DbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "saket.db";
private static final int DATABASE_VERSION = 1;
public static final String SAKET_TABLE_NAME = "login";
public static final String SAKET_TABLE_NAME1 = "Employee";
private static final String SAKET_TABLE_CREATE =
"CREATE TABLE " + SAKET_TABLE_NAME + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NO TNULL);";
private static final String SAKET_TABLE_CREATE1 =
"CREATE TABLE " + SAKET_TABLE_NAME1 + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
"name TEXT NOT NULL, Address TEXT NOT NULL, email TEXT NOT NULL);";
private static final String SAKET_DB_ADMIN = "INSERT INTO" +
SAKET_TABLE_NAME+"values(1, admin, password, admin#gmail.com);";
private static final String SAKET_DB_ADMIN1 = "INSERT INTO " +
SAKET_TABLE_NAME+"values(2, emp, password, Emp#gmail.com);";
private static final String SAKET_DB_ADMIN2 = "INSERT INTO " +
SAKET_TABLE_NAME1 + "values(1, mahesh, address, mahesh#gmail.com);";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
System.out.println("In constructor");
}
}
It's better you check on emulator, or a rooted device....... Follow these steps
In emulator run your application.
In eclipse go to Window>Show view>Other...>Android and click file explorer
In File explorer find a folder called data which should not be on your SD card
in data>data>your.application.packagename you can find database folder, your database is there
Find an icon called pull a file from device...... you can copy that database anywhere you like using this button....
There are many clients to view and operate the SQLITE database including firefox has one..... I recommend to use this.... If you are on ubuntu they have a good application in their software center..... [I don't remember the name so apologies for that]
I hope this works for you....
1)You can see your database in file explorer. you can refer to file explorer as
Window -> show view -> other -> Select File Explorer.
in File Explorer goto
data -> data -> com.YourApplicationPackage -> YourDatabase
2)To create new table is by SQL use CREATE query having stored in String Constant and the execute it by your SQLite database object. if your sqlite database object is db then it would be db.execSQL(StringConstant); String constant carries your SQL CREATE query...
I hope you got your answer....

Inserting values to SQLite table in Android

I am new in android app developement. I tried to insert values to SQLite database through the below code;
public class cashbook extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"cashbookdata.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
final String Create_CashBook =
"CREATE TABLE CashData ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "Description TEXT,"
+ "Amount REAL,"
+ "Trans INTEGER,"
+ "EntryDate TEXT);";
db.execSQL(Create_CashBook);
final String Insert_Data="INSERT INTO CashData VALUES(2,'Electricity',500,1,'04/06/2011')";
db.execSQL(Insert_Data);
It shows error on emulator - The application CashBook has stopped unexpectedly.
The database and table created , but the value insertion is not working.
Please help me to resolve this issue.
Thanks.
Seems odd to be inserting a value into an automatically incrementing field.
Also, have you tried the insert() method instead of execSQL?
ContentValues insertValues = new ContentValues();
insertValues.put("Description", "Electricity");
insertValues.put("Amount", 500);
insertValues.put("Trans", 1);
insertValues.put("EntryDate", "04/06/2011");
db.insert("CashData", null, insertValues);
okk this is fully working code edit it as per your requirement
public class TestProjectActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase( "Temp.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null );
try {
final String CREATE_TABLE_CONTAIN = "CREATE TABLE IF NOT EXISTS tbl_Contain ("
+ "ID INTEGER primary key AUTOINCREMENT,"
+ "DESCRIPTION TEXT,"
+ "expirydate DATETIME,"
+ "AMOUNT TEXT,"
+ "TRNS TEXT," + "isdefault TEXT);";
db.execSQL(CREATE_TABLE_CONTAIN);
Toast.makeText(TestProjectActivity.this, "table created ", Toast.LENGTH_LONG).show();
String sql =
"INSERT or replace INTO tbl_Contain (DESCRIPTION, expirydate, AMOUNT, TRNS,isdefault) VALUES('this is','03/04/2005','5000','tran','y')" ;
db.execSQL(sql);
}
catch (Exception e) {
Toast.makeText(TestProjectActivity.this, "ERROR "+e.toString(), Toast.LENGTH_LONG).show();
}}}
Hope this is useful for you..
do not use TEXT for date field may be that was casing problem still getting problem let me know :)Pragna
You'll find debugging errors like this a lot easier if you catch any errors thrown from the execSQL call. eg:
try
{
db.execSQL(Create_CashBook);
}
catch (Exception e)
{
Log.e("ERROR", e.toString());
}
I recommend to create a method just for inserting and than use ContentValues.
For further info https://www.tutorialspoint.com/android/android_sqlite_database.htm
public boolean insertToTable(String DESCRIPTION, String AMOUNT, String TRNS){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("this is",DESCRIPTION);
contentValues.put("5000",AMOUNT);
contentValues.put("TRAN",TRNS);
db.insert("Your table name",null,contentValues);
return true;
}
public class TestingData extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestingData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
}
}
then see this link link
okkk you have take id INTEGER PRIMARY KEY AUTOINCREMENT and still u r passing value...
that is the problem :)
for more detail
see this
still getting problem then post code and logcat
Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html
I see it is an old thread but I had the same error.
I found the explanation here:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
void execSQL(String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
void execSQL(String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.

SQLite Database creation for Android App

I am creating my SQLite database for my App at runtime if it does not exist and insert rows if it does. Since it is supposed to be created at runtime and I have implemented it by creating a subclass of SQLiteOpenHelper and overriding the onCreate() method -
"Do I need to put anything in the /assets folder of my project?"
I am not using any Content Provider "Do I need to add any tags in the AndroidManifest.xml?"
Here is what I have done. The strings have been defined properly and I do not get any runtime exceptions.
Implementation of the SQLiteOpenHelper subclass.
public class MyDB extends SQLiteOpenHelper {
public MyDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION );
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USERAUTH_TABLE_CREATE);
db.execSQL(USERPREF_TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and
recreate.");
db.execSQL("DROP TABLE IF EXISTS " + USERAUTH_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + USERPREF_TABLE_NAME);
onCreate(db);
}
}
Here is where I create an instance of the MyDB subclass of the SQLiteOpenHelper.
MyDB tdb = new MyDB(Activity.this);
SQLiteDatabase db = tdb.getReadableDatabase();
Everything runs and when I go to the sqlite shell and write the following query
select * from table_name - it just tells me no such record exist. I set breakpoints and it seems after the getReadableDatabase() is called the #Override OnCreate() method is never executed which is where I execute the Create table SQLs. I have tried getWritableDatabase()
as well.
I dont understand why the tables are not being created. If anyone can help that would be awesome.
Thanks.
Query Text String#1
private static final String USERAUTH_TABLE_CREATE =
"CREATE TABLE " + USERAUTH_TABLE_NAME + " (" +
"number INTEGER NOT NULL," +
"dip TEXT NOT NULL," +
"email TEXT NOT NULL," +
"password TEXT NOT NULL," +
"flag INTEGER" + ");" ;
Query Text String #2
private static final String USERPREF_TABLE_CREATE =
"CREATE TABLE " + USERPREF_TABLE_NAME + " (" +
"tpd TEXT NOT NULL ," +
"cat TEXT NOT NULL" + ");";
If onCreate() is not being called, then the database has already been created for your app. The quickest way to solve it is to delete your project on the emulator (Settings --> Applications --> Your application), and then restart your application. Alternatively you could use ADB to just drop your database -- it's up to you. Restarting the app after dropping the database will call onCreate() because the database does not exist, and then your table creation sql will be run. onCreate() is only called if your database DOES NOT exist (so pretty much the first time you call the database in your code.
"Do I need to put anything in the /assets folder of my project?"
No
"Do I need to add any tags in the AndroidManifest.xml?"
No
Your syntax is ok ... could you paste the query you are making for creating tables ?
This might be a silly question, but have you defined the DATABASE_NAME and DATABASE_VERSION variables?
Issue resolved. Code was working all the way once again. sqlite shell was not showing me the tables and the database. When I kept my app running on the emulator and navigated to data > data > your-package-name > databases > your-database-file using DDMS the system shows me the SQLite DB was created fine. I have checked the tables are there as well.
Thank you all guys!!
This simple application will create a data base and 1 table w and at the end it will
retrieve the value which u have enetered and vl show in textBox.
SQLiteDatabase myDB= null;
String TableName="Profile";
String ShowData="";
/* This function create new database if not exists. */
try {
myDB = openOrCreateDatabase("DataBase.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "+ TableName + " (id INT(4),firstname VARCHAR,lastname VARCHAR);");
/* Insert data to a Table*/
//myDB.execSQL("INSERT INTO "+ TableName +"(id, firstname, lastname) "+ " VALUES (1, 'Pir', 'Fahim');");
Toast.makeText(this," DATA BASE HAVE BEEN CREATED ", Toast.LENGTH_SHORT).show();
/*Fetch data from database table */
Cursor c = myDB.rawQuery("SELECT* FROM " + TableName , null);
int id = c.getColumnIndex("id");
int fristName = c.getColumnIndex("firstname");
int lastName = c.getColumnIndex("lastname");
// Check result.
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
int personId = c.getInt(id);
String FirstName = c.getString(fristName);
String LastName = c.getString(lastName);
ShowData =ShowData +personId+" .) " +FirstName+" "+LastName+"\n";
txt.append("********************"+"\n"+personId+"\n"+FirstName+"\n"+LastName+"\n");
// Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
}
while(c.moveToNext());
}
// Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(this, "Error = "+e.getMessage(), Toast.LENGTH_LONG).show();
}
finally
{
if (myDB != null)
myDB.close();
}

Categories

Resources