updating record in android programming - android

I am writing a program to display the details of students' record in android. I am using a existing database and getting the data from it. Here I need to update the status as confirmed.
I have created a confirmation button which on pressing will update the status as confirmed. Here on pressing the button my code shows no error but the value is not updated in the database. For information I am using sqlitebrowser as my database.
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues();
//contentValues.put(DatabaseHelper.STATUS,"CONFIRMED");
StudentDetails = SQLiteDatabase.openDatabase("", null, SQLiteDatabase.OPEN_READWRITE);
//status.setText("CONFIRMED");
//mDbHelper.close();
values.put("Status", "Confrimed");
StudentDetails.insert("Student","", values);
Toast.makeText(getApplicationContext(), "Status upadated", Toast.LENGTH_LONG).show();
StudentDetails.close();
}
}

I noticed you've supplied "" as the argument to path for openDatabase(). Unless you're calling this on a member that will open the appropriate database, I believe this wouldn't open a valid database, and thus I wouldn't be surprised if a row didn't get written to the table you were trying to modify. Perhaps try supplying a database file name instead of a blank string and see if that works.
Also, if you're not implementing SQLiteOpenHelper in your own class as outlined in Saving Data in SQL Databases, I would suggest trying that instead of accessing the database in another way, if it isn't too much trouble. I've just made an app using this method, and I have no problems.
Nonetheless, I would assign a long to the output value of the insert function, and set a debug point or write its value of the console. If the value is -1, the method didn't assign a row to the table (possibly because of database constraints - perhaps check that you're satisfying them in terms of the values supplied in the Bundle).
The value returned from insert will be -1 if an error occurred, as outlined in the docs for insert(String table, String nullColumnHack, ContentValues values)).

You should use StudentDetails.update("Student","", values);

Related

Data insertion failed after wiped out app data emulator

Inserting data in SQlite from EditText
Code was working well before i wiped out data from emulator now its giving me Null Pointer Exception, Kindly figure where actual problem lies. Thanks
Data is being inserted from here ]
public long insert(String name, String password, String role, String unique) {
sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_USERNAME, name);
contentValues.put(KEY_PASSWORD, password);
contentValues.put(KEY_ROLE, role);
contentValues.put(KEY_UNIQUE, unique);
long result = sqLiteDatabase.insert(DOCTOR_TABLE,
null,
contentValues);
sqLiteDatabase.close();
return result;
}
SQLite Database class
Well. It's an obvious.
As you mentioned you have wiped the data, so the table which is located in the android app's own data folder will be deleted too. So you must check whether it exists or not.
Call to Getting your table returns null.
So you inserting your value to nothing.
So You can just alter the code to see if the table exists and if not create it.
Basically you just call,
CREATE TABLE IF NOT EXISTS method(SQLite 3.3 and above support IF NOT EXISTS). When you first call it, if not existed, it will create that table but later it will return the existing table with same name.
In one line- check or get the correct table before you do any operation.

How to write a common code for inserting data in android's Sqlite

For inserting into sqlite presently I have to follow these steps:
Create contentValues i.e. ContentValues contentValues = new ContentValues();
Put column_name and Value
lastly, call sqLiteDatabase.insert(DATABASE_NAME,null,contentValues)
Problem is only in step 2,we have manually Columnname and Columnvalue for n number of times assuming I have n Columns to persist.
So, I wrote the following method thinking I can reuse it:
public void insert(Map tableMap){
ContentValues contentValues = new ContentValues();
Iterator tableMapIterator = tableMap.entrySet().iterator();
while(tableMapIterator.hasNext()){
Map.Entry mapEntry = (Map.Entry)tableMapIterator.next();
contentValues.put((String)mapEntry.getKey(), mapEntry.getValue());
}
sqLiteDatabase.insert(DATABASE_NAME,null,contentValues)
}
But the problem is that when I call mapEntry.getValue(), the return type is Object for which contentValues.put is not defined.
So, can anyone tell me any workaround so that I can use the above approach efficiently to do the data insertion.
NOTE : I want to write method so that I can use it for all data types in SQLITE.
The objects that will access your ContentMap will be verified by this method DatabaseUtils.getTypeOfObject()
Therefore, if you put anything in your ContentValue that is not one of the expected type, it will be assumed to be a String, and in bindArguments(), toString() will be called on it.
Now, assuming that all your object are either recognized valid types, or have sufficient String representation (for instance, a File object would give its path, which is sufficient to recreate it when you extract it from the database), there are ways to put an arbitrary Map in a ContentValue.
The trivial way is to use reflection to access the internal map, which is consistently named mValues across all versions of android.
Another, shorter (but slower) and clearer way, I find, is to use the Parcel mechanism. Indeed, ContentValue.writeToParcel only writes the internal map.
The entire code is here:
Parcel parcel = obtain();
parcel.writeMap(map);
parcel.setDataPosition(0);
ContentValues values = ContentValues.CREATOR.createFromParcel(parcel);
Detailed explanation on my blog : http://njzk2.wordpress.com/2013/05/31/map-to-contentvalues-abusing-parcelable/
I am not exactly sure if i get your question but i will try my best.
1) You can use some kind of already written ORM. - It can automatically detect field types.
2) You can write your own simple ORM to handle situations like this. When i want to automatically add object to DB, i inherit this table object from GenericTableObject, which has methods like getFieldsValues, getFieldsTypes etc... With help of these methods, it is fully automated.
You will probably spend a few hours by writing this generic table object but it is usefull. - It is all about java reflection.
try this one
public void addEntity(EntityClass e) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("Name",e.getmProductName());
values.put("Price",e.getmProductPrice());
values.put("Date",e.getmPurchaseDate());
// Inserting Row
db.insert(TABLE_Accounts, null, values);
Log.d("insert", "success");
Toast.makeText(mContext, "Info added Successfully", Toast.LENGTH_SHORT).show();
db.close(); // Closing database connection
}

Insert rows to a database table : check if it worked?

I have in my database two tables : one is full of content and the other just is empty (I have only built the name of the fields and that's it). The whole database is in the assets folder of my application.
I have a method supposed to add a new element to this empty table every time I click on a button.
OnClickListener poi_favoritesbutton_listener = new OnClickListener(){
#Override
public void onClick(View v) {
DatabaseAdapter.insertInTable(ID_NAME, ID_CAT1, ID_CAT2, ID_CAT3, ID_CUISINE);
}
};
Here is the method :
public static long insertInTable(String ID_NAME, String ID_CAT1,
String ID_CAT2, String ID_CAT3, String ID_CUISINE) {
ContentValues data = new ContentValues();
data.put(FAV_NAME, ID_NAME);
data.put(FAV_CAT1, ID_CAT1);
data.put(FAV_CAT2, ID_CAT2);
data.put(FAV_CAT3, ID_CAT3);
data.put(FAV_CUISINE, ID_CUISINE);
if (myDatabase == null) {
}
return myDatabase.insert("DATABASE_FAVTABLE", null, data);
}
I think it should be correct as I have followed what was discussed on SOF related topics but I'd like not just to "think" and be sure instead! I tried using debug mode / DDMC but no way to actually open my database in real time and check for evolution of its content...
Any suggestion ? Thanks !
ps: i'm using a real device to run my test, emulator is just killing my time.
According to insert() docs:
Returns
the row ID of the newly inserted row, or -1 if an error occurred
so basically all you need is to check if you did not get said -1 in return.
no way to actually open my database in real time and check for evolution of its content
You can pull the database table to the device and see the contents of the table under DDMS tab-> File Explorer

Populate an SQLiteDatabase in Android with static data

I have a database with multiple tables. One of these tables (sport) is where i have to put a static list of object, each one with an _id, name, logo and an int. The _id will be used by other tables to do some queries (eg. select from "table X" where sport_id = _id), so it shouldn't change overtime (is there a way to update all the reference to this _id if it will change?).
Where should i put the code (i think it will be a simple list of db.insertSport()) to make it add this row only one time (and check if the row number grow, to add the new ones)?
There won't be much row, 50 at the best.
I think I would make a method in the dbHelper to insert that data, then call that method immediately upon app start. I'm making a couple of assumptions here... first that you are shipping this static info with the app and when you want to add more info you will be shipping a new version.
You could store the data as a text file in your assets folder and then read the file in execute a batch insert in the method.
If you set it up right (use insertWithOnConflict and the CONFLICT_IGNORE flag in the method) it will only add the new rows (if any) each time so you can run it every time the app starts and not worry about duplicate data or crashes for constraint violations.
If you only want it to run the once and then again when there is additional info, put a version number in the text file and check that against the previous one (which you can store in SharedPreferences).
EDIT
Example of using insertWithOnConflict:
public long createItem(String yourdata) {
ContentValues initialValues = new ContentValues();
initialValues.put(YOUR_COLUMN, yourdata);
return mDb.insertWithOnConflict(YOUR_TABLE, null, initialValues,
SQLiteDatabase.CONFLICT_IGNORE);
}
You can read up on the SQLiteDatabase class (which has the constants and methods) here

Android Update Query

I’m using a database helper to update a table with one row and two fields, I have the following code that that sends two phone numbers through.
dbHelper.updateNumbers(newSmsNumber, newVoiceNumber);
and the following method in the helper.
public void updateNumbers(String newSmsNumber, String newVoiceNumber) {
//Update code here
}
Can anyone show me the code I need to add in the method to update the two fields in the database.
Cheers,
Mike.
ContentValues cv = new ContentValues();
cv.put("SMS", newSmsNumber);
cv.put("Voice", newVoiceNumber);
db.update("[table name]", cv, "ID=?", new String[]{Integer.toString(id)});
There are some gaps to fill up though, the table name, and how you identify the entry you want to update (I put a "ID" field there in that example)
Did not run that code, did not really check, but that should give you an idea.

Categories

Resources