Android Db Insert ContentValues - android

I'm having a problem with a ContentValues ​​that insert data into a db, then my situation is that I have to enter the pairs of values ​​that are being debugged, before insertion into the database, but then it just gives me I enter into the database, here is the code and then some screenshots.
public boolean insertElement(Element element) {
long ret = manager.db.insert(this.getTableName(element), null,
this.getContentValues(element, true));
if (ret == -1)
return false;
element.id = ret;
return true;
}
getTableName is my method to return the name of the table and that has always worked.
The problem is that I enter all the values ​​belonging to the value named "tipo", which is not included despite both within the content values.
This are some screenShot:
http://imageshack.us/photo/my-images/209/vyf.jpg/ After Insert
http://imageshack.us/photo/my-images/854/z2ua.png/ Element-ContentValues
Thanks

As per I can see the problem lies in your getContentValues Method . Can you give some detail about this method and you table structure as it will help me to find out the problem.
Thanks.

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.

Reading a value from a database

I have a database in my app with several columns of which 3 are: _id name selected.
Now, I want to read a single selected value from a row with the name being a string I get from some code. What would be the best way to do this?
Thanks
P.S. I am getting that value to check if it's 0 or 1 (only two possible values), so I want to ask how to make a kind of an if statement in the return field? I have seen some people do it with something resembling this: return true ? ... false
EDIT:
Okay, this is my code atm, haven't checked it yet since I need to do some other things to get it all up, but I think there may be a better way to do this.
public boolean isBandSelected(String name) {
// TODO Auto-generated method stub
Cursor cursor = mDb.query("bands", new String[] { "selected" }, "name="
+ name, null, null, null, null);
int index = cursor.getColumnIndex("selected");
String selected = cursor.getString(index);
return selected == "1";
}
You can use regular expression to match rows whose name field being string. Many databases can support regular expression.
The ternary operator(? :) can be used to make return statement like this.
return value == 0 ? false : true
But it depends on what kind of data type you what to return. Code above returns boolean data type.
The last line of your code above will always return false. This is because the == operator compares the reference of the two objects. you can use:
return "1".equals(selected);

Android - Database with ContentValue with boolean bug?

I created database table in my android app. I used this query:
CREATE TABLE foo (_id INTEGER PRIMARY KEY AUTOINCREMENT, mybool BOOLEAN)
Than I added row to the table, that the value of mybool will be true.
I ran the sqlite3 command to see the value in the table, and I saw:
_id | mybool
----------------------
1 | 1
That is corret, the true value became to 1.
The strange thing is in the reading. I read the table like that:
ContentValues values = new ContentValues();
Cursor cursor = db.rawQuery("SELECT * FROM foo", null);
DatabaseUtils.cursorRowToContentValues(cursor, values);
Then I get strange result:
values.getAsBoolean("mybool"); // return false - WRONG
values.getAsInteger("mybool"); // return 1 = true - CORRECT
I use the code like that to get boolean value:
values.getAsInteger("mybool") != 0;
But it's strange.
Why I get always false in the getAsBoolean function? Is there any bug in the ContentValues class? Anyone else having this problem?
DatabaseUtils.cursorRowToContentValues() stores everything as strings (except blobs). ContentValues.getAsBoolean() will attempt to convert the string to a boolean (using Boolean.valueOf()), but that only works if the string is equal to "true", not "1".
This looks like an Android bug to me.
You've skipped some code here.
What's your proof that values.getAsBoolean("mybool") returns false? You have to return a Boolean. How are you checking it?
ContentValues.getAs returns a value if the key can be found, or null if it can't or if the value can't be converted. Be sure that you're doing a full test.
getAsBoolean does not return a boolean but a Boolean wrapper object, which can be either null, Boolean.FALSE, or Boolean.TRUE.
If you can ensure that there aren't NULLs, use values.getAsBoolean("mybool").booleanValue() to get the actual value.
I don't know if it's the best solution for this problem, but this code below works for me:
Integer result = contentValues.getAsInteger(attributeName);
if(result == null || result == 0) {
parameter = false;
} else {
parameter = true;
}
Get boolean result like below:
boolean result = values.getAsInteger("mybool") == 1;

check dynamically type's variables android

I have a db, I open it and I extract query I need with a cursor. How can I check if variables I extract is int or string? Because i can't know which table I'm opening, everything is dynamic. So I can't use cursor.getString() or cursor.getInt()
EDIT
Sorry for my bad English, I'm italian
Found it. This method works:
public boolean isInt(String s){
boolean result=false;
try{
Integer.parseInt(s);
result=true;
}catch(Exception e){
}
return result;
}
This should help:
http://developer.android.com/reference/android/database/Cursor.html#getType(int)
Pass the column index to it. It should return you one of these
FIELD_TYPE_NULL
FIELD_TYPE_INTEGER
FIELD_TYPE_FLOAT
FIELD_TYPE_STRING
FIELD_TYPE_BLOB

Categories

Resources