How to add all phone contacts in Sqlite database? - android

In my Android app,i am retreiving phone contacts through cursor. Then i want to add all these contacts in database as follows:
public class SettingsActivity extends Activity {
ToggleButton tb_hide;
ToggleButton tb_unhide;
TextView tv_add_contacts;
TextView tv_restore_contacts;
DbManager manager;
Context context;
String[] privateContacts;
Uri queryUri;
String selectIds = "";
String ContactId[];
String ContactNames[];
String ContactNumbers[];
public static String[] wholContactData;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
try{
context = this;
findView();
queryUri = ContactsContract.Contacts.CONTENT_URI;
//String selected_data = ContactsContract.Contacts.DISPLAY_NAME + " IS NOT NULL";
Cursor Cursor = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
privateContacts=showEvents(Cursor);
wholContactData=new String[privateContacts.length];
tv_add_contacts.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
addcontacts();
}
});
tv_restore_contacts.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
for(int i=0;i<privateContacts.length;i++){
selectIds = selectIds + " | " + privateContacts[i];
wholContactData[i]=privateContacts[i];
}
try{
addAllContacts(wholContactData);
}
catch(Exception ex)
{
Log.e("ERROR in adding all contacts", ex.toString());
}
Toast.makeText(getApplicationContext(),""+selectIds, 3000).show();
}});
}
catch(Exception ex){
Log.e("Add all contacts ERROR", ex.toString());
}
}
private void addAllContacts(final String[] selectedItems) {
try{
manager.open();
manager.Insert_phone_contact(selectedItems);
manager.close();
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
}
protected String[] showEvents(Cursor cursor) {
ContactId= new String[cursor.getCount()];
ContactNames = new String[cursor.getCount()];
ContactNumbers = new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
ContactId[i] = i+"";
ContactNames[i] = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
ContactNumbers[i] = Util.getContactNumber(ContactNames[i], context);
i++;
}
return ContactNames;
}
private void findView() {
TextView tv_hide = (TextView)findViewById(R.id.tv_hide);
TextView tv_hide_desc = (TextView)findViewById(R.id.tv_hide_desc);
tv_add_contacts = (TextView)findViewById(R.id.tv_add_contacts);
TextView tv_add_contacts_desc = (TextView)findViewById(R.id.tv_add_contacts_desc);
tv_restore_contacts = (TextView)findViewById(R.id.Tv_restore_contacts);
TextView tv_restore_contacts_desc = (TextView)findViewById(R.id.tv_restore_contacts_desc);
tb_hide = (ToggleButton)findViewById(R.id.tb_hide);
tb_hide.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
HideUnhideIcon();
}});
}
private void HideUnhideIcon() {
if(tb_hide.isChecked()){
PackageManager pm = getPackageManager();
ComponentName com_name = new ComponentName("com.android.discrete.main",
"com.android.discrete.main.SplashScreen");
pm.setComponentEnabledSetting(com_name,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(getApplicationContext(), "Your app is hidden now, Dial provided security code to get into discrete app.", 3000).show();
}
else if(tb_hide.isChecked()==false){
PackageManager pm = getPackageManager();
ComponentName com_name = new ComponentName("com.android.discrete.main",
"com.android.discrete.main.SplashScreen");
pm.setComponentEnabledSetting(com_name,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
,
PackageManager.DONT_KILL_APP );
}
}
private void addcontacts() {
final ProgressDialog myPd_ring=ProgressDialog.show(this, "Phone Contacts", "Loading please wait..", true);
myPd_ring.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try
{
movetoPrivateContacts();
}catch(Exception e){}
myPd_ring.dismiss();
}
}).start();
}
private void moveToLogActivity() {
Intent i = new Intent(this, LogActivity.class);
startActivity(i);
finish();
}
private void movetoPrivateContacts() {
Intent intent = new Intent(this,privateContacts.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
}
Database code is as follows:
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for(int i=0;i<contact.length;i++){
// put all values in ContentValues
if (contact[i] !=null){
cv.put(CONTACT_NAME, ""+contact[i]);
DB.insert(TABLE_CONTACTS, null, cv);
}// insert in db
}
DB.close(); // call close
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
}
i want to add all contacts to database when i click "tv_restore_contacts" .But i am getting NullPointerException. I don't know where i am wrong?
logcat Error stack is java.lang.NullPointerException.

Use the following code to grab the contacts & return them to a list datatype to save them whole list in a db or open a DB connection inside the method and do sql insert statements on each contact object you wish to store. N/B The Contacts API is deprecated be sure to use ContactsContract Api.
Private void getDetails(){
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
Log.e("Name new:", name);
String number = names.getString(indexNumber);
Log.e("Number new:","::"+number);
} while (names.moveToNext());
}

Related

Retrofit asynchrone tash

Here is my code:
private void InitialContact(final Context context)
{
final ContactDatabase db = new ContactDatabase(context);
context.openOrCreateDatabase("****", MODE_PRIVATE, null);
if(refrech){
refrech(db, context);
}
getcontact(db, context);
db.close();
}
A getContact fonction (In main thread)
private void getcontact(final ContactDatabase db, final Context context){
SQLiteDatabase dbread = db.getReadableDatabase();
String[] retour = {
"pseudo",
"adresse",
"image", "ID"
};
Cursor cursor = dbread.query("Contact", retour, null, null, null, null, "pseudo");
while(cursor.moveToNext()) {
String pseudo = cursor.getString(cursor.getColumnIndexOrThrow("pseudo"));
Log.d("debug", "getcontact: "+pseudo);
listcontact.add(new Contact(pseudo));
}
cursor.close();
}
And the Asynchrone task refresh
private void refrech(final ContactDatabase db, final Context context){
final SQLiteDatabase dbwrite = db.getWritableDatabase();
db.onRefresh(dbwrite);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
int ID = preferences.getInt("ID", 0);
if(ID != 0){
ApiInterface mApiService = this.getInterfaceService();
Call<ContactCall> mService = mApiService.getcontact(ID);
mService.enqueue(new Callback<ContactCall>() {
#Override
public void onResponse(Call<ContactCall> call, Response<ContactCall> response) {
ContactCall ContactCallobjet = response.body();
ArrayList pseudo = ContactCallobjet.isLogin;
for(int i = 0 ;pseudo.size() <= i; i++){
ContentValues values = new ContentValues();
String contact = (String) pseudo.get(i);
values.put("pseudo", contact);
values.put("adresse", "test");
values.put("image", "test");
values.put("ID", "5");
dbwrite.insert("Contact", null, values);
}
}
#Override
public void onFailure(Call<ContactCall> call, Throwable t) {
Log.d("DEBUG", "populateWithInitialContacts: "+t.getMessage());
}
});
} else {
Log.d("DEBUG", "populateWithInitialContacts: Error ID");
}
}
My probleme is a getContact fonction is call before a asynchrone function (refrech)
I have test a CallBack but It did not work
Have your getContact method be called in your onResponse and failure callbacks:
private void InitialContact(final Context context) {
final ContactDatabase db = new ContactDatabase(context );
context.openOrCreateDatabase("****", MODE_PRIVATE, null);
if(refrech){
refrech(db, context);
} else {
getcontact(db, context);
}
db.close();
}
private void refrech(final ContactDatabase db, final Context context){
final SQLiteDatabase dbwrite = db.getWritableDatabase();
db.onRefresh(dbwrite);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
int ID = preferences.getInt("ID", 0);
if(ID != 0){
ApiInterface mApiService = this.getInterfaceService();
Call<ContactCall> mService = mApiService.getcontact(ID);
mService.enqueue(new Callback<ContactCall>() {
#Override
public void onResponse(Call<ContactCall> call, Response<ContactCall> response) {
ContactCall ContactCallobjet = response.body();
ArrayList pseudo = ContactCallobjet.isLogin;
for(int i = 0 ;pseudo.size() <= i; i++){
ContentValues values = new ContentValues();
String contact = (String) pseudo.get(i);
values.put("pseudo", contact);
values.put("adresse", "test");
values.put("image", "test");
values.put("ID", "5");
dbwrite.insert("Contact", null, values);
// call get contacts after the response
getcontact(db, context);
}
}
#Override
public void onFailure(Call<ContactCall> call, Throwable t) {
Log.d("DEBUG", "populateWithInitialContacts: "+t.getMessage());
// call get contacts on error
getcontact(db, context);
}
});
} else {
Log.d("DEBUG", "populateWithInitialContacts: Error ID");
// call get contacts on error id
getcontact(db, context);
}
}

inserting and view sqlite database error

I have a broadcastreceiver to detect incoming sms and I'm storing the sms's in sqlite database. Then I'm trying to view the database content using query. The code was working perfectly when I wasn't using "id INTEGER PRIMARY KEY AUTOINCREMENT". After adding "id", when I try to view database content, its showing "No records found". So either its not entering values properly or there is error in view query code. I searched in other posts but not able find the error. Any help in this would be really helpful.
Broadcastreceiver:
public class MyBroadcast extends BroadcastReceiver{
Context mContext;
String msg_body;
String mob_no, name;
String dttm, key;
SQLiteDatabase db;
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
db=context.openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
StringBuffer content = new StringBuffer();
if (messages.length > 0) {
for (int i = 0; i < messages.length; i++) {
content.append(messages[i].getMessageBody());
mob_no = messages[i].getOriginatingAddress();
Calendar calendar = Calendar.getInstance();
Date finaldate = calendar.getTime();
dttm = finaldate.toString();
}
}
msg_body = content.toString();
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(mob_no));
Cursor c = context.getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME},null,null,null);
try {
if(c.moveToFirst()){
name = c.getString(0);
db.execSQL("INSERT INTO student (sender, timestamp, mesg) VALUES('"+name+"','"+dttm+"','"+msg_body+"');");
}else{
db.execSQL("INSERT INTO student (sender,timestamp,mesg) VALUES('"+mob_no+"','"+dttm+"','"+msg_body+"');");
}
} catch (Exception e) {
// TODO: handle exception
}finally{
c.close();
}
}
}
}
MainActivity:
public class MainActivity extends Activity {
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, timestamp TEXT, mesg TEXT);");
} //oncreate
public void ViewAll(View v){
try{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Sender: "+c.getString(1)+"\n");
buffer.append("TimeStamp: "+c.getString(2)+"\n");
buffer.append("Mesg: "+c.getString(3)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
public void Delete(View v){
Cursor c=db.rawQuery("SELECT * FROM student WHERE id=(SELECT MIN(id) FROM student)", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE id=(SELECT MIN(id) FROM student)");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Entry");
}
}
private void showMessage(String title, String message) {
// TODO Auto-generated method stub
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
} //activty

display data from sqlite

i have a problem in showing data coming from database sqlite, i looked for a solution
here i did found plenty but i couldn't make it work, the error i get is : Error occured:
java.lang.IllegalArgumentException: column '_id' does not exist !!
my code is :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
private ArrayList<String> arr;
SimpleCursorAdapter adapter = null;
Cursor c;
DBAdapter db = new DBAdapter(this);
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.open();
Button suivant = (Button)findViewById(R.id.com_quest);
suivant.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent l = new Intent(MainActivity.this,ActivityUn.class);
startActivity(l);
}
});
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
Log.i("MyApp", "Total users: " + cursor.getCount());
Toast.makeText(getApplicationContext(),
"Number of rows: " + cursor.getCount(), Toast.LENGTH_LONG)
.show();
String[] databaseColumnNames = new String[] { DBAdapter._id };
int[] toViewIDs = new int[] { R.id.text };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,R.layout.activity_main, cursor, databaseColumnNames, toViewIDs,FLAG_REGISTER_CONTENT_OBSERVER);
ListView list = (ListView) findViewById(android.R.id.list);
list.setAdapter(myCursordapter);
} }
and in dbadapter is :
private static final String MENAGE = "table_MENAGE";
public static final String _id = "Num_du_Questionnaire";
public Cursor getAllRecords() {
return db.query(MENAGE, new String[] { _id
}, null, null, null,
null, null);
}
All CursorAdapters require that the Cursor includes a column called _id. Your Cursor contains just one column called Num_du_Questionnaire.

Android Sqlite display random row

I'm currently developing an app. What it does, the user would input some sentences and then the app will get the ambiguous word and then display it meaning. In my table I have fields like _id, word, meaning, definition_number.
Sample data:
_id word meaning definition_number
1 Break to pause from something 1
2 Break to cut into pieces 2
If the user would input: My break was very fast.
The intended output would be:
Ambiguous word: Break
Meaning: To pause from something
I want to display the it randomly. This is a snippet of code from my DBHelper.class:
public Cursor getAllWords()
{
Cursor localCursor =
//this.myDataBase.query(DB_TABLE, new String[] {
// KEY_ID, KEY_WORD, KEY_MEANING }, null, null, null, null, null);//"RANDOM()");
//this.myDataBase.query(DB_TABLE, new String[] {
// KEY_ID, KEY_WORD, KEY_MEANING }, null, null, null, null, "RANDOM()", " 1");
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_WORD, KEY_MEANING },
null, null, null, null, "RANDOM()");
if (localCursor != null){
localCursor.moveToFirst();
}
return localCursor;
}
MainActivity.class:
ArrayList<String> colWords = new ArrayList<String>();
ArrayList<String> colMeanings = new ArrayList<String>();
String[] words;
String[] meanings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControls();
}
private void initControls() {
// TODO Auto-generated method stub
text = (EditText) findViewById (R.id.editText1);
view = (TextView) findViewById (R.id.textView1);
clear = (Button) findViewById (R.id.button2);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
text.setText("");
view.setText("");
}
});
connectDB();
ok = (Button) findViewById (R.id.button1);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Log.d(strWord, strWord);
strWord = text.getText().toString();
if(strWord.isEmpty()){
Toast.makeText(MainActivity.this, "Please input some data", Toast.LENGTH_SHORT).show();
} else {
checkAmbiguousWord();
}
}
});
}
private void connectDB(){
dbHelper = new DBHelper(MainActivity.this);
try {
dbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
cursor = dbHelper.getAllWords();
/*strWord = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_WORD))
+ cursor.getString(cursor.getColumnIndex(DBHelper.KEY_MEANING)); */
colWords.clear();///added code
colMeanings.clear();///added code
/*
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
colWords.add(cursor.getString(1));
colMeanings.add(cursor.getString(2));
String records = cursor.getString(0);
Log.d("Records", records);
} */
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
colWords.add(cursor.getString(1));
colMeanings.add(cursor.getString(2));
String records = cursor.getString(0);
Log.d("Records", records);
} while (cursor.moveToNext());
}
}
}
private void checkAmbiguousWord(){
final String textToCheck = text.getText().toString();
List<Integer> ambiguousIndexes = findAmbiguousWordIndexes(textToCheck);
view.setText(!ambiguousIndexes.isEmpty() ?
ambigousIndexesToMessage(ambiguousIndexes) : "No ambiguous word/s found.");
}
/**
* #param text checked for ambiguous words
* #return the list of indexes of the ambiguous words in the {#code words} array
*/
private List<Integer> findAmbiguousWordIndexes(String text) {
final String lowerCasedText = text.toLowerCase();
final List<Integer> ambiguousWordIndexList = new ArrayList<Integer>();
words = (String[]) colWords.toArray(new String[colWords.size()]);
meanings = (String[]) colMeanings.toArray(new String[colMeanings.size()]);
for (int i = 0; i < words.length; i++) {
if (lowerCasedText.contains(words[i].toLowerCase())) {
ambiguousWordIndexList.add(i);
}
}
return ambiguousWordIndexList;
}
public String ambigousIndexesToMessage(List<Integer> ambiguousIndexes) {
// create the text using the indexes
// this is an example implementation
StringBuilder sb = new StringBuilder();
for (Integer index : ambiguousIndexes) {
sb.append("Ambiguous words: ");
sb.append(words[index] + "\nMeaning: " + meanings[index] + "\n");
sb.append("");
}
return sb.toString();
}
But all it does is displaying the two records. Both id 1 and id 2. I just want to display only one record randomly. I really need help regarding this. Any ideas? I would gladly appreciate it.
You have RANDOM() ordering but you also need to add a LIMIT 1 to only return one result row. There's an overload of SQLiteDatabase.query() that takes in a limit parameter:
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_WORD, KEY_MEANING },
null, null, null, null, "RANDOM()", "1");

I want to select a number from the contact book in Android

This Code shows the List of Contact Numbers, but i want to select cell number from selected contact display name--->
Cursor cursor= managedQuery(intent.getData(), null, null, null, null);
while(cursor.moveToNext()) {
String contactId=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
System.out.println("---------ContactId---------"+contactId);
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("---------NAME---------"+name);
String hasPhone=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
System.out.println("---------HAS Phone---------"+hasPhone);
ArrayList one= new ArrayList();
ArrayList two= new ArrayList();
// if(Boolean.parseBoolean(hasPhone)) {
Cursor phones=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = "+ contactId, null, null);
while(phones.moveToNext()) {
phoneNumber= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("---------Number---------"+phoneNumber);
one.add(phoneNumber);
System.out.println("---------email Address---------"+one);
} phones.close();
// }
Display Names
public class ContentProviderActivity extends Activity {
ListView lv;
Map<String, List<String>> mymap;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listContact);
mymap = new HashMap<String, List<String>>();
Uri allContacts = Uri.parse("content://contacts/people/");
Cursor mCursor = managedQuery(allContacts, null, null, null, ContactsContract.Contacts._ID + " ASC");
final String[] contacts = new String[]{ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID};
int [] view = new int[]{R.id.txtName,R.id.txtID};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.main, mCursor, contacts, view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
//displayContacts(position+1);
int id1 = (int) adapter.getItemId(position);
Intent i = new Intent(getApplicationContext(),ShowContactNo.class);
i.putExtra("ID", id1);
startActivity(i);
}
});
}
}
ShowContactNo: TO display associated contact numbers
public class ShowContactNo extends ListActivity{
Map<String, List<String>> mymap;
String name;
List<String> Phone_No;
String select_Number;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mymap = new HashMap<String, List<String>>();
ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_NONE);
Intent i = getIntent();
int position = i.getIntExtra("ID", 0);
displayContacts(position);
Phone_No = new ArrayList<String>();
Phone_No = mymap.get(name);
System.out.println(Phone_No);
if(Phone_No!=null)
{
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, Phone_No));
}
final String [] items = new String [] {"Make Call", "Send Text SMS"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
if (item == 0) {
Intent i = new
Intent(android.content.Intent.ACTION_CALL,
Uri.parse("tel:"+select_Number));
startActivity(i);
dialog.cancel();
} else {
Intent i = new
Intent(android.content.Intent.ACTION_SENDTO,
Uri.parse("smsto:"+select_Number));
i.putExtra("sms_body", "Krishnakant Dalal");
startActivity(i);
}
}
} );
final AlertDialog dialog = builder.create();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
select_Number = String.valueOf(Phone_No.get(arg2));
dialog.show();
}
});
}
private void displayContacts(int position) {
if(position!=0)
{
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, ContactsContract.Contacts._ID +" = ?",
new String[]{String.valueOf(position)}, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
List<String> numberlist = new ArrayList<String>();
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Toast.makeText(this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
numberlist.add(phoneNo);
}
pCur.close();
mymap.put(name, numberlist);
}
}
}
}
}
}
Dont forget to add Permissions:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
Try this,
public void getPhoneNumber(String conatctname)
{
try
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
FirstName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if(FirstName!=null)
{
try
{
String[] splitval=FirstName.split(" ");
if(splitval.length>=1)
{
FirstName=splitval[0];
if(FirstName.equals(conatctname))
{
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
PhoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
PhoneNumberArray.add(PhoneNumber);
}
pCur.close();
}
}
}
catch(Exception error)
{
Log.d("SplitError", error.getMessage());
}
}
cursor.close();
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
}

Categories

Resources