check dynamically type's variables android - 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

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

Android Db Insert ContentValues

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.

How to determine if a column is boolean from cursor object?

I've result of a select query in a cursor object. I've some Boolean columns in the table. The value for Boolean type in SQLite is 0 or 1 depending on if they are false or true respectively. There are columns of int type too which can have value as 0 or 1 or other integer value. I want to return the value of a column from the cursor as,
if column is of boolean type
return true if value = 1
return false if value = 0
else
return the same value
How can I accomplish this?
How to determine if a column is boolean from cursor object?
So at first, SQLite does not have booleans type only integer, string, float, blob. So my suggestion is simply test value for int column and based on result perform appropriate action.
Cursor c = db.rawQuery(query, whereArgs);
int value = 0;
String[] intColumnNames = {columns};
int index = 0;
if (c.moveToFirst()) {
while (index < intColumnNames.length) {
do {
value = c.getInt(c.getColumnIndex(intColumnNames[index]));
switch (value) {
case 0:
// do some action
break;
case 1:
// do some action
break;
default:
// do some action for other cases
break;
}
} while(c.moveToNext());
index++;
}
}
As I have not faced similar problem before So I cannot post a gurranteed answer. but your question seems really interesting and after searching a bit I think one solution might be an option..
at first step before reading data determing the datatype of the column. For this the following links may be helpful
https://stackoverflow.com/a/6298521/931982
https://stackoverflow.com/a/3106349/931982
Then if you find that the column type is boolean then follow any of the solution provided by other two member.
N.B. it is not a confirmed answer, just posted my thinking. I would have commented this but it is too large to write in comment :(
While its true that SQLite doesn't have a BOOLEAN storage type, there's nothing to stop you defining a column with BOOLEAN as a data type. It will be stored as NUMERIC. Your application can use PRAGMA table_info( to get the data type and only do your true/false check if it is BOOLEAN.
try this
int columnNumber = 11;
while (cursor.moveToNext()) {
if( cursor.getInt(columnNumber) > 0){
//true
}
}
As there is no Boolean Data type in sqlite to use boolean you need to have data type INTEGER
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
More Details

Best way you can format a string in an Android TextView that is populated by SimpleCursorAdapter

I have two TextViews in a layout using a row layout for a SimpleCursorAdapter. The TextViews have their values populated from the SimpleCursorAdapter.
The first view displays the name of a computer host, that's fine but the second displays the mac address of the host, at current in the database I've got I'm storing it as a string in Hex format.
What I want to do is not have the formatting for the mac address in the database but format it programatically using a custom TextView or other else that will work. So basically AABBCCEEFF00 will become AA:BB:CC:EE:FF:00 when the SimpleCursorAdapter populates that TextView extened class.
What's the best way forward with this and where should I plug in the code if I do use custom TextView?
I've also seen reference to View Binding? but unsure if that's the route to go, I'm very much about making code modular and rather not override complex code when extending a simple class is possible.
As far as I could understand your question,You want to convert AABBCCDDEEFF into AA:BB:CC:DD:EE:FF programmatically.let me know if I didn't get your question.
look at following code,
from here,you are going to call a function to get formatted mac
String formattedMac = new String();
formattedMac=getFormattedMac("AABBCCDDEEFF");
Log.e("formatted Mac", formattedMac);//it will be look like, AA:BB:CC:DD:EE:FF
and here is the function returning formatted mac,
private String getFormattedMac(String mac) {
String result = new String();
result="";
int start=0;
int end=2;
int max=mac.length()+2;
while(end<max)
{
result = result+mac.substring(start, end);
if(end<mac.length())
{
result = result+":";
}
Log.e("result", result);
start=start+2;
end=end+2;
}
return result;
}
Turns out the best ways was with a ViewBinder setup, I followed this answer in the end.
Android, using SimpleCursorAdapter to set colour not just strings
Once I knew this I also changed the column to be a Blob instead of VarChar to make it a bit nicer as well.
SimpleCursorAdapter.ViewBinder binder = new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
String name = cursor.getColumnName(columnIndex);
if ("mac_address".equals(name)) {
byte[] macAddress = cursor.getBlob(columnIndex);
TextView textView = (TextView)view;
textView.setText(Target.getMacAddress(macAddress));
return true;
}
return false;
}
};

displaying integers in android using sqlite

I have a database that contains decimals. The column is set up as ".. decimal(5,2) not null. What I'm trying to do is to find the sum of the column and displaying it in a text field by using this code..
public int getTotal() {
Cursor cursor = sqliteDatabase2.rawQuery(
"SELECT SUM(thedata) FROM thetable", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
}
However, when returned the value is a whole number. It should be something like 20.75 instead of just 20.
I'm not very familiar with SQLite, so please help.
On top of Xperimental's answer, you are calling getInt() on the Cursor, and you are returning and int from getTotal(). Here, int is shorthand for integer, what you refer to as a "whole number". If you want floating-point values, use getFloat() and return a float or Float.
SQLite doesn't know the datatype DECIMAL, so it could be possible, that it defaults back to the INTEGER datatype it knows. Try to use another datatype, which is recognized by SQLite. The datatypes SQLite knows can be found on the following page:
http://www.sqlite.org/datatype3.html

Categories

Resources