OR operation in WHERE clause - android

Right now my code looks like this:
Cursor cursor = getContentResolver().query(messagesUri, null,"address=?", smsNo, null);
where smsNo is a singleton array.
I would like to add elements to this array and implement an OR operation in the WHERE clause. Is this possible to do continuing to use an array?

I'm not quite sure what you're asking, but you certainly can continue to use an array here. If you're asking how to extend an existing array to have more items, you can use Arrays.copyOf(oldArray, newSize) to make additional space in it. And you can then just use multiple ? placeholders in your query string to reference the new items.
For example:
queryParameters = Arrays.copyOf(smsNo, 2);
queryParameters[1] = "another number"
Cursor cursor = getContentResolver().query(messagesUri, null,"address=? or address=?", queryParameters, null);

Related

More elegant way than using rawQuery for single results?

To get multiple results of a query I use Cursor c = mydatabase.rawQuery("command", null); and then while (c.moveToNext()) { ... }. Works as advertised.
But if I just want to have one result as in SELECT rowSomething FROM table WHERE [row] = 'Test' and I know that it will be one result, a string, can I do something like
String result = mydatabase.StringQuery("Command");?
Yes, for example with DatabaseUtils#stringForQuery().

How to make SQLite select query faster

Hello I am pretty new with SQLite and I am trying to deal with some database manipulation in my project.
I have a table with almost 4000 rows and this is the format of every row:
problem_id (string)
problem_no (string)
problem_title (string)
dacu (int)
I need to query a bunch of problem_no based on the problem_id. The quantity of query is almost 1000 at a time. So I wrote a query code like this:
Set<Integer> getProblemsTitle(HashSet<String> problemsIDs) {
SQLiteDatabase db = this.getReadableDatabase();
HashSet<Integer> problemNo = new HashSet<Integer>();
Cursor cursor = null;
for (Iterator<String> iterator = problemsIDs.iterator(); iterator.hasNext();) {
cursor = db.query(CommonUtils.PROBLEM_TABLE, new String[] {
CommonUtils.KEY_PROBLEM_NO },
CommonUtils.KEY_PROBLEM_ID + "=?",
new String[] { iterator.next() }, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
problemNo.add(cursor.getInt(0));
}
cursor.close();
}
db.close();
Set<Integer> set = new TreeSet<Integer>(problemNo);
return set;
}
I know this is not a optimized snippet. And I need to optimize it a lot to reduce the execution time of the query. I did it inside AsyncTask but it is taking too much time.
How can I do this efficiently with faster performance?
You might want to consider taking this out of the database. If you just grabbed all the problems, you could add them all in code. Running one SELECT with 4000 results is still going to be much faster than a thousand SELECT statements.
The approach would be to grab them all, but sorted(ORDER BY problem_id). You could then just check each item in problemIDs against it, and add when you get a match.
You could also use the IN operator as Mathew suggests, but I don't know how efficient that will be with 1000 items in the set.
Don't iterate over a collection of IDs, but use the IN operator in a WHERE condition.
SELECT * FROM Table WHERE problem_id IN (1,2,3,4,5)
This will return all the records in the set. Whereas you are querying them one at a time.
You could try compiling a query, and maybe you can try to load the database into memory before reading.
Create an index on the problem_id column.

How to get specific rows from ContentProvider?

I am a little new to using content providers. I was wondering how I would get specific rows from a content provider?
For example how would I get the first row of my provider?
This is what I tried but It isnt working:
final Cursor cursorConversations = getActivity().getContentResolver()
.query(CONTENT_URI, null, null, null, null);
Toast.makeText(
getActivity(),
cursorConversations.getString(cursorConversations
.getColumnIndex(Columns.TITLE)),
Toast.LENGTH_LONG).show();
you simply use cursor move methods ex:
cursorConversations.moveToFirst();
cursorConversations.moveToPosition(0);
cursorConversations.moveToNext(); // <-- if at beginning position
just to make this answer a little more meaty, a popular technique used to loop through the rows of the cursor 1 by 1 from the beginning is:
while (cursorConversations.moveToNext()) {
// do something
}
Because the moveToNext() method (as well as other move methods) return a boolean, the loop will exit when the last row has been reached and can no longer moved to the next. effective and easy on the eyes too. One more tip: the cursor starts at the -1 index, before the first position of a zero-based query index results.
use something like this:---
if(cursorConversations.moveToFirst()){
int size=cursorConversations.getCount();
for(int i=0;i<size;i++){
cursorConversations.getString(cursorConversations
.getColumnIndex(Columns.TITLE));
cursorConversations.moveToNext();
}
}
cursorConversations.close();
Or
while(cursorConversations.moveTonext())
{
cursorConversations.getString(cursorConversations
.getColumnIndex(Columns.TITLE));
}

Android: loading from SQLite Database

So I'm still building a Database to support a project of mine. There are two different things to be saved: first, attribute values of some player objects and second, simple values stored in a java class.
ATM my problem lies in the process of loading values of a player object and writing it in the respective class.
Now let's see some code:
Following you see the method I want to use for saving the values in the database.
That works fine atm, but I just realized I'm still passing the contentValues object an extra value for the 'ID' , which I did set - and planned to keep that way - as autoincrement.
Any Idea how to work this in accordingly?
public void savePlayer(Player player[]) {
for (int i = 0; i <= 3; i++) {
playerValues.put("ID", i);
playerValues.put("Name", player[i].getName());
playerValues.put("HP", player[i].getHp());
playerValues.put("Satisfaction", player[i].getsatisfaction());
playerValues.put("Hygiene", player[i].isHygieneInt());
playerValues.put("IsAlive", player[i].isAliveInt());
}
db.insert("playertable", null, playerValues);
}
Okay, hold on to your hats because this might look a bit like spaghetti - the load-method:
public void loadPlayer() {
String[] namecolumn = { "Name" };
String[] intcolumn = { "ID, HP, Satisfaction, Hygiene, IsAlive" };
String[] namesToString = new String[4];
for (int j = 0; j <= 3; j++) {
Cursor playerCursorName = db.query("playertable", namecolumn, "ID="
+ j, null, null, null, null);
namesToString = cursorToString(playerCursorName);
Resource.playerArray[j].setName(namesToString[j]);
}
for (int i = 0; i < 3; i++) {
int[] restToInt;
Cursor playerCursorInt = db.query("playertable", intcolumn, "ID="
+ i, null, null, null, null);
restToInt = cursorToInt(playerCursorInt, 4);
Resource.playerArray[i].setHp(restToInt[i]);
Resource.playerArray[i].setsatisfaction(restToInt[i]);
Resource.playerArray[i].setHygieneInt(restToInt[i]);
Resource.playerArray[i].setAliveInt(restToInt[i]);
}
}
Yeah, I know this looks pretty ugly but let me explain it:
Because there are 4 player objects I planned on iterating through the database entries by using the ID as identifier to get exactly one row at a time and writing the name and the other values of this object in the java class where I want to manage them within my project.
Note: same problem with autoincrement here than in the save method
In addition, I get a CursorIndexOutOfBoundsException when calling loadPlayer because
Index -1 is being requested - isn't that the result of an operation on the database resulting in an error?
Yeah that's pretty much it, I'll provide you with additional code if requested, hope someone can help me
You are using Cursors in a slightly odd way here.
The point of a Cursor is to ask SQLite to do the hard work of fetching data for you, and your job is simply to use the cursor to iterate through the returned values.
Firstly, I would change the query here to ask for all values in the table (and perhaps put some condition to constrain what you get back), to make sure your cursor then contains all your values.
Then, I would loop through the cursor's values by using a while loop, (with cursor.moveToPosition(-1) before the loop) moving along the cursor by using cursor.moveToNext().
See the API for more information:
http://developer.android.com/reference/android/database/Cursor.html
With regard to the autoincrement problem, as far as I can remember you can leave out the ID and use db.insert() without that field and the database will provide an ID for you.
You shouldn't have the same issue in your load method because it doesn't make sense to autoincrement when loading, you just get back what's in the database.

Android problem getting Arraylist<double[]> from cursor

I need to get a value from my cursor. The value needs to be in this format:
List<double[]> values = new ArrayList<double[]>();
The problem is when I do the ".add" it errors wanting me to change it to "length". I have to have it in the List for the app to work at all. Here is my code, is there a way to do that? What am I doing wrong?
cursor = managedQuery(Provider.CONTENT_URI,
proj,
null,
null,
null);
while (cursor.moveToNext()) {
double value;
column_value = cursor.getColumnIndex(CsvProvider.VALUE);
value = cursor.getDouble(column_value);
values.add(value); //this did not work
values.add(new double[] {value}); //this did work
} ;
Thanks Mike!
First of all, you should never paraphrase errors. If you get an error, copy and paste it into your question.
As to your problem:
You have a list of double arrays, i.e. every single entry in your cValues List needs to be a double[]. Instead, however, you're just adding a plain double. That won't work. I don't know how your list is supposed to be setup, if you put the [] in by mistake or if you really need a list of arrays, but assuming that every entry needs an array of one double, then you need to add a new double[] { value }.
Side note: Why not simply while (cursor.moveToNext()) { ... } instead of this do/while construct?

Categories

Resources