Contact Details Returned Twice - java

I am trying fetch contact details such as Name, phone number, email and photo. attached to a contact in an arraylist.
But for a contact having both phone number and email address. I can see the same contact name twice at first with its email address & then with its phone number and is not shown as a single contact (which it should be).
Can anyone please help me out with this?
TIA :)
Ref.:
public ArrayList<User> getPhoneContact(String paramString, ArrayList<User> paramArrayList)
throws CustomException
{
//Cursor localCursor = null;
Cursor cursor = null;
ArrayList localArrayList = new ArrayList();
User user;
boolean flag;
String s1;
String s2;
String s6;
String s5;
String s3;
String s4;
int i;
int j;
int k;
int l;
int i1;
try
{
cursor = getNamesAndPictures(paramArrayList);
if(cursor != null && cursor.moveToFirst()){
user = null;
i = cursor.getColumnIndex("data1");
j = cursor.getColumnIndex("contact_id");
k = cursor.getColumnIndex("display_name");
l = cursor.getColumnIndex("data1");
i1 = cursor.getColumnIndex("mimetype");
s1 = null;
do{
s2 = cursor.getString(j);
if(s2 == null)
return localArrayList;
//if(s2.equals(s1))
//return localArrayList;
user = new User();
s1 = s2;
s3 = cursor.getString(k);
user.setName(s3);
user.setContactId(s2);
user.setContactType(paramString);
s4 = cursor.getString(i1);
if(s4 != null){
if(s4.equals("vnd.android.cursor.item/phone_v2")){
s6 = cursor.getString(i);
user.setPhone(s6);
}
else if(s4.equals("vnd.android.cursor.item/email_v2")){
s5 = cursor.getString(l);
user.setEmail(s5);
}
}
localArrayList.add(user);
}while(cursor.moveToNext());
}
}
catch (Exception localException)
{
//localException
}
finally
{
//closeCursor(localCursor);
closeCursor(cursor);
closeDatabase();
}
return localArrayList;
}
And:
private Cursor getNamesAndPictures(ArrayList<User> paramArrayList)
{
String str1 = prepareContactIdsString(paramArrayList);
ContentResolver localContentResolver = this.getAppContext().getContentResolver();
String[] arrayOfString = { "data1", "contact_id", "display_name", "_id", "data1", "mimetype" };
String str2 = "display_name != 'null' AND ( (mimetype = 'vnd.android.cursor.item/phone_v2' AND is_primary != -1 ) OR (mimetype = 'vnd.android.cursor.item/email_v2' AND is_primary != -1 ) ) AND contact_id NOT IN ( " + str1 + ")";
return localContentResolver.query(android.provider.ContactsContract.Data.CONTENT_URI, arrayOfString, str2, null, "display_name COLLATE LOCALIZED ASC");
}

this is because you query the Data table which holds data rows , each row foe some kind of information about the contact, for example one row for email and one row for phone number.
if you want to get only the contacts you should query ContactsContract.Contacts table but then you will have to query for each of them the email and phone.
http://developer.android.com/guide/topics/providers/contacts-provider.html

Related

How getSet of Text from row in cassandra

I have a table with < frozen < set < text > > > , column. I can't understand how I may read a column value from a row.Trying below but not able to get pass through.
else if (key.getType() == DataType.frozenSet(text))
{
str = row.getSet( , )
}
I tried the below , but i see nothing is printing out from that frozen set column.
public static void main(String[] args) throws FileNotFoundException {
long startTime = System.currentTimeMillis();
PrintWriter pw = new PrintWriter(new File("test.csv"));
String keyspace = "xxxxx";
String table = "xxxxxx";
String username = "xxxx";
String password = "xxxx";
String host = "xxxxxxx";
double count = 0;
Cluster.Builder clusterBuilder = Cluster.builder()
.addContactPoints(host)
.withCredentials(username, password);
Cluster cluster = clusterBuilder.build();
Session session = cluster.connect(keyspace);
Statement stmt = new SimpleStatement("SELECT * FROM " + table);
stmt.setFetchSize(2000);
ResultSet rs = session.execute(stmt);
Iterator<Row> iter = rs.iterator();
while ( !rs.isFullyFetched()) {
if (rs.getAvailableWithoutFetching() == 120 )
rs.fetchMoreResults();
Row row = iter.next();
if ( rs != null )
{
StringBuilder line = new StringBuilder();
for (Definition key : row.getColumnDefinitions().asList())
{
String val = myGetValue(key, row);
line.append("\"");
line.append(val);
line.append("\"");
line.append(',');
}
line.deleteCharAt(line.length()-1);
line.append('\n');
pw.write(line.toString());
System.out.println(line.toString());
++count;
}
}
pw.close();
session.close();
cluster.close();
System.out.println(count + "\t rows copied into csv");
long endTime = System.currentTimeMillis();
System.out.println("Took "+(endTime - startTime) + " ms");
}
public static String myGetValue(Definition key, Row row)
{
String str = "";
if (key != null)
{
String col = key.getName();
try
{
if (key.getType() == DataType.cdouble())
{
str = new Double(row.getDouble(col)).toString();
}
else if (key.getType() == DataType.cint())
{
str = new Integer(row.getInt(col)).toString();
}
else if (key.getType() == DataType.uuid())
{
str = row.getUUID(col).toString();
}
else if (key.getType() == DataType.cfloat())
{
str = new Float(row.getFloat(col)).toString();
}
else if (key.getType() == DataType.timestamp())
{
str = row.getDate(col).toString();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
str = fmt.format(row.getDate(col));
}
else if (key.getType().equals(DataType.set(DataType.text()) ))
{
Set<String> st1 = row.getSet(i, String.class);
str = st1.toString();
++i;
}
else
{
str = row.getString(col);
}
} catch (Exception e)
{
str = "";
}
}
return str;
}
}
schema:
create table view_page_details(
clickid uuid,
view text,
clickin int,
names frozen <set<text>>,
msg_view text,
number_of_times int,
primary key ((clickid, view, clickin), names);
cqlsh output for that specific 'names' column in that table:
| {').'{'2', 'STOP', 'williams', 'The', 'appts:', 'at', 'family''s', 'first', 'of', 'one', 'reminder', 'starts', 'to', 'your'}
| {'2'{'2', 'STOP', 'shane', 'The', 'appts:', 'at', 'family''s', 'first', 'of'}
| {'1', '2/1/15.'{'2', 'STOP', 'brete', 'The', 'appts:', 'at', 'family''s', 'first', 'of', 'one', 'reminder', 'starts', 'to', 'your'}
My program output for that specific 'names'column in that table:
,,
,,
,,
,,
From what i observed by debugging line by line , String val = myGetValue(key, row); gets the entire row value correctly from cluster, when returns value from that function its not giving out the specified column value. Not sure if something wrong inside the function logic for that specific column.
The first argument is index of the column in the ResultSet.
By accessing this way you need to get get columns by their index not by name or key.
Set<String> mySet = row.getSet(index, String.class);
If you don't have the index, then you will need keep a counter as you iterate the keys.
You can find out more from the javadoc
https://docs.datastax.com/en/latest-java-driver-api/com/datastax/driver/core/GettableByIndexData.html#getSet-int-java.lang.Class-
longer answer:
I'm really guessing what most of your code does, but with the given schema I can output the set using this code:
Row row = rs.one();
String str = "";
int i = 0;
Iterator<ColumnDefinitions.Definition> it = rs.getColumnDefinitions().iterator();
while (it.hasNext()) {
ColumnDefinitions.Definition key = it.next();
if (key.getType().equals(DataType.set(DataType.varchar()))) {
Set<String> st1 = row.getSet(i, String.class);
str = st1.toString();
System.out.println(str);
}
i++;
}

Getting duplicates in Arraylist which should have contacts

Im trying to save the users contacts in an ArrayList <Contacts> but somehow I got duplicates in it. I found out that I should use
ContractsContact.Contacts.CONTENT_URI
and not
ContractsContact.DATA.CONTENT_URI
But its not helping me. I still got dublicates in my ArrayList. Here is my code :
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
if (phoneNumber.charAt(0) == '0' && phoneNumber.charAt(1) == '0')
{
String temp = "+";
for(int j=2;j<phoneNumber.length();++j)
temp += phoneNumber.charAt(j);
phoneNumber = temp;
}
if (!phoneNumber.contains("+"))
{
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber normalized_number = null;
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String current_iso_code = telephonyManager.getSimCountryIso();
current_iso_code = current_iso_code.toUpperCase();
try {
normalized_number = phoneUtil.parse(phoneNumber,current_iso_code);
}catch(Exception e){
e.printStackTrace();
}
String str_normalized_number = phoneUtil.format(normalized_number, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
str_normalized_number = str_normalized_number.replaceAll(" ","");
str_normalized_number = str_normalized_number.replaceAll("\\(","");
str_normalized_number = str_normalized_number.replaceAll("\\)","");
contacts.add(new Contact (name,str_normalized_number,current_iso_code,contact_id));
}
else {
phoneNumber = phoneNumber.replaceAll(" ","");
phoneNumber = phoneNumber.replaceAll("\\(","");
phoneNumber = phoneNumber.replaceAll("\\)","");
phoneNumber = phoneNumber.replaceAll("-","");
String iso_code = null;
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
Phonenumber.PhoneNumber numberProto = phoneUtil.parse(phoneNumber, "");
iso_code = phoneUtil.getRegionCodeForNumber(numberProto);
}catch(Exception e){}
contacts.add(new Contact (name,phoneNumber,iso_code,contact_id));
}
}
phoneCursor.close();
}
}
Is there a wrong part in my code which I'm not seeing ?
I think Hash set Concept in Java may help to solve this problem as it removes duplicate items.I hope it will address the problem
The following link may help in this regard.
Removing Duplicate Values from ArrayList

Get User's Google Account Profile Picture

I have so far looked at many questions where this is the topic, not a single answer has worked for me so far. In my code I get the user's google account and their contact info. I can successfully look at their email and display name fine. When I grab their id number and use it how http://developer.android.com/reference/android/provider/ContactsContract.Contacts.Photo.html would have me use it, the InputStream comes up null. When I debug through the following method the program never loads the blob into data, it immediately skips down to finally.
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] {ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
Does this mean the selected contact does not have a profile image??? I no this to not be the case as it is accessing my personal gmail account and giving me the other data correctly. I get this id with the following code (along with email and display name). I get the email with googleAccount.name
AccountManager accountManager;
accountManager = AccountManager.get(context);
Account[] account = accountManager.getAccounts();
Account googleAccount = null;
for(int i = 0; i < account.length; i++) {
if(account[i].type.equals("com.google")) {
googleAccount = account[i];
}
}
Cursor c = context.getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
int count = c.getCount();
c.moveToFirst();
String id = "";
String displayName = "";
String[] columnNames = c.getColumnNames();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
String columnName = columnNames[j];
String columnValue = c.getString(c.getColumnIndex(columnName));
if(columnName.equals("_id"))
id = columnValue;
if(columnName.equals("display_name"))
displayName = columnValue;
// consume the values here
}
}
c.close();
Why is this inputstream coming up null? I got the code directly from google. Has anyone had this problem with this code before?

how to fetch data from 2 sqlite tables and insert it into 3rd table in android? i am new to android...i have tried bt it does not work?

table 1 is MsgTable, 2nd is ContactTable & the third 1 is KeyTable...
i have to select data from first 2 tables & insert it into 3rd table??
public void setKeyValues(String msg_id, String contact_id )//insert intokeytable(msgid - contact)
{
db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("Msg_Id", msg_id);
values.put("Contact_Id", contact_id);
i = db.insert("KeyTable", null, values);//contact
if(i != 0)
{
}
}
public ArrayList<String> getValues()
{
ArrayList<String> arr = null;
try
{
db = getReadableDatabase();
arr = new ArrayList<String>();
Cursor c1= null;
Cursor c2 = null;
c1 = db.rawQuery("select Msg_id from KeyTable where Contact_id = 1", null);
while(c1.moveToNext())
{
String msg = c1.getString(c1.getColumnIndex("MSG"));
String str = msg ;
arr.add(str);
Log.d("fuuast",str);
}
c2 = db.rawQuery("select Contact_id from KeyTable where Msg_id = 1", null);
while(c2.moveToNext())
{
String contact = c2.getString(c2.getColumnIndex("Contact"));
String str = contact ;
arr.add(str);
Log.d("fuuast",str);
}
}catch(Exception ex)
{
ex.printStackTrace();
}
return arr;
}
}

fetch all android contacts and details and put in single multidimensional array

Am new to android(Java) and i want to perform a simple task
how can i Fetch all the contacts phone numbers, email, and fullname on the device and their details and put
them in a single array as such
I am from a PHP BACKGROUND SO THE ARRAY WOULD LOOK LIKE THIS IN PHP :
ContactsArray[0] = array(
'fullname' => 'John doe',
'Phone' => '0909809890' ,
'email' => 'johndoe#email.com'
)
Thats what the array should look like from a PHP perspective,
Am new to android and would like a class to fetch all this data
put them in a single array
return the data.
PSEUDO CODE
function GetContacts(){
contacts = fetchAllContactsDetails
return contacts;
}
This could be a start. Please note that I haven't tested this out and there could be errors but you'll get the idea.
Read this for more info on multi dimensional array. Link
String phpArray;
int x=3;
int y=array.length();
String[][] myStringArray = new String [y][x];
for(int i=0; i<array.length; i++){
for(int j=0; j<3; j++){
phpArray = contactsArray[i];
myStringARray[i][j] = phpArray[j];
}
}
First you need add the permission to read the contacts in your manifest file:
<uses-permission android:name="android.permission.READ_CONTACTS" >
</uses-permission>
And you can check this code:
public void fetchContacts() {
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID+ " = ?", new String[] { contact_id }, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\nEmail:" + email);
}
emailCursor.close();
}
output.append("\n");
}
outputText.setText(output);
}
}
}

Categories

Resources