Picking a Contact from phone book in android - 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?

Related

.setOnItemClicklistener not works

I would like to send my data from one activity to other with help of intent and uri but the task doesnt get accomplished
my main activity code
package com.example.vidit.inventoryapp;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import static android.R.attr.id;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
/** Identifier for the pet data loader */
private static final int ITEM_LOADER = 0;
/** Adapter for the ListView */
ItemCursorAdapter mCursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,editor.class);
startActivity(intent);
}
});
ListView ItemListView = (ListView) findViewById(R.id.list);
// Find and set empty view on the ListView, so that it only shows when the list has 0 items.
View emptyView = findViewById(R.id.empty_view);
ItemListView.setEmptyView(emptyView);
// Setup an Adapter to create a list item for each row of pet data in the Cursor.
// There is no pet data yet (until the loader finishes) so pass in null for the Cursor.
mCursorAdapter = new ItemCursorAdapter(this, null);
ItemListView.setAdapter(mCursorAdapter);
// Setup the item click listener
ItemListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Create new intent to go to {#link EditorActivity}
Intent intent = new Intent(MainActivity.this,editor.class);
Uri itemUri = ContentUris.withAppendedId(ItemContract.ItemEntry.CONTENT_URI, id);
intent.setData(itemUri);
startActivity(intent);
}
});
// Kick off the loader
getLoaderManager().initLoader(ITEM_LOADER, null, this);
}
private void insertPet() {
// Create a ContentValues object where column names are the keys,
// and Toto's pet attributes are the values.
ContentValues values = new ContentValues();
values.put(ItemContract.ItemEntry.NAME, "Football");
values.put(ItemContract.ItemEntry.PRICE, 200);
values.put(ItemContract.ItemEntry.STATUS, ItemContract.ItemEntry.ACCEPTED);
values.put(ItemContract.ItemEntry.QUANTITY, 7);
// Insert a new row for Toto into the provider using the ContentResolver.
// Use the {#link PetEntry#CONTENT_URI} to indicate that we want to insert
// into the pets database table.
// Receive the new content URI that will allow us to access Toto's data in the future.
Uri newUri = getContentResolver().insert(ItemContract.ItemEntry.CONTENT_URI, values);
}
/**
* Helper method to delete all pets in the database.
*/
private void deleteAllPets() {
int rowsDeleted = getContentResolver().delete(ItemContract.ItemEntry.CONTENT_URI, null, null);
Log.v("CatalogActivity", rowsDeleted + " rows deleted from pet database");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
ItemContract.ItemEntry._ID,
ItemContract.ItemEntry.NAME,
ItemContract.ItemEntry.PRICE,
ItemContract.ItemEntry.QUANTITY,
};
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(this, // Parent activity context
ItemContract.ItemEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mCursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
My adapter class:
package com.example.vidit.inventoryapp;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
import static android.R.attr.id;
import static android.R.attr.order;
import static android.R.attr.value;
import static android.os.Build.VERSION_CODES.M;
public class ItemCursorAdapter extends CursorAdapter {
public ItemCursorAdapter(Context context, Cursor c) {
super(context, c, 0 /* flags */);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate a list item view using the layout specified in list_item.xml
return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
// Find individual views that we want to modify in the list item layout
TextView nameTextView = (TextView) view.findViewById(R.id.name);
TextView priceTextView = (TextView) view.findViewById(R.id.price);
final TextView quantityTextView = (TextView) view.findViewById(R.id.quantity);
Button sell=(Button) view.findViewById(R.id.sell);
Button order=(Button) view.findViewById(R.id.order);
Button detail =(Button) view.findViewById(R.id.detail);
// Find the columns of pet attributes that we're interested in
int nameColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry.NAME);
int priceColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry.PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry.QUANTITY);
// Read the attributes from the Cursor for the current pet
String itemName = cursor.getString(nameColumnIndex);
String itemPrice = cursor.getString(priceColumnIndex);
final String itemQuantity=cursor.getString(quantityColumnIndex);
if (TextUtils.isEmpty(itemPrice)) {
itemPrice = "Not known yet";
}
if (TextUtils.isEmpty(itemQuantity)) {
itemPrice = "Not known yet";
}
final int qua=Integer.parseInt(itemQuantity);
nameTextView.setText(itemName);
priceTextView.setText(itemPrice);
quantityTextView.setText(itemQuantity);
sell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Integer.parseInt(itemQuantity)>0)
{
int x=Integer.parseInt(itemQuantity)-1;
quantityTextView.setText("" + x);
int idColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry._ID);
int id = cursor.getInt(idColumnIndex);
Uri itemUri = ContentUris.withAppendedId(ItemContract.ItemEntry.CONTENT_URI, id);
ContentValues values = new ContentValues();
values.put(ItemContract.ItemEntry.QUANTITY, x);
context.getContentResolver().update(itemUri, values, null, null);
}
}
});
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","abc#gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
context.startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
});
/* view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context,editor.class);
Uri itemUri = ContentUris.withAppendedId(ItemContract.ItemEntry.CONTENT_URI, id);
intent.setData(itemUri);
context.startActivity(intent);
}
});*/
}
}
if I add intent code which i have commented in adapter class itnet happens succesfully but no data is passed from list view to the intent .
Thanks in advance.

How do I refresh my cursor from another activity?

How do I refresh my cursor from another activity?
In my main activity I start a cursor to query phone contacts and display in a listview.
In this main activity I also have a menu, 'Add new Contact', which starts the add new contact activity. A new contact gets added correctly (I can see it in other Contacts apps on my phone), but it is not visible in my listview when the user goes back to main activity.
Is there a way to refresh the cursor from 'add new contact' activity, so the user can see it in the listview when they go back to main activity?
I use AsyncTask in my main activity, if that's any useful info. I read about swapcursor and changecursor but it didn't work when I tried to use them. Here's my 'add new contact' code :
(I call changecursor before the "Contact Saved" toast, but I'm sure it's not done correctly.
package com.example.chris.contactlistcustomlistview;
import android.content.ContentProviderOperation;
import android.content.OperationApplicationException;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Chris on 06/05/2016.
*/
public class AddContact extends AppCompatActivity {
EditText nameofcontact;
EditText numberofcontact;
public String contactname;
public String contactnumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addcontact);
nameofcontact = (EditText) findViewById(R.id.edittextname);
numberofcontact = (EditText) findViewById(R.id.edittextnumber);
}
public void createButton(View view) {
contactname = nameofcontact.getText().toString();
contactnumber = numberofcontact.getText().toString();
if (contactname.length() == 0) {
Toast.makeText(this, "Please enter a name",
Toast.LENGTH_LONG).show();
return;
}
ArrayList<ContentProviderOperation> contentProviderOperations = new ArrayList<ContentProviderOperation>();
//insert raw contact using RawContacts.CONTENT_URI
contentProviderOperations.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());
//insert contact display name using Data.CONTENT_URI
Log.d("ffff","wwww");
contentProviderOperations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,contactname ).build());
//insert mobile number using Data.CONTENT_URI
contentProviderOperations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contactnumber).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
try {
//apply the changes
getApplicationContext().getContentResolver().
applyBatch(ContactsContract.AUTHORITY, contentProviderOperations);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
// SelectContactAdapter.changeCursor(cursor);
Toast.makeText(this, "Contact saved",
Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
//This clears the edittext next time user starts the application, rather than
// having the same numbers there, which the user probably doesn't want anymore
protected void onResume() {
final EditText editText = (EditText) findViewById(R.id.edittextname);
super.onResume();
editText.setText("");
}
}
And here's my MainActivity code :
package com.example.chris.contactlistcustomlistview;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends Activity implements PopupMenu.OnMenuItemClickListener {
// ArrayList
ArrayList<SelectContact> selectContacts;
List<SelectContact> temp;
// Contact List
ListView listView;
// Cursor to load contacts list
// Cursor phones, email;
Cursor pCur;
// Pop up
// ContentResolver resolver;
SearchView search;
SelectContactAdapter adapter;
String phoneContactId;
String name;
String phoneNumber;
CharSequence nameofcontact;
// String phoneNumber;
// *****18-04-2016***
Cursor cursor;
ListView mainListView;
ArrayList hashMapsArrayList;
// String contactid;
// *****
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectContacts = new ArrayList<SelectContact>();
// resolver = this.getContentResolver();
listView = (ListView) findViewById(R.id.contacts_list);
LoadContact loadContact = new LoadContact();
loadContact.execute();
search = (SearchView) findViewById(R.id.searchView);
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
adapter.filter(newText);
return false;
}
});
}
// Load data on background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
if (cursor != null) {
cursor.moveToFirst();
}
try {
// get a handle on the Content Resolver, so we can query the provider,
cursor = getApplicationContext().getContentResolver()
// the table to query
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
// Null. This means that we are not making any conditional query into the contacts table.
// Hence, all data is returned into the cursor.
// Projection - the columns you want to query
null,
// Selection - with this you are extracting records with assigned (by you) conditions and rules
null,
// SelectionArgs - This replaces any question marks (?) in the selection string
// if you have something like String[] args = { "first string", "second#string.com" };
null,
// display in ascending order
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
// get the column number of the Contact_ID column, make it an integer.
// I think having it stored as a number makes for faster operations later on.
int Idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
// get the column number of the DISPLAY_NAME column
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
// get the column number of the NUMBER column
int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// int photoIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI);
cursor.moveToFirst();
// We make a new Hashset to hold all our contact_ids, including duplicates, if they come up
Set<String> ids = new HashSet<>();
do {
System.out.println("=====>in while");
// get a handle on the contactid, which is a string. Loop through all the contact_ids
String contactid = cursor.getString(Idx);
// if our Hashset doesn't already contain the contactid string,
// then add it to the hashset
if (!ids.contains(contactid)) {
ids.add(contactid);
HashMap<String, String> hashMap = new HashMap<String, String>();
// get a handle on the display name, which is a string
name = cursor.getString(nameIdx);
// get a handle on the phone number, which is a string
phoneNumber = cursor.getString(phoneNumberIdx);
// String image = cursor.getString(photoIdIdx);
// System.out.println("Id--->"+contactid+"Name--->"+name);
System.out.println("Id--->" + contactid + " Name--->" + name);
System.out.println("Id--->" + contactid + " Number--->" + phoneNumber);
SelectContact selectContact = new SelectContact();
// selectContact.setThumb(bit_thumb);
selectContact.setName(name);
selectContact.setPhone(phoneNumber);
// selectContact.setEmail(id);
// selectContact.setCheckedBox(false);
selectContacts.add(selectContact);
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
// if (cursor != null) {
// }
}
cursor.close();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//into each inflate_listview, put a name and phone number, which are the details making
// our SelectContact, above. And SelectContacts is all these inflate_listviews together
// This is the first property of our SelectContactAdapter, a list
// The next part, MainActivity.this, is our context, which is where we want the list to appear
adapter = new SelectContactAdapter(selectContacts, MainActivity.this);
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
nameofcontact = ((TextView)view.findViewById(R.id.name)).getText();
// }
// Creates a new Intent to edit a contact
Intent intent = new Intent(Intent.ACTION_EDIT);
startActivity(intent);
listView.setFastScrollEnabled(true);
}
});
}}
//the is the arrow image, it opens the activity for edit or new contact
public void EditorCreateContact(View v) {
}
#Override
protected void onStop() {
super.onStop();
}
// this is for the settings menu
public void settingsPopUp(View view) {
PopupMenu popup = new PopupMenu(this,view);
popup.setOnMenuItemClickListener(MainActivity.this);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.popup_actions, popup.getMenu());
popup.show();
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
// from the popup_actions.xml, identify the New_contact id and make it
// open the AddContact class
case R.id.New_contact:{
Intent intent = new Intent(this, AddContact.class);
startActivity(intent);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(intent);
// finish(); // Call once you redirect to another activity
}
// Toast.makeText(getBaseContext(), "You slected New Contact",Toast.LENGTH_SHORT).show();
//
return true;
}
return false;
}
}
First of all declare the line
final EditText editText = (EditText) findViewById(R.id.edittextname);
in OnCreate() ... as it is a bad practice to initialize the view every time at on resume of activity.
and query the data in OnResume of your activity. Thats a better way to refresh the data as you come back to your activity.
You can refresh your contacts in onResume() method as i mentioned in comments, for that you can do the following in onResume() itself
LoadContact loadContact = new LoadContact();
loadContact.execute();
you can remove the above from onCreate() as it would be redundant to call as onResume() will be called every time as the Activity LifeCycle.
If you use this approach just clear ArrayList selectContacts by doing selectContacts.clear() in doInBackground() at the first line, other wise it will list contacts twice and thrice and so onn...
Also apart from these, as mentioned in another answer in same thread you can use, startActivityForResult() and in onActivityResult() method you can update contact list.
You could use startActivityForResult() instead of startActivity and override onActivityResult() to requery your cursor on success. After the toasting, setResult() to RESULT_OK and finish the AddContact activity.
setResult(RESULT_OK);
finish();

Image fails to display

I want to display an image using a file path .
/mnt/sdcard/DCIM/Camera/IMG_20140524_150944.jpg
Here is the layout file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/item_single_new"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"/>
</LinearLayout>
Here is the code i am using.
package com.bridge.bridgeinventory;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
public class SingleImage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_image);
ImageView image = (ImageView)
findViewById(R.id.item_single_new);
image.setAdjustViewBounds(true);
image.setMaxHeight(100);
image.setMaxWidth(100);
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
Intent i=getIntent();
String myimage =i.getStringExtra("photo").trim();
Log.e("image path", myimage);
Bitmap m= BitmapFactory.decodeFile(myimage);
if(m==null)
{
Toast.makeText(getApplicationContext(), "Image was deleted", Toast.LENGTH_LONG).show();
}
image.setImageBitmap(m);
}
}
The intent extral prints out correctly(as shown above) but the image does not display.
I only see a black patch instead of the image.
Is there anything simple i am missing?
This was supposed to be something simple but it has completely defeated me!
Ronald
This is how i get the path to store in the db.
public void GetPhoto(View v)
{
Intent picintent= new Intent(Intent.ACTION_PICK);
picintent.setType("image/*");
startActivityForResult(picintent,GET_PHOTO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if(requestCode==GET_PHOTO){
if (resultData != null) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
String imagePath = cursor.getString(column_index_data);
cursor.close();
bridgephoto=imagePath;
Log.e("imagepath", bridgephoto);
}
}
}
The bridgephoto variable is a class level variable
After getting from the intent, i use it to set the photo proprty like below.
bridge.setBridgePhoto(bridgephoto);
Then i have a listview that displays the bridges . It has an a context menu with an option to display the bridge photo.
Here is the code for the photo menu item
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
int menuItemIndex = item.getItemId();
String menuItemName =menuitems[menuItemIndex];
final AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
.getMenuInfo();
final int pos = menuInfo.position;
if(menuItemName=="Photo")
{
Bridge b= (Bridge)ba.getItem(pos);
String image=b.getBridgePhoto();
/// put it in an intent!
Intent i= new Intent(Bridges.this,SingleImage.class);
i.putExtra("photo",image);
startActivity(i);
}
return super.onMenuItemSelected(featureId, item);
}
It is the string extral that is passed to the SingleImage activity.
But i have used Log.e to test the string(image path) and it appears correct.

Get contacts by push of a button

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"/>

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.

Categories

Resources