I used to set text of my text view the count of my database rows. but it gives me an error. what should i do?
In My Handler Method:
public Integer METHOD_NAME(){
Cursor c = database.rawQuery( "SELECT * FROM MY_TABLE", null);
Integer first=c.getCount();
return first;
}
In My Activity Code:
int COUNT=db.METHOD_NAME();
db.open();
MyTEXTVIEW.setText(COUNT);
db.close();/* what is my Codes problem?
How to make it without problem? */
While i set the text of text view to a String, it doesn't show me any errors.
Firstly you should call the db.open() befor making a query as pointed by user370305 Secondly your METHOD_NAME() returns an Integer where as your COUNT variable is an int .
So you can do
int COUNT=db.METHOD_NAME().intValue()
Or change the return type of METHOD_NAME() type entirely to int
Convert int into String,
MyTEXTVIEW.setText(String.valueOf(COUNT));
Actually setText() only accept int as resource when your string resource is declared in string.xml file.
Update: I also doubt your code, you have db.open() method call after db.METHOD_NAME();, so if db.open() is for opening database connection than you have to change the sequence of both statements.
Like,
db.open();
int COUNT=db.METHOD_NAME();
MyTEXTVIEW.setText(COUNT);
db.close();/* what is my Codes problem?
Related
public void buttonA1(View view) {
int[] board = {R.id.A1, R.id.A2, R.id.A3, R.id.B1, R.id.B2, R.id.B3, R.id.C1, R.id.C2, R.id.C3};
int i=view.getId().intValue; //even this one didn't work
}
I would like to convert a view Id to int so that i can look it up in the array as shown. How do I do that?
I tried something like this int posNew = Arrays.asList(board).indexOf(view.getId()) but it kept saying the array has no object of type Integer.
I even tried this int posNew =Arrays.asList(board).indexOf(view.getId()), but still it didn't work.
int i=view.getId(); will return the view id as integer value.
And use sorting logic to check the position of the id in array of integer.
I don't know why you want to add them to an array, but this will work
ArrayList<Integer>arrayList;
arrayList = new ArrayList<>();
arrayList.add(new Integer(R.id.button));
arrayList.add(new Integer(R.id.button1));
.
.
.
ArrayList need objects so wrap the primitive int in an Integer object like
so
new Integer(R.id.button)
View's Id IS integer already. No need to convert anything. If you want to convert int to Integer then:
Integer viewId = new Integer(view.getId());
would do the job.
per documentation, the getId() method already returns an int. No conversion or methods are needed
I have an issue that may in fact be a design issue but I am struggling to find a way around it.
In my sqlite database in my android application, I have a table called Customer. This has around 40 columns of various string and int data types. In practice, any of these columns may or may not be null.
In my code, I have a function simply called getCustomer(), which queries the database for a specific customer, and places all their cells from the database into a Customer class, which contains variables for each column. I can then pass that customer object around as I wish. The getCustomer() function returns this Customer object.
My problem is integers which may be null. I am familiar with how int cannot be null in java, but how Integer can be null. But my problem actually lies in the fact that the cells in the database can be empty (eg null).
For string columns, I simply do this:
Customer cust = new Customer();
cust.firstName = cursor.getString(0);
If cursor.getString(0); returns a null value, then the firstName variable is assigned null. Nice and simple. However with an int:
Customer cust = new Customer();
cust.daysSinceJoining = cursor.getInt(5);
The above crashes at run-time if daysSinceJoining is null. So I tried the following:
Customer cust = new Customer();
if (cursor.getInt(5) != null)
cust.daysSinceJoining = cursor.getInt(5);
However this gives me a compiler error, as you cannot use an int in a null comparison like that.
How can I get around this problem? How can I retrieve an int from an sqlite database when the int value could be null?
#sanders is right about the isNull() method and here's how you edit your code to use it:
Customer cust = new Customer();
if (!cursor.isNull(5))
cust.daysSinceJoining = cursor.getInt(5);
You could try the isNull() function.
Please take a look to that answer:
getInt null-constraints
I think that should work for you:
int lIndex = cursor.getColumnIndexOrThrow(COLUMN);
Integer lInteger = null;
if (!cursor.isNull(lIndex)
lInteger = cursor.getInt(lIndex);
You can create a cursor wrapper and add new functionality to the cursor class:
public class CustomCursor extends CursorWrapper {
public CustomCursor(Cursor cursor) { super(cursor); } //simple constructor
public Integer getInteger(int columnIndex) { // new method to return Integer instead of int
if (super.isNull(columnIndex)){
return null;
}else{
return super.getInt(columnIndex);
}
}
}
Example usage:
Cursor defaultCursor = db.rawQuery("select null,2 ", null);
defaultCursor.moveToFirst();
CustomCursor customCursor = new CustomCursor(defaultCursor);
customCursor.moveToFirst(); //custom cursor can do anything that default cursor can do
int defaultInt0 = defaultCursor.getInt(0); //nulls are usually converted into zero
int defaultInt1 = defaultCursor.getInt(1); //2 is correct
int customInt0 = customCursor.getInt(0); //these 2 are same as above , ie zero and 2
int customInt1 = customCursor.getInt(1);
Integer customInteger0 = customCursor.getInteger(0); // this will give a null Integer
Integer customInteger1 = customCursor.getInteger(1); // this will give a 2 Integer
Log.v("custom log.v call ", "lets see what outputs, null is usually converted to the word 'null' by the String.valueOf method :"
+String.valueOf(defaultInt0)+","+String.valueOf(defaultInt1)+","
+String.valueOf(customInt0)+","+String.valueOf(customInt1)+","
+String.valueOf(customInteger0)+","+String.valueOf(customInteger1)
);
//V: lets see what outputs, null is usually converted to the word 'null' by the String.valueOf method :0,2,0,2,null,2
if (cursor.getInt(5) !=0){
cust.daysSinceJoining = cursor.getInt(5);
}
or
int index = cursor.getColumnIndex(KEY_NAME);
Integer x = null;
if (!cursor.isNull(index)
cust.daysSinceJoining = cursor.getInt(5);
}
see the documentation
getInt() documentation:
I try to get an Item out of my SQL db in android, everything goes well, the only thing I am struggling with is to get the INTEGER value is there is nothing filled in in the DB (null?)
So I first initialize it, then get the Integer value out of the DB and then assign it to an instance of my class. I was once told that if it will get nothing out of the DB it will keep the initialized value, but this might be wrong? I use now:
int score = 100;
score = c.getInt(11);
q.setScore(score);
I was once told that if it will get nothing out of the DB it will keep the initialized value
That is true for Embedded SQL. You seem to be using a resultset object, so it is not true.
Resultset objects typically return 0 if you try to get a numeric null value from a column.
Use c.wasNull() to check if the value you just read was null and not 0.
EDIT (added the code from Jack's comment):
int score;
if (c.isNull(11)) {
score = 100;
} else {
score = c.getInt(11);
}
q.setScore(score);
http://developer.android.com/reference/android/database/Cursor.html#getInt(int)
*public abstract int getInt (int columnIndex) Since: API Level 1 Returns the value of the requested column as an int. The result and
whether this method throws an exception when the column value is null,
the column type is not an integral type, or the integer value is
outside the range [Integer.MIN_VALUE, Integer.MAX_VALUE] is
implementation-defined. Parameters columnIndex the zero-based index of
the target column. Returns the value of that column as an int.*
I'm using Sqlite in Android and to get a value from the database I use something like this:
Cursor cursor = sqliteDatabase.rawQuery("select title,category from table", null);
int columnIndexTitle = cursor.getColumnIndex("title");
iny columnIndexCategory = cursor.getColumnIndex("category");
cursor.moveToFirst();
while (cursor.moveToNext()) {
String title = cursor.getString(columnIndexTitle);
String category = cursor.getString(columnIndexCategory);
}
cursor.close();
I want to create my own Cursor so that I can do getColumnIndex() and getString() with one method. Something like this:
String title = cursor.getString("title");
I want to create my own class that extends the cursor that I get from sqliteDatabase.rawQuery, but I'm not sure how to accomplish this. Should I extend SQLiteCursor or how should I do this? Is it even a possible and is it a good idea?
I came across this question looking for the best way to create a custom Cursor to use together with a SQLiteDatabase. In my case I needed an extra attribute to the Cursor to carry an additional piece of information, so my use case is not exactly as in the body of the question. Posting my findings in hope it will be helpful.
The tricky part for me was that the SQLiteDatabase query methods returns a Cursor, and I needed to pass on a custom subclass to Cursor.
I found the solution in the Android API: Use the CursorWrapper class. It seems to be designed exactly for this.
The class:
public class MyCustomCursor extends CursorWrapper {
public MyCustomCursor(Cursor cursor) {
super(cursor);
}
private int myAddedAttribute;
public int getMyAddedAttribute() {
return myAddedAttribute;
}
public void setMyAddedAttribute(int myAddedAttribute) {
this.myAddedAttribute = myAddedAttribute;
}
}
Usage:
public MyCustomCursor getCursor(...) {
SQLiteDatabase DB = ...;
Cursor rawCursor = DB.query(...);
MyCustomCursor myCursor = new MyCustomCursor(rawCursor);
myCursor.setMyAddedAttribute(...);
return myCursor;
}
Creating your own getString will cause a map lookup for each call instead of only for getColumnIndex.
Here's the code for SQLiteCursor.getColumnIndex and AbstractCursor.getColumnIndex. If you have many rows, reducing calls to this function will prevent unnecessary string processing and map lookups.
I wouldn't extend it, I'd make a helper:
class MartinCursor {
private Cursor cursor;
MartinCursor(Cursor cursor) {
this.cursor = cursor;
}
String getString(String column) {
....
}
}
or
class MartinCursorHelper {
static String getString(Cursor cursor, String column) {
....
}
}
Personally, I'd do the latter, unless you hate providing this extra argument all the time.
EDIT: I forgot to mention pydave's important point: If you call this in a loop, you're setting yourself up for a noticeable performance impact. The preferred way is to lookup the index once, cache it, and use that instead.
You should make use of the DatabaseUtils.stringForQuery() static method that is already in Android SDK to easily retrieve a value, this example is for String bot there is also method for Long
stringForQuery(SQLiteDatabase db, String query, String[] selectionArgs)
Utility method to run the query on the db and return the value in the first column of the first row.
Something like
String myString=DatabaseUtils.stringForQuery(getDB(),query,selectionArgs);
Came across this looking for a different solution, but just want to add this since I believe the answers are unsatisfactory.
You can easily create your own cursor class. In order to allow functions requiring Cursor to accept it, it must extend AbstractCursor. To overcome the issue of system not using your class, you simply make your class a wrapper.
There is a really good example here.
https://android.googlesource.com/platform/packages/apps/Contacts/+/8df53636fe956713cc3c13d9051aeb1982074286/src/com/android/contacts/calllog/ExtendedCursor.java
public class ExtendedCursor extends AbstractCursor {
/** The cursor to wrap. */
private final Cursor mCursor;
/** The name of the additional column. */
private final String mColumnName;
/** The value to be assigned to the additional column. */
private final Object mValue;
/**
* Creates a new cursor which extends the given cursor by adding a column with a constant value.
*
* #param cursor the cursor to extend
* #param columnName the name of the additional column
* #param value the value to be assigned to the additional column
*/
public ExtendedCursor(Cursor cursor, String columnName, Object value) {
mCursor = cursor;
mColumnName = columnName;
mValue = value;
}
#Override
public int getCount() {
return mCursor.getCount();
}
#Override
public String[] getColumnNames() {
String[] columnNames = mCursor.getColumnNames();
int length = columnNames.length;
String[] extendedColumnNames = new String[length + 1];
System.arraycopy(columnNames, 0, extendedColumnNames, 0, length);
extendedColumnNames[length] = mColumnName;
return extendedColumnNames;
}
That's the general idea of how it will work.
Now to the meat of the problem. To prevent the performance hit, create a hash to hold the column indices. This will serve as a cache. When getString is called, check the hash for the column index. If it does not exist, then fetch it with getColumnIndex and cache it.
I'm sorry I can't add any code currently, but I'm on mobile so I'll try to add some later.
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