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.
Related
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
}
I'm using Xamarin.Mobile Component for Android to fetch contacts using the code:
var book = new AddressBook (Activity) {PreferContactAggregation = true};
var contData = data.Data;
var cur = Activity.ManagedQuery (contData, null, null, null, null);
Contact myContact = null;
var lookupKeyList = new List<string> ();
while (cur.MoveToNext ()) {
lookupKeyList.Add (cur.GetString (cur.GetColumnIndexContactsContract.Contacts.InterfaceConsts.LookupKey)));
}
myContact = book.Where (c => c.Id == lookupKeyList [0]).First ();
This code is part of picking a contact from the phone book and receiving the data on OnActivityResult method.
Unfortunately, this code is taking up too much time on some devices and is instantaneous on others. I guess its related to Contact Aggregation but I am not sure. Any pointers?
Sounds like an Android issue, not necessarily a Xamarin issue. Take a look at the question Getting name and email from contact list is very slow. One of the things this answer does is use a Projection in the query to get all the columns in one go.
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.
I'm creating an Sms app which contains a ListView in the Main Activity that displays all the conversations from the sms inbox. Each ListView row displays one conversation along with the phone number, message body and time of the message. Now instead of the phone number I want to display the contact name if it exists.
So far, for getting the contact name by phone number I found this code
private String getDisplayNameByNumber(String number) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor contactLookup = context.getContentResolver().query(uri, new String[] {ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);
int indexName = contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME);
try {
if (contactLookup != null && contactLookup.moveToNext()) {
number = contactLookup.getString(indexName);
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
return number;
}
But this seems inefficient as it has to make a query for each contact name individually and lags the app. So instead I tried to get all the contact names from the phone and store it in an HashMap with the phone number as the key and the contact name as the value, so that I can get the contact name any time I want from the HashMap. But there seems to be another problem, the phone numbers are stored in many different formats, for eg:
+91 4324244434
04324244434
0224324244434
So how do I search for a phone number from the HashMap since it can be stored in many different formats?
Before you add the contact to the HashMap, use regular expression to grab the phone number. This way, no matter what format the phone number is in, the regular expression will be able to grab the appropriate number needed.
Once you grab the number, add it to the HashMap accordingly.
Hope that answers your question.
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