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.
Related
I would like to change an ImageView's image to black and white. The only thing is my code allows the user to take a photo, that photo is placed in the imageview. I would like that photo to be black and white. If anyone knows how I could do this, I would appreciate it.
MainActivity:
package com.example.triptych4;
import java.io.File;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
// label our logs "CameraApp3"
private static String logtag = "CameraApp3";
// tells us which camera to take a picture from
private static int TAKE_PICTURE = 1;
// empty variable to hold our image Uri once we store it
private Uri imageUri;
private Integer[] pics = { R.drawable.android, R.drawable.android3d,
R.drawable.background3 };
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
imageView = (ImageView) findViewById(R.id.imageView1);
gallery.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), "pic:" + arg2,
Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[arg2]);
}
});
// look for the button we set in the view
ImageButton cameraButton = (ImageButton)
findViewById(R.id.button_camera);
// set a listener on the button
cameraButton.setOnClickListener(cameraListener);
}
// set a new listener
private OnClickListener cameraListener = new OnClickListener() {
public void onClick(View v) {
// open the camera and pass in the current view
takePhoto(v);
}
};
public void takePhoto(View v) {
// tell the phone we want to use the camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// create a new temp file called pic.jpg in the "pictures" storage area of the phone
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "pic.jpg");
// take the return data and store it in the temp file "pic.jpg"
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
// stor the temp photo uri so we can find it later
imageUri = Uri.fromFile(photo);
// start the camera
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class ImageAdapter extends BaseAdapter{
private Context context;
int imageBackground;
public ImageAdapter(Context context){
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pics.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView imageView =new ImageView(context);
imageView.setImageResource(pics[arg0]);
return imageView;
}
}
// override the original activity result function
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// call the parent
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
// if the requestCode was equal to our camera code (1) then...
case 1:
// if the user took a photo and selected the photo to use
if(resultCode == Activity.RESULT_OK) {
// get the image uri from earlier
Uri selectedImage = imageUri;
// notify any apps of any changes we make
getContentResolver().notifyChange(selectedImage, null);
// get the imageView we set in our view earlier
ImageButton imageButton = (ImageButton)findViewById(R.id.button_camera);
// create a content resolver object which will allow us to access the image file at the uri above
ContentResolver cr = getContentResolver();
// create an empty bitmap object
Bitmap bitmap;
try {
// get the bitmap from the image uri using the content resolver api to get the image
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
// set the bitmap to the image view
imageButton.setImageBitmap(bitmap);
// notify the user
Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
} catch(Exception e) {
// notify the user
Toast.makeText(MainActivity.this, "failed to load", Toast.LENGTH_LONG).show();
Log.e(logtag, e.toString());
}
}
}
}
}
Layout:
<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"
tools:context="com.example.triptych5.MainActivity" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="200dp"
android:layout_height="200dp"
android:scaleType="fitXY"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/button_camera"/>
<ImageButton
android:id="#+id/button_camera"
android:layout_width="230dp"
android:layout_height="235dp"
android:scaleType="fitXY"
android:rotation="-90"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/middle4" />
<Gallery
android:id="#+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
You can simply achieve this by doing:
ImageView imageview = (ImageView) findViewById(R.id.imageView1);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
imageview.setColorFilter(filter);
This is the Kotlin Version
imageView.colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f)})
You can use android.graphics.ColorFilter for your purpose.
You can use this sample to suite your need.
Pass the imageView to the setBW method like
setBW(imageView);
and the the functionality is
private void setBW(ImageView iv){
float brightness = 10; // change values to suite your need
float[] colorMatrix = {
0.33f, 0.33f, 0.33f, 0, brightness,
0.33f, 0.33f, 0.33f, 0, brightness,
0.33f, 0.33f, 0.33f, 0, brightness,
0, 0, 0, 1, 0
};
ColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
iv.setColorFilter(colorFilter);
}
Try using this. Any concerns. Let me know. Thanks.
I would also suggest using Kotlin extensions:
private const val MAX_SATURATION = 1f
private const val MIN_SATURATION = 0f
fun ImageView.setMaxSaturation() {
val matrix = ColorMatrix()
matrix.setSaturation(MAX_SATURATION)
colorFilter = ColorMatrixColorFilter(matrix)
}
fun ImageView.setMinSaturation() {
val matrix = ColorMatrix()
matrix.setSaturation(MIN_SATURATION)
colorFilter = ColorMatrixColorFilter(matrix)
}
Java version in one line
imageview.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(){{setSaturation(0f);}}));
I'm trying to make a android app that will take a picture from the camera and display it on the same screen next to the "take picture button". I've been trying to use a tutorial but it is not working. whenever I take the picture and press save, the picture app fails. Also I don't know if it would display the photo on screen if I saved it. However, I am not sure of this since it always breaks after I press save.
Does anybody have any suggestions to help me save and display the photo on screen?
Thanks
Here's my xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_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="com.example.pictureproject.MainActivity"
android:orientation ="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button_camera"
android:text="#string/button_camera"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id = "#+id/image_camera"
android:contentDescription="#string/image_cd_camera"
android:layout_width="fill_parent"
android:layout_height = "wrap_content"
/>
</LinearLayout>
and Heres my java:
package com.example.pictureproject;
import java.io.File;
import android.app.Activity;
import android.content.ContentResolver;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static String logtag ="CameraApp8";
private static int TAKE_PICTURE = 1;
private Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cameraButton = (Button)findViewById(R.id.button_camera);/*possibly button camera 1*/
cameraButton.setOnClickListener(cameraListener);
}
private OnClickListener cameraListener = new OnClickListener() {
public void onClick(View v){
takePhoto(v);
}
};
private void takePhoto(View v){
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"picture.jpg");
imageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
if(resultCode == Activity.RESULT_OK){
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView)findViewById(R.id.image_camera);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try{
bitmap = MediaStore.Images.Media.getBitmap(cr,selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, selectedImage.toString(),Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e(logtag,e.toString());
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
try to add this code..
public class MyCameraActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
i am programming a little bit android and i have a problem with adding and calling contacts.
my idea was to add two contacts and when the call-button was pressed the user can decide which one he wants to call.. and my two problems are, that on my AVD the code is working until i have to call somebody. so i can choose 2 contacts and these contacts are safed... on the phone of my friend i cant even choose contacts.. the programm just says: "The Application Contacts_SPrefs stopped working"...
well i think there is a problem in my code.. but i dont know where it is and how i could fix it, because in my previous version the code works...
So in this part of the app you can add 2 contacts and choose the button call which opens the other intent which is described below
Main Activity
package com.example.contact_sprefs;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private String contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// this opens the activity. note the Intent.ACTION_GET_CONTENT
// and the intent.setType
((Button)findViewById(R.id.bro1)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
//-------- > this thing here opens the contacts view < ------
//later its waiting until the user clicks on a number of his contacts
contact = "Brah1";
startActivityForResult(intent, 1);
}
});
((Button)findViewById(R.id.bro2)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
contact = "Brah2";
startActivityForResult(intent, 1);
}
});
((Button)findViewById(R.id.call)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), OpenMenu.class);
startActivity(intent);
}
});
}
//doing random sh*t which i dont know whaat happens
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
//after he clicked a number its getting to this point
//in the uri it saves some number and all this things where the contact is
//so this is for the location
Uri uri = data.getData();
if (uri != null) {
//get more data
//in this cursor all the values of the contacts are going to be safed
//c is for the contact
Cursor c = null;
try {
//here all datas from the contact are going to be safed in c
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
//c is the phone number in very special code types and stuff like that
//in c is everything from the contact saved
//now c is going to be converted into a string -> everything that stays is the phone number
String number = c.getString(0);
//get the type... somehow
int type = c.getInt(1);
showSelectedNumber(type, number);
save(contact, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, "Saved Nr : " + number, Toast.LENGTH_LONG).show();
}
public void save(String type, String number) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString(type, number);
edit.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
so.. as you can see.. i dont know really much about the topic Intent and its specifications.. anyway... heres the second part of the app, in which the call-command is.. and this command doesent work either...
OpenMenu
package com.example.contact_sprefs;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class OpenMenu extends Activity {
private String nr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open_menu);
((Button)findViewById(R.id.bro1)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
nr = load("Brah1", nr);
String uri = "tel:" + nr.trim() ;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
startActivity(intent);
}
});
((Button)findViewById(R.id.bro2)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
nr = load("Brah2", nr);
String uri = "tel:" + nr.trim() ;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
startActivity(intent);
}
});
}
public void showSelectedNumber(String number) {
Toast.makeText(this, "Took Nr : " + number, Toast.LENGTH_LONG).show();
}
public String load(String brahNr, String number) {
String sharedNumber;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
sharedNumber = sp.getString(brahNr, number);
return sharedNumber;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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.get
ItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
....well... this is a lot of code(for me).. and i thank everybody who helps me :)
edited lateron
i just forgot the permissions... so this is also needed
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
vZ
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?
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.