Android sqlite data insertion issue - android

i have created a database with the table name tbl_customer and tbl_product...i can view the tbl_customer values but can't see tbl_product values.. I use adb shell to confirm my insertion. Can any one plz help me to figure out the issue
private void addProFromDB() {
// TODO Auto-generated method stub
ArrayList<String> results = new ArrayList<String>();
SQLiteDatabase sampleDB = null;
try {
list = (ListView)findViewById(android.R.id.list);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, 1, null);
sampleDB.execSQL("create table tbl_product("
+ "pro_id integer PRIMARY KEY autoincrement,"
+ "pro_name text," + "pro_price integer);");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('1','Milk','60');");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('2','Sugar','70');");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('3','Oil','200');");
Cursor c = sampleDB.query(SAMPLE_TABLE_NAMES, null, null, null, null, null,
null);
char pro_nameColumnIndex = (char) c.getColumnIndexOrThrow("pro_name");
int pro_priceColumnIndex = (int) c.getColumnIndexOrThrow("pro_price");
} finally {
if (sampleDB != null)
sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAMES);
sampleDB.close();
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, new ArrayList()));
new AddStringTask().execute();
}
Also help me how i can get its primary key and display the selected value...
Best regards....

First, it is a good idea to consider using the insert() method on SQLiteDatabase, instead of executing INSERT statements via execSQL(), particularly if you do not have much SQL experience.
Second, normally, an INSERT statement lists the columns to be inserted into, which you are not doing. SQLite might support your syntax, but it makes for more fragile code.
Third, with an autoincrement column, you do not assign your own values, as you are trying to do.
Fourth, you are putting string values into integer columns. SQLite supports that, but not by actually converting the values to integers, but rather storing the strings themselves in the columns, which may not be what you want.
Fifth, getColumnIndexOrThrow() returns an int, not a char.
Sixth, you are deleting your data from the table milliseconds after inserting it, in your finally block, assuming that SAMPLE_TABLE_NAMES is set to tbl_product. If those values are not equal, then you are inserting into and querying from a table that does not exist.
Seventh, your Cursor is dead as soon as you close() the database in your finally block.
Some combination of those probably explains "the issue".

Related

android sql cursor error

Im playing with sql in android and found this issue:
Im reading data from my database:
SQLiteDatabase db = this.getReadableDatabase();
cursor = db.rawQuery("SELECT * FROM " + TABLE_SINGLE_APPS + " WHERE " + COLUMN_SINGLE_PACKAGE + "=?"
, new String[]{packageName});
SingleAppModel singleAppModel = new SingleAppModel();
and when I try to get cursor.getInt(3) over here:
try {
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
singleAppModel.setId(cursor.getInt(0));
singleAppModel.setAppName(cursor.getString(1));
singleAppModel.setPackageName(cursor.getString(2));
singleAppModel.setState(cursor.getInt(3) == 1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
cursor.close();
db.close();
It returns error:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0`
Weird is that if I delete line where Im calling cursor.getInt(3), it works.
Colum with that value exists and Im sure its of type INTEGER.
Also the value of cursor.getColumnCount() is 4 and value of cursor.getCount() is 1 ... so there are definetly some data...
Any advice?
Thankyou.
Rather than using * I suggest you to use,
cursor = db.rawQuery("SELECT COL0, COL1, COL2, COL3 FROM " + TABLE_SINGLE_APPS + " WHERE " + COLUMN_SINGLE_PACKAGE + "=?"
, new String[]{packageName});
Use the appropriate values for COL0, COL1, COL2, COL3 according to your table.
That way you make sure that the order of the columns fetched in the query.
But according to this,
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0`
I need more information to confirm, can you add your table schema, according to the issue there is no 3rd column in the database raw.
Edit:
This can be a small programmer mistake,
Look out for the onCreate and onUpgrade methods in SQLiteOpenHelper implementation

android second column returns no value

I have a problem to create a table. If I try to get a value from the second column, android writes a empty space in the toast. But if I try to get a value from the first column, android writes the value of the column correctly. The query functions to write the first column and to write the second column are equal. So I think the Creation of the Table is the problem. But look yourself:
public SQLiteDatabase tabelleerstellen(){
SQLiteDatabase leveldatabase = openOrCreateDatabase("leveldata.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
leveldatabase.setVersion(1);
final String CREATE_TABLE_LEVEL =
"CREATE TABLE IF NOT EXISTS tbl_level ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "ME1 TEXT, "
+ "ME2 TEXT, "
+ "ME3 TEXT, "
+ "ME4 TEXT, "
+ "ME5 TEXT, "
+ "ME6 TEXT, "
+ "ME8 TEXT, "
+ "GESCHAFFT INTEGER);";
leveldatabase.execSQL(CREATE_TABLE_LEVEL);
return leveldatabase;
}
public void tester(SQLiteDatabase leveldata){
ContentValues cursortester = new ContentValues();
cursortester.put("ME2","25");
leveldata.insert("tbl_level",null,cursortester);
String[] testerpr = {"ME2"};
Cursor testerprüfen = leveldata.query("tbl_level",testerpr,null,null, null, null,null,null);
testerprüfen.moveToFirst();
String dada = testerprüfen.getString(testerprüfen.getColumnIndex("ME2"));
Toast testertoast = Toast.makeText(getApplicationContext(),dada,Toast.LENGTH_SHORT);
testertoast.show();
}
Please check the following things:
Please make sure the table is up to date .. so try to call DROP TABLE IF EXISTS tbl_level; and recreate the table.
If you run a test make sure the table is completely empty ... so delete everything at the beggining of the test.
If the table can contain elements during the test then make sure you check the last inserted element. Please note that calling testerprüfen.moveToFirst(); moves the cursor to the first row in the table so checking that row every time is even if the table contains 50 elements is not a good thing. In this case you either use a sorting option in your query of uese while (testerprüfen != null && testerprüfen.moveToNext()) {// Your code here}
All in all I think your problem is that you already inserted more that one element in the able but you always check only the first element (with testerprüfen.moveToFirst();). Please not that there is a cursor.moveToLast() method that you can also call. This method moves the cursor to the last row in the table.

Insert null in Sqlite table

I am trying to figure how to insert a null value into an SQLite table in Android.
This is the table:
"create table my table (_id integer primary key autoincrement, " +
"deviceAddress text not null unique, " +
"lookUpKey text , " +
"deviceName text , " +
"contactName text , " +
"playerName text , " +
"playerPhoto blob " +
");";
I wanted to use a simple Insert command via execSQL but since one of the values is a blob I can't do it (I think).
So, I am using a standard db.Insert command.
How do I make one of the values null?
If I just skip it in the ContentValues object will it automatically put a null value in the column?
You can use ContentValues.putNull(String key) method.
Yes, you can skip the field in ContentValues and db.insert will set it NULL.
Also you can use the other way:
ContentValues cv = new ContentValues();
cv.putNull("column1");
db.insert("table1", null, cv);
this directrly sets "column1" NULL. Also you can use this way in update statement.
I think you can skip it but you can also put null, just make sure that when you first create the Database, you don't declare the column as "NOT NULL".
In your insert query string command, you can insert null for the value you want to be null. This is C# as I don't know how you set up database connections for Android, but the query would be the same, so I've given it for illustrative purposes I'm sure you could equate to your own:
SQLiteConnection conn = new SQLiteConnection(SQLiteConnString());
// where SQLiteConnString() is a function that returns this string with the path of the SQLite DB file:
// String.Format("Data Source={0};Version=3;New=False;Compress=True;", filePath);
try
{
using (SQLiteCommand cmd = conn.CreateCommand()
{
cmd.CommandText = "INSERT INTO MyTable (SomeColumn) VALUES (null)";
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// do something with ex.ToString() or ex.Message
}

Android SQLite Repeated Elements

I have an issue with SQLite on android. Right now, I'm pulling a JSON object from a server, parsing it, and putting each sub-object in a Table with things such as the Name, Row_ID, unique ID, etc. using this code:
public void fillTable(Object[] detailedList){
for(int i=0;i<detailedList.length;++i){
Log.w("MyApp", "Creating Entry: " + Integer.toString(i));
String[] article = (String[]) detailedList[i];
createEntry(article[0], article[1], article[2], article[3], article[4], article[5]);
}
}
createEntry does what it sounds like. It takes 6 strings, and uses cv.put to make an entry. No problems.
When I try to order them however, via:
public String[] getAllTitles(int m){
Log.w("MyApp", "getTitle1");
String[] columns = new String[]{KEY_ROWID, KEY_URLID, KEY_URL, KEY_TITLE, KEY_TIME, KEY_TAGS, KEY_STATE};
Log.w("MyApp", "getTitle2");
Cursor c = ourDatabase.query(DATABASE_TABLENAME, columns, null, null, null, null, KEY_TIME);
Log.w("MyApp", "getTitle3");
String title[] = new String[m];
Log.w("MyApp", "getTitle4");
int i = 0;
int rowTitle = c.getColumnIndex(KEY_TITLE);
Log.w("MyApp", "getTitle5");
for(c.moveToFirst();i<m;c.moveToNext()){
title[i++] = c.getString(rowTitle);
Log.w("MyApp", "getTitle " + Integer.toString(i));
}
return title;
}
Each entry actually has many duplicates. I'm assuming as many duplicates as times I have synced. Is there any way to manually call the onUpgrade method, which drops the table and creates a new one, or a better way to clear out duplicates?
Secondary question, is there any way to order by reverse? I'm ordering by time now, and the oldest added entries are first (smallest number). Is there a reverse to that?
If you don't want duplicates in one column then create that column with the UNIQUE keyword. Your database will then check that you don't insert duplicates and you can even specify what should happen in that case. I guess this would be good for you:
CREATE TABLE mytable (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
theone TEXT UNIQUE ON CONFLICT REPLACE
)
If you insert something into that table that already exists it will delete the row that already has that item and inserts your new row then. That also means that the replaced row gets a new _id (because _id is set to automatically grow - you must not insert that id yourself or it will not work)
Your second question: you can specify the direction of the order of if you append ASC (ascending) or DESC (descending). You want DESC probably.
Cursor c = ourDatabase.query(DATABASE_TABLENAME, columns, null, null, null, null, KEY_TIME + " DESC");

Android: Deleting specific row in database

Sorry if this seems obvious. I'm trying to write a method to delete a row from a String showId. What would be the best way, and can Cursors only be used for Selects or also for Deletes and Updates?
These are the two methods I'm at so far:
public int deleteShowById1(String showId){
Cursor cursor = db.rawQuery("DELETE FROM tblShows WHERE showId = '" + showId+"'", null);
if (cursor.moveToFirst()) {
return 1;
} else
return -1;
}
public int deleteShowById2(String showId) {
String table_name = "tblShows";
String where = "showId='"+showId+"'";
return db.delete(table_name, where, null);
}
As we know from mysql query, it is same here in android.
String query = "DELETE FROM " +TABLE_NAME+ " WHERE " + COLUM_NAME+ " = " + "'"+VALUE +"'" ;
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
db.close();
VALUE may or may not have single quotation depending on datatype.
I tend to use the second method (db.delete), as I think using rawQuery is frowned upon.
If you do a select, then loop through the cursor to do updates or deletes, that would make sense, but to pass a cursor to do the delete or update doesn't make sense to me, as the program won't know how to parse the cursor results to get the correct fields.

Categories

Resources