Android create Insert statement at runtime - android

I have fileds list & values list.I want to insert records using DBAdapter.I tried from this link http://mfarhan133.wordpress.com/2010/10/24/database-crud-tutorial-for-android/
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(Insert.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
initialValues.put("name", etName.getText().toString());
initialValues.put("age", etAge.getText().toString());
long n = dbAdapter.insertRecordsInDB("user", null, initialValues);
Toast.makeText(Insert.this, "new row inserted with id = " + n, Toast.LENGTH_SHORT).show();
Please anybody help me how to send the fields & their values at runtime.Please help me as soon as possible

You can make fields as String array & their value also make array.For example:
String[] strToFields = new String[names.length()];
String[] strToFieldsVal = new String[names.length()];
for (int k = 0; k < names.length(); k++) {
strToFields[k] = names.getString(k);
strToFieldsVal[k]=strVal;
}
calling method like
insertTableRecords(actualtable, strToFields, strToFieldsVal);
method should be:
public void insertTableRecords(String strTableName, String[] strToFields, String[] strValues){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(DownlaodTableActivity.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
for(int i=0 ;i<strToFields.length;i++){
initialValues.put(strToFields[i],strValues[i]);
}
long n = dbAdapter.insertRecordsInDB(strTableName, null, initialValues);
System.out.println( " -- inserted status : --- " + n);
}
If you need more help see this Android sqlite dynamic insert query

Related

Android SQLiteStatement Insert, nothing happen

i have some data from SoapObject, i want insert to sqlite, for better performance, i use the following code :
public void testInsert(String sql, SoapObject rs, int index) {
try {
sql = "INSERT INTO NSPMasterHarga (KdBarang, Wilayah, HargaJual1, HargaJual2) VALUES (?, ?, ?, ?)";
theDatabase = getWritableDatabase();
theDatabase.beginTransaction();
String drop = "DROP TABLE IF EXISTS NSPMasterHarga";
SQLiteStatement stmtDrop = theDatabase.compileStatement(drop);
stmtDrop.execute();
String create = "CREATE TABLE NSPMasterHarga (KdBarang TEXT PRIMARY KEY, Wilayah TEXT, HargaJual1 TEXT, HargaJual2 TEXT)";
SQLiteStatement stmtCreate = theDatabase.compileStatement(create);
stmtCreate.execute();
SQLiteStatement stmt = theDatabase.compileStatement(sql);
int count = rs.getPropertyCount();
for (int i = 0; i < count; i++) {
SoapObject row = (SoapObject) rs.getProperty(i);
for (int j = 1; j <= index; j++) {
stmt.bindString(j, row.getProperty(j - 1).toString().replace("anyType{}", ""));
}
long entryID = stmt.executeInsert();
stmt.clearBindings();
}
/*for (int i = 0; i < NUMBER_OF_ROWS; i++) {
//generate some values
stmt.bindString(1, randomName);
stmt.bindString(2, randomDescription);
stmt.bindDouble(3, randomPrice);
stmt.bindLong(4, randomNumber);
long entryID = stmt.executeInsert();
stmt.clearBindings();
}*/
theDatabase.setTransactionSuccessful();
theDatabase.endTransaction();
theDatabase.close();
}
catch (Exception ex)
{
String err = ex.getMessage();
}
}
When debug, i've got nothing error, but the data not insert to my sqlite.
Any idea or clue ?
Thanks
for better performance
I'm not so sure which part of the code you are referring to. Opening and closing the database after each interaction is terrible for performance. The SQLiteOpenHelper takes care of all this, so you don't need to do anything manually.
Try the following alternative to insert an entry:
public boolean addEntry(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("column1", "value1"); // make sure the type corresponds to your sql column type
values.put("column2", "value2");
values.put("column3", "value3");
values.put("column4Int", 1);
long newRowId = db.insert(TABLE_NAME, null, values);
Log.d("DBHelper", "Added row " + newRowId + " to DB.");
return newRowId != -1; // -1 means it failed
}

Getting specific value from Array which does not exist in database

I'm trying to get the value or data from the array that doesn't exists in the database.
public Cursor checkExistence(){
Cursor c=null;
String[] values={"headache","cold"};
SQLiteDatabase db= getReadableDatabase();
String query="SELECT * FROM "+TABLE_SYMPTOMS+" WHERE "+COLUMN_SYMP+" IN ("+toArrayRep(values)+")";
c=db.rawQuery(query,null);
Log.i("From Cursor","Cursor Count : " + c.getCount());
if(c.getCount()>0){
String val= c.getString()
Log.i("From Cursor","No insertion");
}else{
Log.i("From Cursor","Insertion");
}
db.close();
return c;
}
public static String toArrayRep(String[] in) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < in.length; i++) {
if (i != 0) {
result.append(",");
}
result.append("'" + in[i] + "'");
}
return result.toString();
}
In the String values={"headache","cold"} ,headache exists but cold does not exist in the database. From the code above, the Cursor returns Count=1 which is count>0 hence i can't insert into table.I would like to know how i can independently check whether the individual data exists, and the one which doesn't exist will be inserted into table.So in this case, "Cold" would be able to be inserted into the table.
If you use a single query to check all values, then what you get is a list of existing values, and you still have to search in the original list for any differences.
It is simpler to check each value individually:
String[] values = { "headache", "cold" };
SQLiteDatabase db = getReadableDatabase();
db.beginTransaction();
try {
for (String value : values) {
long count = DatabaseUtils.queryNumEntries(db,
TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value });
if (count == 0) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_SYMP, value);
db.insert(TABLE_SYMPTOMS, null, cv);
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You need check Cursor.moveToFirst()
True = Have records in cursor.
False = Dont have records.
Example my code:
return database.query( table.getNameTable(),
table.getColumns(),
table.getWhereSelectTableScript(),
null,
table.getGroupBySelectTableScript(),
table.getHavingSelectTableScript(),
table.getOrderBySelectTableScript(),
table.getLimitRecordsSelectTableScript());
See more here !

Android copy values from table and insert in another

I'm trying to copy all the data in a database table, which correspond to the WHERE clause, and insert them into another table. I'm trying this code, but in the table prev there are only 2 records in the table Ver are inserted more than 100 records .... why?
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
String sql = "SELECT data, unita_di_misura FROM prev WHERE numero ='"+numero_ricevuto+"'";
Cursor c = db.rawQuery(sql, null);
int count = c.getCount();
String[] data = new String[count];
String[] unita_di_misura = new String[count];
for(int i=0; i<count; i++) {
c.moveToNext();
data[i] = c.getString(0);
unita_di_misura[i] = c.getString(1);
}
for(int i=0 ;i < data.length;i++){
ContentValues cv = new ContentValues();
cv.put(VerTable.SI_NO, "0");
cv.put(VerTable .DATA, data[i]);
cv.put(VerTable .U_M, e.unita_di_misura[i]);
db.insert(VerTable .TABLE_NAME, null, cv);
}
c.close();
db.close();
}
Try this 3 line solution hope this will help you
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
String sql = "INSERT INTO "+VerTable .TABLE_NAME+" SELECT 0,data, unita_di_misura FROM prev WHERE numero = '"+numero_ricevuto+"'";
db.execSQL(sql);
db.close();
}
but in the table prev there are only 2 records in the table Ver are inserted more than 100 records .... why?
Possibly you ran the code more than once.
Also, pulling data from db only to insert it back is not very efficient. It's better to let the database engine do the work for you, e.g.
db.execSQL("INSERT INTO " + VerTable.TABLE_NAME +
"(" + VerTable.SI_NO + "," VerTable.DATA + "," + VerTable.U_M + ") " +
"SELECT 0, data, unita_di_misura FROM prev WHERE numero=?",
new String[] { numero_ricevuto });
Using ? params also avoids the possiblity of string SQL injection.

Application crashs when I try to view the entries of in a multiple tables Database

I created two table weekone and weektwo in my database. They a both uploaded the data in the database succussfully taken from EditTexts, however when I want to view the database by pressing Viewbutton, the application crashes.
This is how i am saving entries from Editext in database in table weekone
String treadmillTimings = durOnTreadmill.getText().toString();
DatabaseManager entry = new DatabaseManager(this);
entry.open();
entry.createEntry(treadmillTimings);
entry.close();
String stepperTimings = durOnStepper.getText().toString();
DatabaseManager entry1 = new DatabaseManager(this);
entry1.open();
entry1.week1createEntry1(stepperTimings);
entry1.close();
String stationaryRowingTimings = durOnStationaryRowing.getText().toString();
DatabaseManager entry2 = new DatabaseManager(this);
entry2.open();
entry2.week1createEntry2(stationaryRowingTimings);
entry2.close();
String exerciseBikeTimings = durOnExerciseBike.getText().toString();
DatabaseManager entry3 = new DatabaseManager(this);
entry3.open();
entry3.week1createEntry3(exerciseBikeTimings);
entry3.close();
String ellipticalTrainerTimings = durOnEllipticalTrainer.getText().toString();
DatabaseManager entry4 = new DatabaseManager(this);
entry4.open();
entry4.week1createEntry4(ellipticalTrainerTimings);
entry4.close();
Writing Entries in table weekone
//creating entry in table for treadmill in table week 1 with the help of ContentValues
public long createEntry(String treadmillTimings)
{
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
//enterting each exercise name corresponding to their respective edit Texts
cv.put(KEY_EXERCISENAME, "Treadmill");
cv.put(KEY_DURATION, treadmillTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv);
}
//creating entry in table for stepperTimings in table week 1 with the help of ContentValues
public long week1createEntry1 (String stepperTimings)
{
ContentValues cv1 = new ContentValues();
cv1.put(KEY_EXERCISENAME, "Stepper");
cv1.put(KEY_DURATION, stepperTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv1);
}
//creating entry in table for Stationary Rowing in table week 1 with the help of ContentValues
public long week1createEntry2 (String stationaryRowingTimings)
{
ContentValues cv2 = new ContentValues();
cv2.put(KEY_EXERCISENAME, "Stationary Rowing");
cv2.put(KEY_DURATION, stationaryRowingTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv2);
}
//creating entry in table for exercise bike in table week 1 with the help of ContentValues
public long week1createEntry3 (String exerciseBikeTimings)
{
ContentValues cv3 = new ContentValues();
cv3.put(KEY_EXERCISENAME, "Exercise Bike");
cv3.put(KEY_DURATION, exerciseBikeTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv3);
}
//creating entry in table for elliptical trainer in table week 1 with the help of ContentValues
public long week1createEntry4 (String ellipticalTrainerTimings)
{
ContentValues cv4 = new ContentValues();
cv4.put(KEY_EXERCISENAME, "Stationary Rowing");
cv4.put(KEY_DURATION, ellipticalTrainerTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv4);
}
Displaying entries in database
//displaying/reading data in the table using cursor
public String week1getData()
{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_EXERCISENAME, KEY_DURATION};
Cursor cur = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
//creating a result(string type variable) to store the text and display it.
String result = "";
int iRow = cur.getColumnIndex(KEY_ROWID);
int iExerciseName = cur.getColumnIndex(KEY_EXERCISENAME);
int iDuration = cur.getColumnIndex(KEY_DURATION);
// cursor start from the first position, keeps moving to the next as long as the position in not after that last.
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext())
{
/*getting the rows, exercise name and duration in the tables of database and setting it to result.
.The next time it loops, it will still have the prevoius result*/
result = result + cur.getString(iRow) + " " + cur.getString(iExerciseName) + " " + cur.getString(iDuration) + "\n";
}
return result;
}
All the code is same for tableweektwo except for the below
public String week2getData() <------- ERROR IS IN THIS METHOD, BASED ON LOGCAT
{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_EXERCISENAME, KEY_DURATION};
Cursor cur = ourDatabase.query(DATABASE_TABLE2, columns, null, null, null, null, null);
//creating a result(string type variable) to store the text and display it.
String result = "";
int iRow = cur.getColumnIndex(KEY_ROWID);
int iExerciseName = cur.getColumnIndex(KEY_EXERCISENAME);
int iDuration = cur.getColumnIndex(KEY_DURATION);
// cursor start from the first position, keeps moving to the next as long as the position in not after that last.
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext())
{
/*getting the rows, exercise name and duration in the tables of database and setting it to result.
.The next time it loops, it will still have the previous result*/
result = result + cur.getString(iRow) + " " + cur.getString(iExerciseName) + " " + cur.getString(iDuration) + "\n";
}
return result;
}
Addtionally I did exactly the same for weektwowhatever i did for weekone. please tell me where am I going wrong. thanks
Saw your logcat and it seems that your database is closed when you try to read the data. I would like to suggest to not to open and close the database so frequently. This creates a lot of confusion in the code. You can try to open the database at onCreate of your parent Activity(the context that you pass) and close it in onDestroy() only.
EDIT: You can refer this for design patterns.
EDIT 2 : You can confirm if this is the problem or not by opening the database only once and never closing it to see if the problem goes away. If it does the refer the linked article in previous edit.

how to get the database value to a String array in android(sqlite Database)

I have a database name "CUED" (sqlite Android)it have a table HELLO which contain a column NAME I can get the value to String from that column.
Let me show you my code section
myDB =hello.this.openOrCreateDatabase("CUED", MODE_PRIVATE, null);
Cursor crs = myDB.rawQuery("SELECT * FROM HELLO", null);
while(crs.moveToNext())
{
String uname = crs.getString(crs.getColumnIndex("NAME"));
System.out.println(uname);
}
It will print the value one by one. Now what I need is that I want to get the column values from database and so that I can store it in a String Array.
You already did the hard part... the array stuff is pretty simple:
String[] array = new String[crs.getCount()];
int i = 0;
while(crs.moveToNext()){
String uname = crs.getString(crs.getColumnIndex("NAME"));
array[i] = uname;
i++;
}
Whatever, I always recommend to use collections in cases like this:
List<String> array = new ArrayList<String>();
while(crs.moveToNext()){
String uname = crs.getString(crs.getColumnIndex("NAME"));
array.add(uname);
}
In order to compare the arrays, you can do things like this:
boolean same = true;
for(int i = 0; i < array.length; i++){
if(!array[i].equals(ha[i])){
same = false;
break;
}
}
// same will be false if the arrays do not have the same elements
String[] str= new String[crs.getCount()];
crs.movetoFirst();
for(int i=0;i<str.length();i++)
{
str[i] = crs.getString(crs.getColumnIndex("NAME"));
System.out.println(uname);
crs.movetoNext();
}
Enjoy it
This is my code that returns arraylist contains afield value:
public ArrayList<String> getAllPlayers() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT " + serailnumber + " as _id, " + title
+ " from " + table, new String[] {});
ArrayList<String> array = new ArrayList<String>();
while (cur.moveToNext()) {
String uname = cur.getString(cur.getColumnIndex(title));
array.add(uname);
}
return array;
}

Categories

Resources