How to get Phone number from Android Cursor? - java

Following this tutorial I'm trying to get the phone number of a person in the contacts list. With this code I can get the email address:
if (cursor.moveToFirst()){
int emailIdx = cursor.getColumnIndex(Email.DATA);
String email = cursor.getString(emailIdx);
Log.wtf("Email address: ", email);
}
Following this reasoning I tried to get the Phone number like this:
if (cursor.moveToFirst()){
int phoneNrIdx = cursor.getColumnIndex(Phone.DATA);
String phoneNr = cursor.getString(phoneNrIdx);
Log.wtf("Phone number:", phoneNr);
}
Unfortunately this also returns the email address. Does anybody know how I can get the phone number of this contact? All tips are welcome!

Both Email.DATA and Phone.DATA equal the same string, namely 'data1'. That is the name of the column holding the data in the cursor, hence both of your code snippets are effectively the same.
I understand you queried Email.CONTENT_URI, hence the cursor has the email address only in column 'data1'.
To get the phone number as well, close the cursor and then query Phone.CONTENT_URI to get a cursor holding the phone number instead.

Related

SQLite database saves String as "0"

I've just learned how to use SQLite database in Android. And i have one error which i cant figure out.
When i try to save string in my sqlite database, it saves it always as "0", no matter which string i use as an input. This is my code example.
ContentValues values = new ContentValues();
Log.i("CrimeLab", "put : "+crime.getId().toString());
values.put(CrimeDbSchema.CrimeTable.Cols.UUID, "31b0a98a-4089-46de-8325-4ec673bbd713"); // crime.getId().toString()
Log.i("CrimeLab", "take: "+values.getAsString(CrimeDbSchema.CrimeTable.Cols.UUID));
values.put(CrimeDbSchema.CrimeTable.Cols.TITLE, crime.getTitle());
values.put(CrimeDbSchema.CrimeTable.Cols.DATE, crime.getDate().getTime());
values.put(CrimeDbSchema.CrimeTable.Cols.UUID, crime.isSolved() ? 1 : 0);
I have class Crime which have it's unique UUID, title, date and if crime is solved. Everything is saved perfectly but only UUID.toString() is saved in database as "0". No matter which string i try to put it will be saved as "0" in my database, here's the picture.
Here is how it is displayed in the database, everything is good except this string. I have one book, from where i follow my lectures, and it is the same code from the book and it doesn't work. This is how i get my value back from the database.
public class CrimeCursorWrapper extends CursorWrapper
{
public CrimeCursorWrapper(Cursor cursor)
{
super(cursor);
}
public Crime getCrime(){
String uuidString = getString(getColumnIndex(CrimeDbSchema.CrimeTable.Cols.UUID));
String title = getString(getColumnIndex(CrimeDbSchema.CrimeTable.Cols.TITLE));
long date = getLong(getColumnIndex(CrimeDbSchema.CrimeTable.Cols.DATE));
int isSolved = getInt(getColumnIndex(CrimeDbSchema.CrimeTable.Cols.SOLVED));
// And so on.
Everything is saved perfectly but only UUID.toString() is saved in database as "0".
That is because you have not solved any crimes, and you probably have a typo in your code.
In your code snippet, you are setting CrimeDbSchema.CrimeTable.Cols.UUID twice. Once it is the UUID. Once it is 0 or 1 depending on isSolved().
I would assume that the second occurrence needs a different column name.

Content Provider ListView Limit

I would like to limit the amount of contacts displayed in my app. Currently it is querying my Contactscontract.Contacts DB and returning every primary display name that has a phone number. Is there a simple way to reduce this to a numerical amount (say only display 5 contacts), or to certain specified ID's?
This is what I have so far:
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// load from the "Contacts table"
Uri contentUri = ContactsContract.Contacts.CONTENT_URI;
// no sub-selection, no sort order, simply every row
// projection says we want just the _id and the name column
return new CursorLoader(getActivity(),
contentUri,
PROJECTION,
ContactsContract.Contacts.HAS_PHONE_NUMBER + " =?", // This is selection string, were looking for records that HAS_PHONE_NUMER is 1
new String[]{"1"}, // 1 means that contact has a phone number
ContactsContract.Contacts._COUNT,
new String[] {"5"},
null);
}
Whenever I try to add new parameters in the return section, Android Studio immediately goes red saying cannot resolve constructor. Is this because the CursorLoader is not defined to receive more parameters?
I defined it earlier in my code as:
mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);
Cheers,
Shyam
To achieve a limitation of query results, please add (string concatenate) a " LIMIT 5" to your query:
...
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=? LIMIT 5" //This is selection string, were looking for records that HAS_PHONE_NUMER is 1 AND
// the result set is limited to 5 rows
new String[]{"1"},
null);
...

BaseAdapter with sections, listview - adding cursor list data

I'm new here and would be great if someone could help me with this small crisis I have been having. I have been following Jeff Sharkeys Separate List Adapter tutorial which can be found here and I got it all working appropriately to how he explains it.
My problem is I have a database, pre made one which has a table that I am trying to put the extracted data into a list view using Jeffs adapter. I need this data to be put in different sections according to the Category ID column.
The table I am currently extracting data from is the Food table, which has 6 columns, categoriID, menuID, Item, Description, price and a PK _id
My database works properly as in other activities I use a SimpleCursorAdapter to bind data to a list view. (from other tables)
I use the following method in the Database Helper class to retrieve the data I need
public List<FoodModel> getData(String catid, String menuid) {
List<FoodModel> FoodListModel = new ArrayList<FoodModel>();
Cursor cursor = myDataBase.query(FOOD_TABLE, new String [] {FOODITEM_COLUMN, FOODITEMDESCRIPTION_COLUMN,FOODPRICE_COLUMN}, "catid = ? AND menuid = ?",
new String[] { catid, menuid},null, null, null, null);
if (cursor.moveToFirst()){
do{
FoodModel FoodModel = new FoodModel();
FoodModel.setItem(cursor.getString(0));
FoodModel.setdescrription(cursor.getString(1));
FoodModel.setprice(Double.parseDouble(cursor.getString(2)));
FoodListModel.add(FoodModel);} while (cursor.moveToNext());
}
return FoodListModel;
}
the Food Model class is the standard get set class to store the cursors data.
This public method works accordingly as in my main activity (jeffs ListSample.java) I output to the log cat the required information using
Log.d("Reading: ", "Testing Cursor");
List<FoodModel> Data1 = dba.getData("1", "1");
for (FoodModel fd : Data1){
String log = "Item: "+fd.getitem()+" ,Description: " + fd.getdescription() + " ,Price: " + fd.getprice();
Log.d("Name: ", log);
This outputs a list of all the data I need to put into 1 section of the SeperateListAdapter but to the log cat
The 3 things i am trying to output to the list view are the Item, description and price.
My problem is How do I add this data to the list view under the correct section?
as oposed to manually inserting it as Jeff shows
List<Map<String,?>> security = new LinkedList<Map<String,?>>();
security.add(createItem("Remember passwords", "Save usernames and passwords for Web sites"));
security.add(createItem("Clear passwords", "Save usernames and passwords for Web sites"));
security.add(createItem("Show security warnings", "Show warning if there is a problem with a site's security"));
I didn't want to start my first experience of using this site by pasting all my classes is as this is my first time using this website, my English is not the best and it took me a while to write this I hope it is acceptable as a question, I would be really great full if someone could kindly help me or point me in the right direction.
EDIT: Will gladly post the rest of my code just didnt whant to bombard everyone with loads of information

Error on Updating Table in Sqlite

When trying to update a record for one of my records I am using this code
private void UpdateCattleRecord(UpdateCattleRecord updateRecord){
mDB.beginTransaction();
String where = "_ID=";
String[] RecordToUpdate = {Cattle._ID};
Toast.makeText(this,"Updating Animal "+ RecordToUpdate, Toast.LENGTH_LONG).show();
try {
ContentValues CattleFieldsToUpdate = new ContentValues();
CattleFieldsToUpdate.put(Cattle.CATTLE_ANIMALID,updateRecord.getCattleName());
CattleFieldsToUpdate.put(Cattle.CATTLE_TYPE, updateRecord.getCattleType());
CattleFieldsToUpdate.put(Cattle.CATTLE_LOCATION, updateRecord.getCattleLocation());
CattleFieldsToUpdate.put(Cattle.CATTLE_DOB, updateRecord.getCattleDob());
CattleFieldsToUpdate.put(Cattle.CATTLE_DAM, updateRecord.getCattleDam());
CattleFieldsToUpdate.put(Cattle.CATTLE_SEX, updateRecord.getCattleSex());
mDB.update(Cattle.CATTLE_TABLE_NAME,CattleFieldsToUpdate, where, RecordToUpdate);
mDB.setTransactionSuccessful();
} finally {
mDB.endTransaction();
}
}
My log shows
Tag Database sqlite returned: error code =1, msg = near "=": syntax error
After researching this, I think I have everything in the right place but obviously I don't,
when I look at the next error in the log it's of course in 'red' and it shows me all the correct data,
03-27 15:15:29.291: E/Database(12011): Error updating date_of_birth=March 27, 2012 animaltype=Calf sex=F location=Eastern dam=601 animal_id=601A using UPDATE cattle SET date_of_birth=?, animaltype=?, sex=?, location=?, dam=?, animal_id=? WHERE _ID=
I've obviously got a problem with the value for _ID but can't seem to locate it. Can someone please point out where my Syntax error is?
Update
The problem occurred because I was failing to pass the actual value of the record (_ID) that I wanted to update. Once I passed that as a parameter to my updaterecords function the update went as scheduled.
Thanks for the input, it helped me narrow down what I was doing wrong.
Check your database creation, your probably have a column named _id(although you refer to it by _ID, its name is _id) and not _ID:
String where = "_id= ?"; // ? represent the value from the selection arguments String array
or better:
String where = Cattle._ID + "= ?";
Edit:
In your where selection argument you put:
String[] RecordToUpdate = {Cattle._ID};
you probably want to put in there some id you get from somewhere(of the record you want to update, a long number), right now you're doing:
WHERE _ID = _ID (or _id)
and this will fail.
try:
mDB.update(Cattle.CATTLE_TABLE_NAME,CattleFieldsToUpdate, "_ID="+Cattle._ID, null);
try:
mDB.update(Cattle.CATTLE_TABLE_NAME,CattleFieldsToUpdate, "_ID="+updateRecord.getId(), null);

Match number to contact in android app

Have an android app that prints with a toast pop up, and reads out a received message with tts. I use "String origin = smsMessage[0].getOriginatingAddress();" to get the phone number of the sender.
I want to query the contacts list on the phone, so if the received number matches any contacts, it will print & read out the name of the sender instead. Otherwise, if the number is not recognised, it will default back to just printing & reading the OriginatingAddress number.
Iv'e looked at How can I query Android contact based on a phone number? - but not quite sure howto go about it.
Uri phoneUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(origin));
Cursor phonesCursor = context.getContentResolver().query(phoneUri, new String[] {PhoneLookup.DISPLAY_NAME}, null, null, null);
if(phonesCursor != null && phonesCursor.moveToFirst()) {
displayName = phonesCursor.getString(0); // this is the contact name
}//end if
Go this eventually.
That question had the answer and posted the code.
Uri phoneUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(mNumber));
Cursor phonesCursor = managedQuery(phoneUri, new String[] {PhoneLookup.DISPLAY_NAME}, null, null, null);
if(phonesCursor != null && phonesCursor.moveToFirst()) {
String displayName = phonesCursor.getString(0); // this is the contact name

Categories

Resources