What's in Android cursor index -1? - android

I have just started Android.
So I'm using SQLite for an apps, and comes to something like
Cursor c = new Cursor()
c = db.rawquery(randomQueryString, null)
if (c!=null)
c.moveToFirst();
So, I have read somewhere that cursor default position is -1, and it is, according to the code above, not null, then what kind of data could possibly be in this position?

This the position "before first", being in this position make it more simple and clear to write a code to iterate thorough data in this cursor, you need just start looping from first as you would do in any other position.
Example:
if (cursor == null) {
//handle
}
while (cusor.moveToNext()) {
//do somehitng
}

Related

Unable to fetch the first entry in SQLlite Database using cursors in android

I am trying to fetch all the entries in a database table using SQLite. I ran a query, stored the values in a cursor and then via a loop I fetched all the values. However I can access all the entries except for the first one. Here is my code :
mydb1=new Database_CustomTransaction(getApplicationContext());
Cursor c12 = mydb1.executeQuery("Select * from table1");
System.out.println(c12);
if(c12 == null)
{
TextView nodataView = new TextView(this);
nodataView.setId(20);
nodataView.setText("No Data here !");
nodataView.setTextSize(20);
}
else
{
if(flagValue == false)
{
c12.moveToFirst();
flagValue = true;
}
while(c12.moveToNext())
{
type=c12.getString(0);
amount = c12.getInt(1);
spentOn = c12.getString(2);
date = c12.getString(3);
listType.add(i,type);
listSpentOn.add(i,spentOn);
listAmount.add(i,amount);
listDate.add(i,date);
i++;
}
}
latesttrans2.setAdapter(new TestAdapter2(this, listType, listSpentOn,listAmount,listDate));
Any ideas what I am doing wrong ?
c12.moveToFirst();
This moves to the first row.
while(c12.moveToNext())
This moves to the next row after the first row.
I would guess that the first call should be just dropped, but only you know what you intended with flagValue.
Use do while instead of using just while.I think it is skipping the first entry and straight away moving to next entry.

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));
}

Can't update event on phone's calendar from code

I'm attempting to update a calendar's event on my phone from my code, but context.getContentResolver().update keeps returning 0, and of course there are no changes made to the event when I look at it in the Calendar app.
I'm getting the event ID, start time, etc with context.getContentResolver().query, and I'm getting unique numbers like 431, 4, 233, etc, so I'm presuming the event IDs I'm using are real.
I understand the official way to do this is to go through Google's servers instead of using update(), but for my implementation it doesn't make sense to do it that way (or even in general, but I digress).
Am I doing something wrong, or am I trying to do something that Android simply isn't going to allow?
Uri updateEventUri = ContentUris.withAppendedId(Uri.parse("content://com.android.calendar/events"), id);
ContentValues cv = new ContentValues();
begin.set(Calendar.HOUR_OF_DAY, arg0.getCurrentHour()); //begin is a java.util.Calendar object
begin.set(Calendar.MINUTE, arg0.getCurrentMinute());
//cv.put("_id", id);
//cv.put("title", "yeahyeahyeah!");
cv.put("dtstart", begin.getTimeInMillis());
int updatedrowcount = context.getContentResolver().update(updateEventUri, cv, null, null);
System.out.println("updated "+updatedrowcount+" rows with id "+id);
A related question was posted here with no replies https://stackoverflow.com/questions/5636350/update-android-calendar-event
Let me know if I can clarify anything; I would really appreciate any input you guys and dolls could provide!
i had tried a lot and finally ended up with solution (Unreliable though).. but works fine..
public static boolean updateCalendar(Context context,String cal_Id,String eventId)
{
try{
Uri CALENDAR_URI = Uri.parse(CAL_URI+"events");
Cursor c = context.getContentResolver().query(CALENDAR_URI, null, null, null, null);
String[] s = c.getColumnNames();
if (c.moveToFirst())
{
while (c.moveToNext())
{
String _id = c.getString(c.getColumnIndex("_id"));
String CalId = c.getString(c.getColumnIndex("calendar_id"));
if ((_id==null) && (CalId == null))
{
return false;
}
else
{
if (_id.equals(eventId) && CalId.equals(cal_Id))
{
Uri uri = ContentUris.withAppendedId(CALENDAR_URI, Integer.parseInt(_id));
context.getContentResolver().update(uri, null, null, null);// need to give your data here
return true;
}
}
}
}
}
finally
{
return true;
}
}
and finally i'm not sure if it works with every device.
Ok, so, the problem was that I was using different URIs between fetching the events and editing them. I used the code sample from here and was using the URI "content://com.android.calendar/instances/when" to fetch the events and display them on the screen. When I had made a change I was using "content://com.android.calendar/events" to edit by id as in my example above.
What I found, thanks to your response, ntc, was that the ids for events between the two URIs were different, and therefore I couldn't edit the events consistently with the information each was giving me. I was presuming the event ids I was getting were system ids and universal to the phone.
I guess I'll have to do some testing and see what hardware isn't compatible with this method. I am using an HTC Evo for testing and so far so good.
When querying the Instances table, use Instances.EVENT_ID to get the identifier for the event you want to edit, instead of Instances._ID.

Get contacts in Android

I want to get the contact numbers in Android but as far as I found a tutorial, it puts out the number in ascending order, not in the order they appear in the contacts...
How can I modify the code to obtain the numbers in the exact order from my contact list??
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER}, null,null, null);
ArrayList <String> nr_formatat = new ArrayList <String> ();
if (cursor != null) {
while (cursor.moveToNext() == true)
nr_formatat.add(cursor.getString( cursor.getColumnIndex(Phone.NUMBER)));
}
You're going about it the wrong way. You need to query the number against the CONTACT_ID or else you won't have any correspondence between the two. Take a look at this tutorial.
It depends on how your contacts are ordered in your contact list. Hit the menu button and tap on 'Display Options'. Other than that, you don't have enough information in your question to adequately answer it.
From what I can see, you're going about it the wrong way. I would look over this example application. It fetches the contacts differently than you and will allow you to sort it however you want.
http://developer.android.com/resources/samples/BusinessCard/src/com/example/android/businesscard/index.html
Following should work if:
(Anna, 0342) has ID 1, (Lulu, 0311) has ID 2, (John, 0088) has ID 3
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER}, null,null, new String[]{Phone.ID});
ArrayList <String> nr_formatat = new ArrayList <String> ();
if (cursor != null) {
while (cursor.moveToNext() == true)
nr_formatat.add(cursor.getString( cursor.getColumnIndex(Phone.NUMBER)));
}
The last variable of ContentResolver().query() takes the sortorder. So here you put something like the ID, if your contactlist also sorts on ID.
ConecntResolver().Query() info here.

What to do with Cursor after a SQLite query?

This is my first time using a database and I'm not really sure how this works. I made the database and made a query that returns a cursor and... now what? What is a cursor, really? Can I just use that to navigate through my data or do I have to put it in an ArrayList or ListActivity or what?
You need to iterate the cursor to get your results.
Use cursor.moveToFirst() and/or cursor.moveToNext() (with a while loop). Then you can use the getX() method, like cursor.getInt() or cursor.getString().
For example, ir your are expecting one result from your query:
if (cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex('NAME'));
int age = cursor.getInt(cursor.getColumnIndex('AGE'));
} else {
// oops nothing found!
}
First call cursor.moveToFirst(). Each time you call cursor.moveToNext() it will move to the next row. Make sure when you are done with your cursor you call cursor.deactivate() or you will get errors in your log cat.
Iterate over the returned Cursor instance
public List<Object[]> cursorToTableRows(Cursor cursor) {
List<Object[]> result = new ArrayList<Object[]>(cursor.getCount());
cursor.move(0);
cursor.moveToNext();
while (cursor.isAfterLast() == false) {
Object[] tableRow = new Object[cursor.getColumnCount()];
for(int i=0; i<cursor.getColumnNames().length; i++) {
int columnIndex = cursor.getColumnIndex(cursor.getColumnName(i));
String columnValue = cursor.getString(columnIndex);
tableRow[i] = columnValue;
}
result.add(tableRow);
cursor.moveToNext();
}
cursor.close();
return result;
}
Then create the desired objects.
public List<Vehicle> getVehicles() {
List<Vehicle> vehicles = new ArrayList<Vehicle>();
Cursor cursor = null;
List<Object[]> objects = cursorToTableRows(cursor);
for(Object[] row : objects) {
int i=0;
Vehicle vehicle = new Vehicle(row[i++].toString(), row[i++].toString()));
vehicles.add(vehicle)
}
return vehicles;
}
from Developer.android: This interface provides random read-write access to the result set returned by a database query.
In other words: query returns you a set of data represented by a cursor. First you need to make sure you got a valid cursor (not null) and then try to move it to desired position in the data set (use moveToXXX methods). In order to obtain data pointed by cursor use getXXX methods. When done using it make sure to call close to release resources.
According to this link it looks like you can iterate through the query return using something like:
cursor.next();
And grab the data at the location you are looking for using:
cursor.getString(0)
After you successfully have your Cursor setup, you would typically want to display that to a view in some form.
Have a look at the following answer for a detailed, but simple example of using a Cursor Adapter to pair up your newly-minted Cursor with your desired XML View:
https://stackoverflow.com/a/20532937/293280

Categories

Resources