If I'm assigning a value to a field of a contact, such as nickname;
.withValue(Nickname.NAME, "Mr. Incredible")
it is stored in the DATA1 column according to http://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds.Nickname.html
Yet, if I add a SIP Address with SipAddress.SIP_ADDRESS() it's value is also assigned to column DATA1. How do I differentiate between these two? I'm a bit confused on how to access a contacts specific fields and I can't find an explanation in the Android Reference.
I'm specifically using
SimpleCursorAdapter(getActivity(),
R.layout.contact_list, null, new String[] {
SipAddress.DISPLAY_NAME, SipAddress.SIP_ADDRESS, Nickname.NAME},
new int[] {
R.id.text1, R.id.text2, R.id.text3}, 0);
Please try,
try {
Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data.DISPLAY_NAME},
ContactsContract.CommonDataKinds.Nickname.DATA1 + "=" + text, null, null);
cursor.moveToFirst();
String Nickname = cursor.getString(0);
}
catch (Exception e) {
}
Yes its saved in ContactsContract.DataColumns.DATA1 with the String SIP_ADDRESS. May this helps you ContactsContract.CommonDataKinds.SipAddress
Happy coding!
Related
I have been struggling for hours trying to use an array inside a while loop. The problem is that im very new to android development so i have no idea how to do this. I have seen similar questions but most/all of them does not suite for my scenario. The code below does work but im calling a new instance of articlesData for each row in the while statement, this causes it to just return the value of the last row.. Is there any way to use an array like ArticlesData[] and get all my data in it? Please help :) Here is my code:
public ArticlesData[] getArticleData(int no) {
Log.e("DB STAT", "getArticleData Called");
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = { ArticlesHelper.ID, ArticlesHelper.TITLE, ArticlesHelper.IMAGEURL };
Cursor cursor = db.query(ArticlesHelper.TABLE_NAME,
columns,
ArticlesHelper.DATENUMBER+" < '"+Integer.toString(no)+"'", null, null, null, ArticlesHelper.DATENUMBER+" DESC", "20");
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
Log.e("DB STAT", "Article Id = "+Integer.toString(id));
String title = cursor.getString(1);
Log.e("DB STAT", "Article Title = "+title);
String url = cursor.getString(2);
articlesData = new ArticlesData[] {
new ArticlesData(title, Integer.toString(id), url)
};
}
return articlesData;
}
You most probably want to use a Collection such as List:
public List<ArticlesData> getArticleData(int no) {
Log.e("DB STAT", "getArticleData Called");
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = { ArticlesHelper.ID, ArticlesHelper.TITLE, ArticlesHelper.IMAGEURL };
Cursor cursor = db.query(ArticlesHelper.TABLE_NAME,
columns,
ArticlesHelper.DATENUMBER+" < '"+Integer.toString(no)+"'", null, null, null, ArticlesHelper.DATENUMBER+" DESC", "20");
List<ArticlesData> list = new ArrayList<ArticlesData>();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
Log.e("DB STAT", "Article Id = "+Integer.toString(id));
String title = cursor.getString(1);
Log.e("DB STAT", "Article Title = "+title);
String url = cursor.getString(2);
list.add(new ArticlesData(title, Integer.toString(id), url));
}
return list;
}
You should not try to use a raw array here because it has a fixed size. You could use it if you limited the number of rows in the query so you'd know exactly how much elements you need, but even then it would still be much easier to just use a Collection elsewhere in the code.
As you seem new to Android development and Java I suggest you first get acquainted with the basic data structures such as Maps, Lists, and Sets, and then later you might want to use an ORM to save you the pain of writing boilerplate code for interacting with a database.
I'm new to android and i'm working with native contact.
So my app is let user put contact display name and their number for edit/delete.
In case the contact have more that one number.
I tried a lot but still have no luck, the app still doesn't update the number or it crashes.
What I'm going to do as my understanding is:
Find name in contact that matched name user inserted and use that to get contact_id that represent this contact datagroup.
Use contact_id in 1. and the number user input to find ._ID that represent the specific row id.
Do task with ._ID we get from 2.
This is 1. code to get contact_id:
public String getPeopleUniqueID(String name, Context context) {
String s = null;
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
String[] projection = new String[] {ContactsContract.Data.CONTACT_ID};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, null);
if(c.moveToFirst()) {
s = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
}
c.close();
return s;
}
This is 2. code to get ._ID (num is number user inserted and name is from 1. > the contact_id)
public String checkPhoneNumber(String num, String name, Context context) {
String s = null;
String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + "=?" + " AND "+ContactsContract.Data.CONTACT_ID+ "=?";
String[] projection = new String[] {ContactsContract.Data._ID};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, new String[]{u,name}, null);
if(c.moveToFirst()) {
s=c.getString(c.getColumnIndex(ContactsContract.Data._ID));
}
c.close();
if (s==null){
s = "null";
}
return s;
}
To do something like editing (num is _.ID we get from 2. and newnum is new number user want to change into).
public void editNumber(String num , String newnum) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(Data._ID + "=? AND " +
Data.MIMETYPE + "='" +
CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
new String[]{num})
.withValue(Data.DATA1, newnum)
.build());
try{
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);}
catch (RemoteException e){e.printStackTrace();}catch (OperationApplicationException e) {e.printStackTrace();}
}
And well it crashes when I call editNumber().
Can you help me fix my code and my understanding?
And another question, can I edit/insert group for the contact programatically, like I want to add this contact to family friend or co-worker group (the default group that we can set at contact edit page)?
Use ContactsContract.Contacts.CONTENT_FILTER_URI for searching a contact based on name - to get Id or anything else. The like operator cannot handle all cases which the CONTENT_FILTER_URI does handle - For various languages, special characters etc.
http://developer.android.com/reference/android/provider/ContactsContract.Contacts.html#CONTENT_FILTER_URI
Use following uri to lookup a contact from phone number - you can get person id or anything else :
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
In the set query you can also use contactId in the condition
For groups you can use custom mimetypes if the default one does not suit you (which is still very primitive for groups across different account types)
In my application I am saving a bill number in SQLite database. Before I add a new bill number how to check if the bill number exists in the DB.
My main class code is,
String bill_no_excist_or_not = db.billno_exist_or_not(""+et_bill_number.getText().toString());
Log.v("Bill No", ""+bill_no_excist_or_not);
My DB Code,
String billno_exist_or_not(String bill_number){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_BILL_DETAILS, new String[] { KEY_BILL_NUMBER }, KEY_BILL_NUMBER + "=?"
+ new String[] { bill_number }, null, null, null, null);
//after this i don't know how to return the values
return bill_number;
}
I don't know how to check the values which is already available or not in DB. Can any one know please help me to solve this problem.
Here is the function that helps you to find whether the value is available in database or not.
Here please replace your query with my query..
public int isUserAvailable(int userId)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select user_id from user_table where user_id = ?", new String[] {String.valueOf(userId)});
if(c.getCount() != 0)
number = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}
Make your KEY_BILL_NUMBER column in your table UNIQUE and you can just insert using insertWithOnConflict with the flag SQLiteDatabase.CONFLICT_IGNORE
I wanted to do query in table for field id with some vales like 1,5,4,11 which will come from previous screen according to selection.
cursor = database.query(tablename,
new String[] { "TopName" }, "id =?", new String[]{"2,3"}, null, null, null);
When I do like this, I am getting cursor count 0, with new String[]{"2"} I am getting value I want for all ids with values in string array like OR which have value in that column.
You can use the IN operator like this,
cursor = database.query(tablename, new String[] {"TopName"}, "id IN(?,?)",
new String[]{"2","3"}, null, null, null);
The correct syntax for using the IN operator in Android's ContentProvider is as follows:
cursor = database.query(contentUri, projection, "columname IN(?,?)", new String[]{"value1" , "value2"}, sortOrder);
Alternatively, we can also use,
cursor = database.query(contentUri, projection, "columnName IN(?)", new String[] {" 'value1' , 'value2' "}, sortOrder);
Note that we need single quotes around each comma-separated value in the arguments for second case, otherwise the whole string will be treated as one value for the column. The SQL will treat it as
SELECT * FROM table WHERE columnName IN ('value1,value2')
instead of the correct syntax
SELECT * FROM table WHERE columnName IN ('value1' , 'value2')
VolkerK was first to correctly answer the question, but for the sake of completeness here is a full example of how to use the IN operator:
cursor = database.query(tablename,
new String[] { "TopName" }, "id IN (?)", new String[]{"2,3"}, null, null, null);
Use the IN operator instead of equality comparison (=).
For the SelectionArgs section I think you need to change:
new String[]{"2,3"}
To
new String[]{"2","3"}
I would like to put this here since a compendium of answers helped me putting multiple (unknown) values in SQLiteDatabase.query() and the one-question-mark did not work for me. Hope helps anyone
// API > 24
protected String attributesAsMarks(String[] attributes) {
List<String> marks = Collections.nCopies(attributes.length, "?");
return marks.stream().collect(Collectors.joining(","));
}
// I'm using API > 15
protected String attributesAsMarks(String[] attributes) {
StringBuilder sb = new StringBuilder();
String separator = "";
for (String s : attributes) {
if (s == null) continue;
sb.append(separator).append("?");
separator = ",";
}
return sb.toString();
}
Thanks to
#Lalit
https://stackoverflow.com/a/5600690/1358777
https://stackoverflow.com/a/38546936/1358777
https://stackoverflow.com/a/524089/1358777
In my application, I come up with a thing where I have to add a contact to the favorite list. I used this code to update the starred column of the contact table but all in vain. As far as I think, I am passing null to content values in my query, but I'm unable to figure out the possible correction.
try{
ContentResolver cr = getContentResolver();
String[] projection={ContactsContract.Contacts.STARRED};
Cursor cur = cr.query(CallLog.Calls.CONTENT_URI,projection, null, null, null);
cur.moveToPosition(Integer.parseInt(idholder)); //idholder holds unique row id
cr.update(ContactsContract.Contacts.CONTENT_URI, null, Contacts.STARRED+"="+1, null);
}
catch(SQLiteException sqle){
sqle.printStackTrace();
}
In ContactsContract.ContactOptionsColumns you have a column called STARRED, which is boolean. So all you have to do is update the selected contact
I know its too late to give the answer. But if anyone finding the answer can use this.
private int updateContact(int val,String lookupKey) {
// val = 0/1
// you can also use _ID instead of lookupKey
try {
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(ContactsContract.Contacts.STARRED, val);
return cr.update(ContactsContract.Contacts.CONTENT_URI, values,
ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY+ " = ?",
new String[] {lookupKey});
} catch (Exception e) {
Log.e("TAG", e.toString());
}
return 0;
}