#

Android Code: Lookup a Contact by the Phone Number
 
 
Diese Java Beispiel prüft in einer Java App, ob auf dem Android Smartphone eine neue Nummer schon vorhanden ist.
Wenn die Telefonnummer Nummer noch nicht in den Kontakten gespeichert wurde, dann wird ein neuer Android Kontakt erstellt und die Daten werden eingefügt.
 
 

 
Wenn keine Telefon-Nummer gefunden wird, dann wird der Kontakt hinzugefügt, ansonsten wird bei bestehender Telefonnummer kein zusätzlicher Kontakt erzeugt.

 
 
Als Video Anleitung, Tutorial

 
Der eigentliche Java Code zum prüfen auf die Telefon-Nummer habe ich eines separate Methode gelegt.
 
Die Zeile contentResolver.query(Sub-Tabelle,,WHERE,,) durchsucht die Contact-Datenbank und gibt je nach WHERE Bedingung die Suchergebnisse als eine Art Recordset zurück.
Hier ist phones ein Recordset, welches anschliessend mit .Move durchlaufen wird.

Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI , null, ContactsContract.CommonDataKinds.Phone.NUMBER + " = " + sPhoneNr , null, null);

 
Die Methode zum Suchen und Prüfen eines Android Kontakts auf Existenz wird dadurch gewährleistet,
dass die contentResolver.query nach den Phone Daten sucht mit dem Suchparameter Number=Eingabewert und im Trefferfall auf phones.movefirst() ein Ergebnis mit true oder false zurückgibt.

public String fxLookup_RawContact_byPhoneNr(String sPhoneNr) {
//----------------< fxLookup_RawContact_byPhoneNr() >----------------
//< check >
if(sPhoneNr=="") return "";
//</ check >

Uri rawContactUri = RawContacts.CONTENT_URI.buildUpon()
.appendQueryParameter(RawContacts.
ACCOUNT_NAME, null)
.appendQueryParameter(RawContacts.
ACCOUNT_TYPE, null)
.build();

ContentResolver contentResolver = getContentResolver();
Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.
CONTENT_URI , null, ContactsContract.CommonDataKinds.Phone.NUMBER + " = " + sPhoneNr , null, null);
if(phones.moveToFirst())// .getCount() > 0
{
try {
//String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String rawcontactID= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID)) ;
return rawcontactID;
}
catch (Exception e)
{
Log.d(
"Phone-Number: ",e.getMessage()) ;
}
return "";
}

return "";
//----------------</ fxLookup_RawContact_byPhoneNr() >----------------

 
 
 
MainActivity.java:
 
Kompletter Java-Code zum Download mit 3 wesentlichen Methoden:
public void btnAdd_Contact_onClick(View view) {..}
public String fxLookup_RawContact_byPhoneNr(String sPhoneNr) {..}
public void fxAdd_RawContact(String sFirstname,String sLastname,String sPhoneNr, String sEmail) {..}

package de.rue25.a2016_09_22_add_new_contactraw;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.RawContacts;
//import android.provider.ContactsContract.Contacts;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.
activity_main);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

public void btnAdd_Contact_onClick(View view) {
//----------------< btnAdd_Contact_onClick() >----------------
//----< get+init values >----
String sFirstname = String.valueOf(((EditText)findViewById(R.id.txtFirstname )).getText());;
String sLastname = String.valueOf(((EditText)findViewById(R.id.
txtLastname)).getText());
String sDisplayName = sLastname +
" " + sFirstname;

String sPhoneNr = String.valueOf(((EditText)findViewById(R.id.
txtTelephone)).getText());
String sEmail = String.valueOf(((EditText)findViewById(R.id.
txtEmail)).getText());
//----</ get+init values >----


//< Lookup >
//*match=PhoneNumber
String sContactID=fxLookup_RawContact_byPhoneNr(sPhoneNr);
//</ Lookup >

//< add >
if (sContactID =="" ){
fxAdd_RawContact(sFirstname, sLastname, sPhoneNr, sEmail);
}
//</ add >

//----------------</ btnAdd_Contact_onClick() >----------------
}


public String fxLookup_RawContact_byPhoneNr(String sPhoneNr) {
//----------------< fxLookup_RawContact_byPhoneNr() >----------------
//< check >
if(sPhoneNr=="") return "";
//</ check >

Uri rawContactUri = RawContacts.CONTENT_URI.buildUpon()
.appendQueryParameter(RawContacts.
ACCOUNT_NAME, null)
.appendQueryParameter(RawContacts.
ACCOUNT_TYPE, null)
.build();

ContentResolver contentResolver = getContentResolver();
Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.
CONTENT_URI , null, ContactsContract.CommonDataKinds.Phone.NUMBER + " = " + sPhoneNr , null, null);
if(phones.moveToFirst())// .getCount() > 0
{
try {
//String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String rawcontactID= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID)) ;
return rawcontactID;
}
catch (Exception e)
{
Log.d(
"Phone-Number: ",e.getMessage()) ;
}
return "";
}

return "";
//----------------</ fxLookup_RawContact_byPhoneNr() >----------------
}




public void fxAdd_RawContact(String sFirstname,String sLastname,String sPhoneNr, String sEmail) {
//----------------< fxAdd_RawContact() >----------------

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContact_NewID= ops.size();

//----< add new blank Contact >----
try {
ops.add(ContentProviderOperation.newInsert(RawContacts.
CONTENT_URI)
.withValue(RawContacts.
ACCOUNT_TYPE, null) //accountType=null
.withValue(RawContacts.ACCOUNT_NAME, null) //accountName=null
.build());
}
catch(Exception e)
{
Log.e(
"Add","could not find account_type null");
return;
}
//----</ add new blank Contact >----




//----< set values to new contact >----
String sDisplayName = sLastname + " " + sFirstname;
//< Person >
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.
RAW_CONTACT_ID, rawContact_NewID)// rawContact_NewID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.
DISPLAY_NAME, sDisplayName) // Name of the person
.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, sLastname)
.withValue(ContactsContract.CommonDataKinds.StructuredName.
GIVEN_NAME, sFirstname)
.build());
//</ Person >
//< Email >
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.
RAW_CONTACT_ID, rawContact_NewID)// rawContact_NewID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.
DATA, sEmail)
.build());
//</ Email >
//< Phone >
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.
RAW_CONTACT_ID, rawContact_NewID)// rawContact_NewID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.
NUMBER, sPhoneNr)
.withValue(ContactsContract.CommonDataKinds.Phone.
TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME )
.build());
//</ Phone >
//----</ set values to new contact >----

//----< check result >----
//< get result >
ContentProviderResult[] res = new ContentProviderResult[0];
try {
res = getContentResolver().applyBatch(ContactsContract.
AUTHORITY, ops);
}
catch (RemoteException e) {
//e.printStackTrace();
Log.e("getContentResolver()",e.getMessage());
}
catch (OperationApplicationException e) {
//e.printStackTrace();
//Log.getStackTraceString(e)
Log.e("getContentResolver()",e.toString());
}
catch (Exception e) {
//e.printStackTrace();
//Log.getStackTraceString(e)
Log.e("getContentResolver()",e.toString());
}
finally {
//ok.. Log.d("getContentResolver.","..finally");
}
//</ get result >

//--< check result >--
if (res != null && res[0] != null) {
//< ok >
Uri newContactUri = res[0].uri;
Log.d(
"AddContact", "URI added contact:" + newContactUri);
//</ ok >
}
else {
//< error >
// Log.e("AddContact", "Contact not added.");
//</ error >
}
//--</ check result >--
//----</ check result >----
//----------------</ fxAdd_RawContact() >----------------
}
 

 
 
 
 
Android Manifest.xml: einfügen der Zugriffs-Erlaubnis für Read_Contacts und Write Contacts

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.rue25.a2016_09_22_add_new_contactraw">



<
uses-permission android:name="android.permission.READ_CONTACTS" />
<
uses-permission android:name="android.permission.WRITE_CONTACTS" />

<
application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<
activity android:name=".MainActivity">
<
intent-filter>
<
action android:name="android.intent.action.MAIN"/>

<
category android:name="android.intent.category.LAUNCHER"/>
</
intent-filter>
</
activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
</
application>

</
manifest>
 

 
 

 
 
Activity_main.xml: zeigt alle Eingabefelder und Labelfelder plus den Add-Contact Button

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="de.rue25.a2016_09_22_add_new_contactraw.MainActivity">

<
TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add RawContact"/>

<
Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Contact"
android:id="@+id/btnAdd_Contact"
android:onClick="btnAdd_Contact_onClick"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="72dp"/>

<
EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/txtFirstname"
android:layout_marginTop="36dp"
android:layout_alignLeft="@+id/txtTelephone"
android:layout_alignStart="@+id/txtTelephone"/>

<
EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="@+id/txtTelephone"
android:layout_alignTop="@+id/lblTelephone"
android:layout_alignLeft="@+id/btnAdd_Contact"
android:layout_alignStart="@+id/btnAdd_Contact"/>

<
TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Firstname"
android:id="@+id/lblName"
android:layout_alignTop="@+id/txtFirstname"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>

<
TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Telephone"
android:id="@+id/lblTelephone"
android:layout_below="@+id/txtLastname"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="24dp"/>

<
TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Lastname"
android:id="@+id/lblLastname"
android:layout_below="@+id/txtFirstname"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="21dp"/>

<
EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/txtLastname"
android:layout_alignTop="@+id/lblLastname"
android:layout_alignLeft="@+id/txtTelephone"
android:layout_alignStart="@+id/txtTelephone"/>

<
EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/txtEmail"
android:layout_below="@+id/txtTelephone"
android:layout_alignLeft="@+id/txtTelephone"
android:layout_alignStart="@+id/txtTelephone"
android:layout_marginTop="24dp"/>

<
TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Email:"
android:id="@+id/lblEmail"
android:layout_alignTop="@+id/txtEmail"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</
RelativeLayout>
 

 
Mobile

.

0123movie.net