Saved data lost when I restart the application(android) - android

I'm saving some records through my application in SQLite database and later retrieving those records for future use.
It's working fine until I close my application.
When I close my application all the previously saved record becomes zero.
Here is the code:--
public long insertAlbum(long Outlet_id,long user_id,String Remarks,String PhotoName,String ReportId,String Date,String Status,String LocalRepId)
{
long rowId=0;
ContentValues initialValues = new ContentValues();
initialValues.put("web_AlbumId", 0);
initialValues.put("OutletId", Outlet_id);
initialValues.put("Remarks", Remarks);
initialValues.put("UserId", user_id);
initialValues.put("Usr_Entdt", Date);
initialValues.put("PhotoName", PhotoName);
initialValues.put("ApprovedYN", "Pending");
initialValues.put("Status", Status);
initialValues.put("ReportId", ReportId);
initialValues.put("LocalReportId", LocalRepId);
try
{
myDataBase.beginTransaction();
rowId= myDataBase.insertOrThrow("Album", null, initialValues);
myDataBase.setTransactionSuccessful();
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
myDataBase.endTransaction();
}
return rowId;

This shouldn't happen.
Sounds to me like you're recreating the database when you're opening the database.
Check your code to make sure it's correct

Without seeing your code, it's hard to say what's going on. However, my suspicion is that your code is ALWYAYS creating the database. Are you extending the SQLiteOpenHelper class to create your database? Check there or post the code for further assistance.

Go to to folder where your Sqlite Db file created and check in that file whether the data you saved is present or not . If the data is present in the DB then you need to Retrieve the data from DB

Related

Insert data into database in Android

This is my first Application with database, I hope that someone can help me to understand this problem. I have this insert method:
public long insertData(String name, int password){
....
contentValues.put(KEY_NAME, name);
contentValues.put(KEY_PASSWORD, password);
return db.insert(DBHelper.TABle_NAME, null, contentValues);
}
I can insert few data with this method, but what about if I have thousands of rows? how can I insert all these data into database? where can I write all these data, in extra class or what?
As others have said, you'll need to do some sort of iteration.
Efficiency can be gained by performing a bulk transaction. Here's an example:
public int bulkInsert(#NonNull ContentValues[] values) {
int insertCount = 0;
SQLiteDatabase db = mSqlHelper.getWritableDatabase();
try {
db.beginTransaction();
for (ContentValues value : values) {
if (db.insertOrThrow(tableName, null, value) == -1) {
throw new Exception("Unknown error while inserting entry in database.");
}
insertCount++;
}
db.setTransactionSuccessful();
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred while bulk-inserting database entries.\n" + e.getMessage(), e);
} finally {
db.endTransaction();
}
return insertCount;
}
There is no 'bulk load' facility that I'm aware of.
You'd just have to spin through the list, and insert the items.
You might want to think about why you're potentially trying to insert thousands of items into a database on a hardware-limited device like a phone or a tablet.
Might it be better to put the data on a server, and create an API that you can use to load data (for display) by pages?
you can do it the same way, that you do with few data, you only need to catch the thousands rows to insert into your database using your method, you can use asyntask, or a service to do that
You can use the same method to insert any amount of records, whether it's 1 or 1,000. Use a loop to call your insert method and add your records to your database. Consider putting your database executions in an AsyncTask to prevent your UI thread from hanging.
Your data can come from anywhere, as long as it's formatted to fit your function parameters String, int

add large amount of data in SQLite android

I am new to android and maybe its a silly question but i am not getting it. See i am designing a game in which we give scores to some persons. So i want to store the names of the persons in a database while installation and then their scores set to 0 initially which will be updated according to what the users select. Here i am not able to figure out that how should i enter the data as it will be around 100 names and their scores. Using INSERT INTO() statement will make it like 100 statements. So is there any short method like can we do it through strings or something. Just guessing though. Any help would be appreciated.
You don't hard-code names or scores into your SQL statements. Instead, you use parameters.
var command = new SQLiteCommand()
command.CommandText = "INSERT INTO Scores (name, score) VALUES(#name, #score)";
command.CommandType = CommandType.Text;
foreach (var item in data)
{
command.Parameters.Add(new SQLiteParameter("#name", item.Name));
command.Parameters.Add(new SQLiteParameter("#score", item.Score));
command.ExecuteNonQuery();
}
and then just loop through all of the names and scores.
I recommend you using a transaction.
You can archive this stating you want to use a transaction with beginTransaction(), do all the inserts on makeAllInserts() with a loop and if everything works then call setTransactionSuccessful() to do it in a batch operation. If something goes wrong, on the finally section you will call endTransaction() without setting the success, this will execute a rollback.
db.beginTransaction();
try {
makeAllInserts();
db.setTransactionSuccessful();
}catch {
//Error in between database transaction
}finally {
db.endTransaction();
}
For the makeAllInserts function, something like this could work out:
public void makeAllInserts() {
for(int i = 0; i < myData.size(); i++) {
myDataBase = openDatabase();
ContentValues values = new ContentValues();
values.put("name", myData.get(i).getName());
values.put("score", myData.get(i).getScore());
myDataBase.insert("MYTABLE", nullColumnHack, values);
}
}
If you also want to know about the nullColumnHack here you have a good link -> https://stackoverflow.com/a/2663620/709671
Hope it helps.

Call logs restore in android

I am creating an application in android for call logs backup and restore using csv file.Backup was successfully created but while restoring all call logs are not restored from csv.Here is the code i am writing for backup
while((row = csvReader.readNext()) != null)
{
RestoreCallLogs(row[0],row[1],row[2],row[3],row[4]);
}
public void RestoreCallLogs(String Name,String number,String Date,String Type,String Duration){
ContentValues values = new ContentValues();
values.put(CallLog.Calls.NUMBER, number);
values.put(CallLog.Calls.DATE, Date);
values.put(CallLog.Calls.DURATION,Duration);
values.put(CallLog.Calls.TYPE, Type);
if(Name!="Unknown")
values.put(CallLog.Calls.CACHED_NAME, Name);
getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);
}
You have a try-catch block which is hiding the exception generated here:
RestoreCallLogs(row[0],row[1],row[2],row[3],row[4]);
You should not use try-catch without understanding what it does.
To fix:
String[] row;
while((line = csvReader.readNext()) != null){
row = line.split(",");
RestoreCallLogs(row[0],row[1],row[2],row[3],row[4]);
}
Please read the documentation for .split(). You will need to do extra work to deal with commas and other non-alphanumeric characters inside strings of a contact record. You are also assuming that the csv only contains 5 columns. Can you guarantee that?
Finally, please use accepted conventions for naming identifiers in Java. Using a capital letter to start a variable name makes your code hard to read.
[EDIT]
I don't know how your code compiles. Please show the declarations for row and csvReader.

Android transaction or trigger?

I am working on a fuel use application which will run on Android 1.6 onwards. The bundled SQLite on v1.6 doesn't do foreign keys, so I've had to handle it manually. So far, I have done this using an Android transaction:
public static long addFuelUp(String registrationNumber, String date)
{
SQLiteDatabase db = uKMpgData.getReadableDatabase();
long result = -1;
ContentValues values = new ContentValues();
Cursor vehicleCursor = VehicleDataProvider.getVehicle(registrationNumber);
if(vehicleCursor.moveToNext())
{
Cursor fuelUpsCursor = getFuelUps(registrationNumber, date);
if(!fuelUpsCursor.moveToNext())
{
db.beginTransaction();
try
{
values.put(REGISTRATION_NO_COLUMN, registrationNumber.replace(" ", ""));
values.put(DATE_TIME_COLUMN, date);
result = db.insertOrThrow(FUEL_USE_TABLE_NAME, null, values);
db.setTransactionSuccessful();
}
catch(SQLException e)
{
Log.d("addFuelUp", e.getMessage());
}
finally
{
db.endTransaction();
vehicleCursor.close();
fuelUpsCursor.close();
}
}
}
return result;
}
I.e. fuel data cannot be entered unless there is a matching vehicle registration number in the database.
My question is, is there a better way to do this? I'm not a database expert, but I know you can set up triggers to enforce rules - are triggers more suited to handle constraints?
Cheers,
Barry
Triggers would be a good solution to this problem.
In fact there is an automated way to generate triggers for simulating foreign keys. SQLite for PC provides a utility called "genfkey" which can examine an existing database which uses foreign keys and outputs the corresponding triggers.

Values stored using ContentValues are not in correct order, WHY?

currently I'm working on my 1st Android app and I encounter something I cannot solve. When I try to insert data into my own database there is an error: 07-18 03:41:04.414: ERROR/AndroidRuntime(3480): java.lang.NullPointerException
My code for inserting into table is:
public long createRecord(String created_time, String modified_time,
long reading, String unit, String period, String remark) {
ContentValues values = new ContentValues(6);
values.put(KEY_CREATED_TIME, created_time);
values.put(KEY_MODIFIED_TIME, modified_time); //System.out.println(values);
values.put(KEY_RECORD, reading); //System.out.println(values);
values.put(KEY_UNIT, unit); //System.out.println(values);
values.put(KEY_PERIOD, period);// System.out.println(values);
values.put(KEY_REMARK, remark);
System.out.println(values);
return mDb.insert(DATABASE_TABLE, null , values);
}
This is under my Adapter class which is an instance of my DatabaseHelper class. For my DatabaseHelper class, I can copy created database from assets folder into system databases folder. But just cannot create data into table, I tried to print out the "values", it showed that:
created_time=2010-07-18 03:41:04 remark=on unit=mg/dL reading=67 period=Before Meal modified_time=00:00:00
which was not the way it supposed to be, so I guessed this might be the problem.
Can anyone help me with this? Searched online but not so many info on this. Thanks in advance:)
The reason for the order not being retained is that ContentValues is backed by a HashMap. So that's ok.
The problem is likely caused by mDb being null (check it with System.out.println("" + mDb);).
if(db!=null){
ContentValues row = new ContentValues();
row.put("rt_id",tid);
row.put("rs_id", sid);
row.put("rsubject", rsubject);
row.put("rdescr",rdescr);
row.put("day", day);
row.put("month",month);
row.put("year",year);
row.put("stamp", stamp);
row.put("amount",amount);
long chk = db.insert("records",null, row);
if(chk!=0){
Toast.makeText(myContext, "Record added successfully",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(myContext, "Record added failed...! ",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(myContext, "could Not connected database..!!! ",Toast.LENGTH_LONG).show();
}
}catch(SQLiteException exc){
Toast.makeText(myContext, "Record could not saved...!!! ",Toast.LENGTH_LONG).show();
}finally{
db.close();
}
You can check your database object is null or not...Or checking it by just println it..All the best.
Have you seen the source code of sqliteDatabase i?It made a sql and handle it.but the order is based on :
Set<Map.Entry<String, Object>> entrySet = null;
if (initialValues != null && initialValues.size() > 0) {
entrySet = initialValues.valueSet();
Iterator<Map.Entry<String, Object>> entriesIter = entrySet.iterator();
I think something wrong with it? or the order will wrong when lots of values.Do you find somew

Categories

Resources