Get contacts by push of a button - android

I want a scroll-able list of contacts to pop up when a click a button. I cannot figure out how to get it and how content resolvers, managed queries, and adapters work.
I have tried with the following code:
package com.hapybay.rad;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.database.Cursor;
public class startingPoint extends Activity {
Button redcandle;
private ListView mContactList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*Obtain handles to UI objects (Constructor)*/
redcandle = (Button) findViewById(R.id.button1);
/*Register handle for UI element*/
redcandle.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
populateContactList();
}
});
}
private void populateContactList() {
// Build adapter with contact entries
Cursor cursor = getContacts();
String[] fields = new String[] {
ContactsContract.Data.DISPLAY_NAME
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor,
fields, new int[]{R.id.contactEntryText});
mContactList.setAdapter(adapter);
}
private Cursor getContacts()
{
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
}

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
and override this in your activity
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// TODO Whatever you want to do with the selected contact name.
}
}
break;
}
}
dont forget to add the permission
<uses-permission android:name="android.permission.READ_CONTACTS"/>

Related

Android get all details of a contact

I didn't find any solution in the Internet, only a tutorial on Android Developers, which unfortunately gives only a small part of code needed for it. I ended up having something like this:
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract.Data;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
// Defines the selection clause
private static final String SELECTION = Data.LOOKUP_KEY + " = ?"; // Defines the array to hold the search criteria
private String[] mSelectionArgs = { "" };
private String mLookupKey;
private static final String SORT_ORDER = Data.MIMETYPE;
final int DETAILS_QUERY_ID = 0;
private static final String PROJECTION[] = {
Data._ID, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5, Data.DATA6, Data.DATA7, Data.DATA8, Data.DATA9, Data.DATA10, Data.DATA11, Data.DATA12, Data.DATA13, Data.DATA14, Data.DATA15
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// getLoaderManager().initLoader(DETAILS_QUERY_ID, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int loaderId, Bundle args) {
switch (loaderId) {
case DETAILS_QUERY_ID:
// Assigns the selection parameter
mSelectionArgs[0] = mLookupKey; // Starts the query
CursorLoader mLoader = new CursorLoader(this, Data.CONTENT_URI, PROJECTION,
SELECTION, mSelectionArgs, SORT_ORDER);
}
return null; // TODO what should be here ?
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// switch (loader.getId()) {
// case DETAILS_QUERY_ID:
// }
// break;
// }
}
}
How can I make it work ? https://developer.android.com/training/contacts-provider/retrieve-details.html is really lacking some code and explanation

Unable to attach file though after you are navigated to files using ACTION_GET_CONTENT

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class AttachFiles extends Activity {
Button btnAddFile;
ListView listViewFiles;
String[] str;
ArrayList<String> arrayList = new ArrayList<String>();
Adapter myFileListAdapter;
final int RQS_LOADIMAGE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAddFile = (Button) findViewById(R.id.addphoto);
btnAddFile.setOnClickListener(btnAddFileOnClickListener);
}
View.OnClickListener btnAddFileOnClickListener
= new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, RQS_LOADIMAGE);
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_LOADIMAGE:
Uri imageUri = data.getData();
String string = imageUri.toString();
Log.e("STRING", " "+string);
arrayList.add(string);
Log.e("Get arrayList :" , " "+arrayList);
myFileListAdapter = new Adapter(AttachFiles.this, arrayList);
listViewFiles = (ListView) findViewById(R.id.filelist);
listViewFiles.setAdapter(myFileListAdapter);
myFileListAdapter.notifyDataSetChanged();
break;
}
}
}
}
In the above code I can see the files but couldn't load it into ListView.
In case you getting the result inside onactivityresult().I haven't see other than any chance to an error.
Change Adapter to ArrayAdapter
ArrayAdapter< String > myFileListAdapter = new
ArrayAdapter< String >(AttachFiles.this,
android.R.layout.simple_list_item_1, arrayList);
And declaring listview inside oncreate is better.
And give a try :)

Picking a Contact from phone book in android

I want to pick a contact from the phone book in android. I press a button and then it shows the contact list. When I click I want to pick that clicked contact's number displayed in my activity, but in my case it returned null. Here is my code:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
Button b;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,People.CONTENT_URI);
startActivityForResult(intent, 100);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri contact = data.getData();
Cursor c = managedQuery(contact, null, null, null, null);
c.moveToFirst();
tv.setText(c.getString(c.getColumnIndex(People.NUMBER))+" Added");
}
}
Why this is happening?
Thanks in advance.
instead of using People.CONTENT_URI use ContactsContract.Contacts.CONTENT_URI
that is instead of
Intent intent = new Intent(Intent.ACTION_PICK,People.CONTENT_URI);
use
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
example : Getting Contact Phone Number
your onacitivityResult:
Uri contact = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = managedQuery(contact, null, null, null, null);
// c.moveToFirst();
while(c.moveToNext()){
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
tv.setText(name+" Added " + phone);
}
}
}
Did you try to pick different contacts? this may be stupid, but maybe that contact doesn't have a number?

Retrieving contacts in list view and displaying the name and phone number in next activity with click action

I have got the code where through content provider i am retrieving the phone contacts and displaying them in list format.
I want to display the phone no and name of the particular person in next activity when i click on the list format contacts from first activity. I am getting errors in this its not able to perform click operation and display it on to next activity Please help me with this.
Here is the first Activity through i am display the contacts through content provider.
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MsatActivity extends ListActivity
{
TextView ContactsTV;
ListView lv;
Cursor c;
public static final Uri CONTENT_URI =
Uri.parse("content://com.android.contacts/contacts/1557");
public void onListItemClick(View v)
{
Intent outData = new Intent(this,Full.class);
// setResult(Activity.RESULT_OK, outData);
startActivity(outData);
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Uri myContacts = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
c = getContentResolver().query(myContacts, new String[]
{ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER}
, null, null, null);
String[] columns = new String[]
{
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] to = new int[] {R.id.text1,R.id.text2};
SimpleCursorAdapter mAdapter = new
SimpleCursorAdapter(this,R.layout.listitems, c, columns, to);
setListAdapter(mAdapter);
lv.setOnItemSelectedListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
{
int rowId = c.getInt(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone._ID));
Uri outURI = Uri.parse(CONTENT_URI.toString() + "/" + rowId);
Intent outData = new Intent();
outData.setData(outURI);
setResult(Activity.RESULT_OK, outData);
finish();
}
});
}
}
Here is the second activity.......
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
public class Full extends Activity
{
private static final int CONTACT_PICKER_RESULT = 1001;
String name;
Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
Button getContacts = (Button)findViewById(R.id.button1);
getContacts.setOnItemClickListener(new View.OnItemClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, CONTACT_PICKER_RESULT);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK)
{
switch (requestCode)
{
case CONTACT_PICKER_RESULT:
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
//Get Name
cursor = getContentResolver().query(result, null, null, null, null);
if (cursor.moveToFirst())
{
name =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
catch (Exception e)
{
}
}
}
}
}
I really can't figure out your code at all. The first activity seems to be creating an Intent to start the Full Activity, but it has two "onclick" methods and it does a setResult() and finish() even though it never did getIntent()!
The second activity creates an ACTION_PICK Intent for the entire Phone table, and handles the return by doing a query on the result, which should be the contact ID of the contact whose # the user picked. I don't think it's the entire URI, though; you should verify that through debug. You then try to get the DISPLAY_NAME for this contact.
Fine, but I don't see why you need the first Activity at all.
I posted some instructions on using the Contacts Provider somewhere else on Stackoverflow; just search for android and ContactsContract.

Android: Database help -Return all items in a specific column

i am really stuck. I am familiar in Java and Android development but i do not have any experience with databases. This is my first time. I have been going through multiple tutorials but i cannot figure out how return all the values from a specific row and set it to a single string.
Below is my database console. I was able to get all the items and display it in my view but i intended on writing a specific function to do something with all the data in only the TITLE column. Can anyone shed any light or provide a small routine to get all the items from the TITLE column into a single string? The very last function is my getTitleList that is where i would like to gather the data
Here is the function:
public void getTitleList(){
cursor = db.rawQuery("SELECT TITLE FROM table", null);
cursor.close();
}
Here is my class
package edu.asu;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.view.View;
import android.app.ListActivity;
import static android.provider.BaseColumns._ID;
public class DbBookConsole extends ListActivity {
private static String[] FROM = { _ID, DbConstants.TITLE, DbConstants.PRICE,
DbConstants.ISBN, DbConstants.CHECKIN };
private DbCreate books;
private static SQLiteDatabase db;
private static int[] TO = { R.id.rowid, R.id.name, R.id.price, R.id.isbn, R.id.checkin};
private ListView lv1;
private static String itemId;
private static String titles;
private static String test;
private Cursor cursor;
static final int BOOK_CANCELED = 0;
static final int BOOK_ADDED = 1;
static final int BOOK_MODIFIED = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showDatabaseContent();
lv1 = getListView();
lv1.setTextFilterEnabled(true);
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
cursor = (Cursor) a.getItemAtPosition(position);
itemId = cursor.getString(0);
openOptionsMenu();
}
});
lv1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
// selected item index from ListView
public void showDialogItemId(long itemId) {
Toast.makeText(this,
"Menu item selected index is" + Long.toString(itemId),
Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.modifyitem:
if (null != itemId) {
Bundle bookToModify = new Bundle();
bookToModify.putString("cTitle", cursor.getString(1));
bookToModify.putString("cPrice", cursor.getString(2));
bookToModify.putString("cISBN", cursor.getString(3));
bookToModify.putString("cCheckin", cursor.getString(4));
bookToModify.putString("mod_type", "modifyBook");
Intent intent = new Intent(this, BookDetails.class);
intent.setClass(this, BookDetails.class);
intent.putExtras(bookToModify);
startActivityForResult(intent, BOOK_MODIFIED);
} else {
Toast
.makeText(this, "Select Book to modify",
Toast.LENGTH_LONG).show();
}
break;
case R.id.additem:
Intent i = new Intent(this, BookDetails.class);
Bundle bun = new Bundle();
bun.putString("mod_type", "addBook");
i.setClass(this, BookDetails.class);
i.putExtras(bun);
startActivityForResult(i, BOOK_ADDED);
break;
case R.id.removeitem:
if (null != itemId) {
removeBook(itemId);
showDatabaseContent();
} else {
Toast
.makeText(this, "Select Book to delete",
Toast.LENGTH_LONG).show();
}
break;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
// See which child activity is calling us back.
switch (resultCode) {
case BOOK_ADDED:
// This is the standard resultCode that is sent back if the
// activity crashed or didn't doesn't supply an explicit result.
if (resultCode == RESULT_FIRST_USER) {
Bundle bundle = new Bundle();
bundle = intent.getBundleExtra("bookData");
addBook(bundle);
showDatabaseContent();
} else {
Toast.makeText(this, "CANCEL BOOK BUTTON PRESSED",
Toast.LENGTH_LONG).show();
}
break;
case BOOK_MODIFIED:
if (resultCode == 2) {
Bundle bundle = new Bundle();
bundle = intent.getBundleExtra("bookData");
modifyBook(bundle);
showDatabaseContent();
} else {
Toast.makeText(this, "MODIFY BOOK FAILED", Toast.LENGTH_LONG)
.show();
}
break;
default:
break;
}
}
// method removes item from database
private void removeBook(String itemId) {
db = books.getWritableDatabase();
db.delete(DbConstants.TABLE_NAME, "_ID=" + itemId, null);
}
private void addBook(Bundle bundle) {
// Insert a new record into the Events data source.
// You would do something similar for delete and update.
db = books.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put(DbConstants.TITLE, bundle.getString("bookTitle"));
vals.put(DbConstants.PRICE, bundle.getString("bookPrice"));
vals.put(DbConstants.ISBN, bundle.getString("bookISBN"));
vals.put(DbConstants.CHECKIN, bundle.getString("bookCheck"));
db.insertOrThrow(DbConstants.TABLE_NAME, null, vals);
}
// method should modify existing Contact
private void modifyBook(Bundle bundle) {
db = books.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put(DbConstants.TITLE, bundle.getString("bookTitle"));
vals.put(DbConstants.PRICE, bundle.getString("bookPrice"));
vals.put(DbConstants.ISBN, bundle.getString("bookISBN"));
vals.put(DbConstants.CHECKIN, bundle.getString("bookCheck"));
db.update(DbConstants.TABLE_NAME, vals, _ID + "=" + itemId, null);
}
private Cursor getBooks() {
db = books.getReadableDatabase();
cursor = db.query(DbConstants.TABLE_NAME, FROM, null, null, null, null, null,
null);
startManagingCursor(cursor);
return cursor;
}
public void showDatabaseContent() {
books = new DbCreate(this);
try {
cursor = getBooks();
showBooks(cursor);
} finally {
books.close();
db.close();
}
}
private void showBooks(Cursor cursor) {
// set up data binding
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.item, cursor, FROM, TO);
setListAdapter(adapter);
}
public void getTitleList(){
cursor = db.rawQuery("SELECT TITLE FROM table", null);
cursor.close();
}
}
unless i missunderstood the Question to get all items from your query in a cursor, loop through all items and concatenate into a string you would do something like this:
// constants of column indexes
int INDEX_ROWID = 0;
int INDEX_TITLE = 1;
...
db = new MyDBAdapter(this);
db.open();
Cursor c = db.getTitleList();
startManagingCursor(c);
String allTitles;
// loop through cursor
while(c.moveToNext()) {
allTitles += c.getString(INDEX_TITLE);
}
Hope that helps

Categories

Resources