BitmapFactory decodeFile FileNotFoundException - android

I have an app where you can select images from the gallery or Photos folder on the device. The selected file's paths are stored in an Intent so they can be passed around between Activities. I access the paths via intent.getDataString().
Once i have all the selected paths to the images, i store them in an ArrayList and pass that to an ImageAdapter, to display in a ListView.
I'm geting a FileNotFoundException, Has anyone any ideas why?
Thanks in advance
Matt.
import java.util.ArrayList;
import uk.co.mobilewebexpert.infowrapsynclibrary.ApplicationObj;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class QueuedImagesActivity extends Activity {
private static final String TAG = QueuedImagesActivity.class.getSimpleName();
private ImageAdapter adapter;
private ListView imageList;
ApplicationObj appObj;
Intent[] photos;
String path;
private ArrayList<String> imagePaths= new ArrayList<String>(); // Edit your code here..
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.image_listview);
appObj = (ApplicationObj) getApplication();
boolean includeBeingProcessed = true;
try {
photos = appObj.getQueuedPhotos(includeBeingProcessed);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < photos.length; i++){
path = photos[i].getDataString();
imagePaths.add(path);
Log.e(TAG, "path in QueuedImagesActivity = " + path);
}
imageList= (ListView) findViewById(R.id.listView1);
adapter= new ImageAdapter(getBaseContext(), imagePaths);
imageList.setAdapter(adapter);
}
}
.
import java.util.ArrayList;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private static final String TAG = ImageAdapter.class.getSimpleName();
static class RowItemHolder{
ImageView imageView;
}
private Context context;
private ArrayList<String> imagePaths= new ArrayList<String>();
public ImageAdapter(Context baseContext, ArrayList<String> imagePaths) {
// TODO Auto-generated constructor stub
this.context= baseContext;
this.imagePaths= imagePaths;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return imagePaths.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view;
view= convertView;
RowItemHolder holder = null;
if(view== null){
LayoutInflater in =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = in.inflate(R.layout.image_view, parent, false);
holder= new RowItemHolder();
holder.imageView=(ImageView) view.findViewById(R.id.imageView1);
view.setTag(holder);
} else{
holder = (RowItemHolder) view.getTag();
}
//Edit the code here according to you needs..
//like creating option and converting to Bitmap,
//or you can do this job in the main activity.
//holder.imageView.setImageResource(imagePaths.get(position));
Log.e(TAG, "imagePaths.get(position) = " + imagePaths.get(position));
holder.imageView.setImageBitmap(BitmapFactory.decodeFile(imagePaths.get(position)));
return view;
}
}
.
07-02 07:51:33.941: E/QueuedImagesActivity(22700): path in QueuedImagesActivity = content://media/external/images/media/7496
07-02 07:51:33.951: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.961: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException
07-02 07:51:33.971: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.971: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException
07-02 07:51:33.981: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.981: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException
07-02 07:51:33.991: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.991: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException

The path you are getting is not real path of the Image it is a Uri.If you want to set it it ImageView set it like
imageView.setImageURI(Uri.parse(imagePaths.get(position)));
or
get the Real path by passing your URI and set it to ImageView
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
For more check here Uri to path conversion

It causes because intent.getDataString() returns the uri string. Use intent.getData().getPath() instead.

Try this way,hope this will help you to solve your problem.
public String getAbsolutePath(Uri uri) {
if(Build.VERSION.SDK_INT >= 19){
String id = uri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA };
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}else{
return null;
}
}else{
String[] projection = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}

Your problem is in appObj.getQueuedPhotos- it isn't returning filenames, its returning URIs, decodeFile expects a path. You can, for this case, do a quick string manipulation and remove the content:/ from the front, but you're better off fixing the URIs in your getQueuedPhotos function

content://media/external/images/media/7496 is not the actual location of the stored file, but just the Uri, hence android can't find the file on the specified path. However, you can use the URI to get the absolute path of the file and use that path when decoding.
Use this method to the get the absolute path :
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
From : https://stackoverflow.com/a/3414749/1239966

Check for the inputstream, you are passing just a URI.
BitmapFactory.decodeFile(imagePaths.get(position));
Hence the file is not found, get the absolute path of the Image and pass it over.

Related

Use async task to modify element in a contact listview

i want to check if a phonenumber of my contacts is in a database.
So far i created a listview with a custom adapter and can display contact name, number and image. I added a fourth field that should display if the phonenumber is in the database.
i use asynctask to get a json like this {"android":{"error":"0"}} in case the number is in the database and to {"android":{"error":"1"}} if there is not.
my questions are how can i pass the phonenumber to the asynctask and what should the asynctask return so that the textview can be set to display "ok".
the code i use in all in one class.
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class contactos extends Activity {
ListView lv_addcontacts;
Cursor cur;
ContentResolver cr;
JSONArray android = null;
JSONParser jsonParser = new JSONParser();
private static String url = "my.php";
private static final String TAG_OS = "android";
private static final String TAG_ERROR = "error";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactos);
readContacts();
if (!((cur.moveToFirst()) || cur.equals(null) || cur.getCount() == 0)) {
} else if (cur.getCount() > 0) {
cur.moveToFirst();
}
lv_addcontacts = (ListView) findViewById(R.id.lv_addcontact);
CustomAdapterAddContacts myad = new CustomAdapterAddContacts();
lv_addcontacts.setAdapter(myad);
}
class CustomAdapterAddContacts extends BaseAdapter {
#Override
public int getCount() {
System.out.println(cur.getCount());
return cur.getCount();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ContactViewHolder contactViewHolder;
if (convertView == null) {
// Inflate the layout
LayoutInflater li = getLayoutInflater();
convertView = li.inflate(
R.layout.contactos_detalle, null);
contactViewHolder = new ContactViewHolder();
contactViewHolder.imgContact = (ImageView) convertView
.findViewById(R.id.imgView_addcontact);
contactViewHolder.txtViewContactName = (TextView) convertView
.findViewById(R.id.txtView_addcontact_contactname);
contactViewHolder.txtViewPhoneNumber = (TextView) convertView
.findViewById(R.id.txtview_addcontact_phonenumber);
contactViewHolder.txtViewCheck = (TextView) convertView
.findViewById(R.id.txtview_addcontact_check);
convertView.setTag(contactViewHolder);
} else {
contactViewHolder = (ContactViewHolder) convertView.getTag();
}
cur.moveToPosition(position);
// Add Contact Name //
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (name != null)
contactViewHolder.txtViewContactName.setText(name);
else
contactViewHolder.txtViewContactName.setText("Unknown");
// Add Phone Number //
String phoneNumber = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phoneNumber != null)
contactViewHolder.txtViewPhoneNumber.setText(phoneNumber);
else
contactViewHolder.txtViewPhoneNumber.setText("Unknown");
// start async task to check if phone number is in a database
// if the async task returns true contactViewHolder.txtViewPhoneCheck.setText("OK");
// if the async task returns false contactViewHolder.txtViewPhoneCheck.setText("NOT OK");
new JSONParse().execute(phoneNumber);
Uri uri = getPhotoUri(Long.parseLong(fetchContactIdFromPhoneNumber(phoneNumber)));
if (uri != null) {
contactViewHolder.imgContact.setImageURI(uri);
} else {
contactViewHolder.imgContact
.setImageResource(R.drawable.ic_launcher);
}
return convertView;
}
private String fetchContactIdFromPhoneNumber(String phoneNumber) {
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));
Cursor cFetch = getContentResolver().query(uri,
new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
null, null, null);
String contactId = "";
if (cFetch.moveToFirst()) {
cFetch.moveToFirst();
contactId = cFetch.getString(cFetch
.getColumnIndex(PhoneLookup._ID));
}
System.out.println(contactId);
return contactId;
}
public Uri getPhotoUri(long contactId) {
ContentResolver contentResolver = getContentResolver();
try {
Cursor cursor = contentResolver
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ contactId
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cursor != null) {
if (!cursor.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
return Uri.withAppendedPath(person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
public class ContactViewHolder {
ImageView imgContact;
TextView txtViewContactName;
TextView txtViewPhoneNumber;
TextView txtViewCheck;
}
}
private void readContacts() {
cr = getContentResolver();
cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
}
// async check if gcm
private class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
// is this the correct way to get the phoneNumber send in the execute
String phoneNumber = args[0];
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cel", phoneNumber));
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
JSONObject android = json.getJSONObject(TAG_OS);
String error = android.optString(TAG_ERROR);
if(Integer.parseInt(error) == 0){
// if the async task returns true contactViewHolder.txtViewPhoneCheck.setText("OK");
// return true;
}
if(Integer.parseInt(error) == 1){
// if the async task returns false contactViewHolder.txtViewPhoneCheck.setText("NOT OK");
// return false;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (cur != null) {
cur.close();
}
}
}
thanks for helping.
You are on the right track with:
new JSONParse().execute(phoneNumber);
Just make sure phoneNumber is a String.
is this the correct way to get the phoneNumber send in the execute
String phoneNumber = args[0];
Yes, that is the correct way. The first and only argument your AsyncTask accepts is phoneNumber and the index of String..args starts at 0
Now, in your onPostExecutemethod, am not conversant with the JSONObject class, but I think if:
if(Integer.parseInt(error) == 0)
and
if(Integer.parseInt(error) == 1){
return true, then you could go ahead to set the edittext as desired?

How to list all videos from specific folder in android

I am working on video recording application.I want to list the videos which I would be stored in particular folder.By the following code,I can able to fetch all videos from mobile.But i need to list the videos from particular folder.Can anyone guide me please.Thanks in Advance
public class VideoListActivity extends Activity {
private Cursor videocursor;
private int video_column_index;
ListView videolist;
int count;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_list);
init_phone_video_grid();
}
private void init_phone_video_grid() {
System.gc();
String[] proj = { MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.SIZE };
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.listView1);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
videolist.setOnItemClickListener(videogridlistener);
}
private OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
System.gc();
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videocursor.moveToPosition(position);
String filename = videocursor.getString(video_column_index);
Intent intent = new Intent(VideoListActivity.this, Viewvideo.class);
intent.putExtra("videofilename", filename);
startActivity(intent);
}
};
public class VideoAdapter extends BaseAdapter {
private Context vContext;
public VideoAdapter(Context c) {
vContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
TextView tv = new TextView(vContext.getApplicationContext());
String id = null;
if (convertView == null) {
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videocursor.moveToPosition(position);
id = videocursor.getString(video_column_index);
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videocursor.moveToPosition(position);
id += " Size(KB):" + videocursor.getString(video_column_index);
ImageView iv = new ImageView(vContext);
ContentResolver crThumb = getContentResolver();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, position, MediaStore.Video.Thumbnails.MICRO_KIND, options);
iv.setImageBitmap(curThumb);
tv.setText(id);
} else
tv = (TextView) convertView;
return tv;
}
}
}
Try the following code:
public static ArrayList<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files;
files = parentDir.listFiles();
if (files != null) {
for (File file : files) {
if (file.getName().endsWith(".mp4") ||
file.getName().endsWith(".gif")) {
if (!inFiles.contains(file)) inFiles.add(file);
if (!inFiles.contains(file)) inFiles.add(file);
}
}
}
return inFiles;
}
Use :
private static final String WHATSAPP_STATUSES_LOCATION =
"/storage/emulated/0/yourfoldername";
getListFiles(new File(WHATSAPP_STATUSES_LOCATION));
use this code :
package com.vt.soc;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
//set constants for MediaStore to query, and show videos
private final static Uri MEDIA_EXTERNAL_CONTENT_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private GridView _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
String filename;
int flag = 0;
protected Context _context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_context = getApplicationContext();
setContentView(R.layout.activity_main);
//set GridView for gallery
_gallery = (GridView) findViewById(R.id.videoGrdVw);
//set default as external/sdcard uri
_contentUri = MEDIA_EXTERNAL_CONTENT_URI;
initVideosId();
//set gallery adapter
setGalleryAdapter();
}
private void setGalleryAdapter() {
_gallery.setAdapter(new VideoGalleryAdapter(_context));
_gallery.setOnItemClickListener(_itemClickLis);
flag = 1;
}
private AdapterView.OnItemClickListener _itemClickLis = new OnItemClickListener()
{
#SuppressWarnings({ "deprecation", "unused", "rawtypes" })
public void onItemClick(AdapterView parent, View v, int position, long id)
{
// Now we want to actually get the data location of the file
String [] proj={MEDIA_DATA};
// We request our cursor again
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
MEDIA_DATA + " like ? ", // WHERE clause; which rows to return (all rows)
new String[] {"%Movies%"}, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
// We want to get the column index for the data uri
int count = _cursor.getCount();
//
_cursor.moveToFirst();
//
_columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
// Lets move to the selected item in the cursor
_cursor.moveToPosition(position);
// And here we get the filename
filename = _cursor.getString(_columnIndex);
//*********** You can do anything when you know the file path :-)
showToast(filename);
Intent i = new Intent(MainActivity.this, Player.class);
i.putExtra("videoPath", filename);
startActivity(i);
//
}
};
#SuppressWarnings("deprecation")
private void initVideosId() {
try
{
//Here we set up a string array of the thumbnail ID column we want to get back
String [] proj={_ID};
// Now we create the cursor pointing to the external thumbnail store
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
MEDIA_DATA + " like ? ", // WHERE clause; which rows to return (all rows)
new String[] {"%Movies%"}, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int count= _cursor.getCount();
// We now get the column index of the thumbnail id
_columnIndex = _cursor.getColumnIndex(_ID);
//initialize
_videosId = new int[count];
//move position to first element
_cursor.moveToFirst();
for(int i=0;i<count;i++)
{
int id = _cursor.getInt(_columnIndex);
//
_videosId[i]= id;
//
_cursor.moveToNext();
//
}
}catch(Exception ex)
{
showToast(ex.getMessage().toString());
}
}
protected void showToast(String msg)
{
Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
//
private class VideoGalleryAdapter extends BaseAdapter
{
public VideoGalleryAdapter(Context c)
{
_context = c;
}
public int getCount()
{
return _videosId.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imgVw= new ImageView(_context);;
try
{
if(convertView!=null)
{
imgVw= (ImageView) convertView;
}
imgVw.setImageBitmap(getImage(_videosId[position]));
imgVw.setLayoutParams(new GridView.LayoutParams(200, 200));
imgVw.setPadding(8, 8, 8, 8);
}
catch(Exception ex)
{
System.out.println("MainActivity:getView()-135: ex " + ex.getClass() +", "+ ex.getMessage());
}
return imgVw;
}
// Create the thumbnail on the fly
private Bitmap getImage(int id) {
Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(
getContentResolver(),
id, MediaStore.Video.Thumbnails.MICRO_KIND, null);
return thumb;
}
}
}
and add permission to manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
A bit late but posting for future viewers
Uri uri= MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String condition=MediaStore.Video.Media.DATA +" like?";
String[] selectionArguments=new String[]{"%FolderPath%"};
String sortOrder = MediaStore.Video.Media.DATE_TAKEN + " DESC";
String[] projection = { MediaStore.Images.Media._ID, MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri,projection, condition, selectionArguments, sortOrder);
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int pathColumn=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if(cursor!=null){
ContentResolver resolver = getApplicationContext().getContentResolver();
while(cursor3.moveToNext()){
String filePath=cursor.getString(pathColumn);
int id = cursor.getInt(idColumn );
Bitmap thumbNail = bitmap=MediaStore.Video.Thumbnails.getThumbnail(resolver, imageID,
MediaStore.Video.Thumbnails.MICRO_KIND, null);
}
}
use this code`
String path = Environment.getExternalStorageDirectory().toString()+"/Your Folder/";`
File f = new File(path);
File file[] = f.listFiles();
for (int i=0; i < file.length; i++)
{
Log.d("Files", "FileName:" + file[i].getName());
}
above code give you all file from the folder ,after you can separate
using it's extension

how to show thumbimage in gridview from sdcard

iam using following code it is not displaying thumb image in gridview but displaying in emulator pls suggest me how to show thumb image in gridview from sdcard
String[] projection = {MediaStore.Images.Media._ID};
final String orderBy = MediaStore.Images.Media._ID+" DESC";
// Create the cursor pointing to the SDCard
Cursor cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
orderBy);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int size = cursor.getCount();
// If size is 0, there are no images on the SD Card.
if (size == 0) {
//No Images available, post some message to the user
}
int imageID = 0;
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
imageID = cursor.getInt(columnIndex);
uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 86, 96, true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}
Try this code, it will work
package com.video;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class StartActivity extends Activity {
//set constants for MediaStore to query, and show videos
private final static Uri MEDIA_EXTERNAL_CONTENT_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private GridView _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
protected Context _context;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_context = getApplicationContext();
setContentView(R.layout.main);
//set GridView for gallery
_gallery = (GridView) findViewById(R.id.videoGrdVw);
//set default as external/sdcard uri
_contentUri = MEDIA_EXTERNAL_CONTENT_URI;
//initialize the videos uri
//showToast(_contentUri.getPath());
initVideosId();
//set gallery adapter
setGalleryAdapter();
}
private void setGalleryAdapter() {
_gallery.setAdapter(new VideoGalleryAdapter(_context));
_gallery.setOnItemClickListener(_itemClickLis);
}
private AdapterView.OnItemClickListener _itemClickLis = new OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v, int position, long id)
{
// Now we want to actually get the data location of the file
String [] proj={MEDIA_DATA};
// We request our cursor again
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
// We want to get the column index for the data uri
int count = _cursor.getCount();
//
_cursor.moveToFirst();
//
_columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
// Lets move to the selected item in the cursor
_cursor.moveToPosition(position);
// And here we get the filename
String filename = _cursor.getString(_columnIndex);
//*********** You can do anything when you know the file path :-)
showToast(filename);
//
}
};
private void initVideosId() {
try
{
//Here we set up a string array of the thumbnail ID column we want to get back
String [] proj={_ID};
// Now we create the cursor pointing to the external thumbnail store
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int count= _cursor.getCount();
// We now get the column index of the thumbnail id
_columnIndex = _cursor.getColumnIndex(_ID);
//initialize
_videosId = new int[count];
//move position to first element
_cursor.moveToFirst();
for(int i=0;i<count;i++)
{
int id = _cursor.getInt(_columnIndex);
//
_videosId[i]= id;
//
_cursor.moveToNext();
//
}
}catch(Exception ex)
{
showToast(ex.getMessage().toString());
}
}
protected void showToast(String msg)
{
Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
//
private class VideoGalleryAdapter extends BaseAdapter
{
public VideoGalleryAdapter(Context c)
{
_context = c;
}
public int getCount()
{
return _videosId.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imgVw= new ImageView(_context);;
try
{
if(convertView!=null)
{
imgVw= (ImageView) convertView;
}
imgVw.setImageBitmap(getImage(_videosId[position]));
imgVw.setLayoutParams(new GridView.LayoutParams(96, 96));
imgVw.setPadding(8, 8, 8, 8);
}
catch(Exception ex)
{
System.out.println("StartActivity:getView()-135: ex " + ex.getClass() +", "+ ex.getMessage());
}
return imgVw;
}
// Create the thumbnail on the fly
private Bitmap getImage(int id) {
Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(
getContentResolver(),
id, MediaStore.Video.Thumbnails.MICRO_KIND, null);
return thumb;
}
}
}

Display All Song From the SD card Genre Wise

I am Doing Musicplayer Application. and want to show All the Songs with respect to its Genre. if possible then please give me some hint for that. i able to display all the Song With Respect to Artist and Album but Facing Problem While Going For Genre Wise Song. my out put is displaying all the Songs in Each genre catagory. it is not saprating the Song According to genre. Mycode is Below.
LocalGenre.java
package com.PageViewerTilesDemo.src;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Window;
import android.widget.ExpandableListView;
import android.widget.TextView;
public class LocanGenre extends Activity {
ExpandableListView listLocalArtists;
TextView txttitle;
Cursor musiccursor, musiccursor1;
int music_column_index, music_column_index1;
int count, count1;
ArrayList<String> genresName = new ArrayList<String>();
ArrayList<String> genreID = new ArrayList<String>();
ArrayList<Integer> albumID = new ArrayList<Integer>();
ArrayList<String> numberOFSongs = new ArrayList<String>();
ArrayList<String> artistName = new ArrayList<String>();
ArrayList<String> path = new ArrayList<String>();
ArrayList<String> path12 = new ArrayList<String>();
ArrayList<ArrayList<String>> pathDisplay = new ArrayList<ArrayList<String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.localartists);
txttitle = (TextView) findViewById(R.id.title);
txttitle.setText("Genres");
listLocalArtists = (ExpandableListView) findViewById(R.id.listView1);
init_phone_music_grid();
listLocalArtists.setAdapter(new ExpandableListGenreAdapter(this, path, genresName,
genresName, pathDisplay,albumID));
}
private void init_phone_music_grid() {
// TODO Auto-generated method stub
System.gc();
String[] proj = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.ALBUM_ID};
musiccursor1 = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null,
null);
count1 = musiccursor1.getCount();
if (count1 > 0) {
musiccursor1.moveToFirst();
do {
music_column_index1 = musiccursor1
.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
String filename0 = musiccursor1.getString(music_column_index1);
path.add(filename0);
Log.i("LocalGenres ", "Path Main" + path);
music_column_index1 = musiccursor1
.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
String filename123 = musiccursor1
.getString(music_column_index1);
path12.add(filename123);
Log.i("LocalGenre", "Media ID " + path12);
music_column_index1 = musiccursor1
.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
int filename1 = musiccursor1.getInt(music_column_index1);
albumID.add(filename1);
Log.i("LOCAL Genres!!!", " ALBUM ID" + albumID);
} while (musiccursor1.moveToNext());
}
String[] projection = { MediaStore.Audio.Genres._ID,
MediaStore.Audio.Genres.NAME};
musiccursor = managedQuery(
MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, projection, null,
null, null);
genresName.clear();
count = musiccursor.getCount();
if (count > 0) {
musiccursor.moveToFirst();
do {
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
String filename = musiccursor.getString(music_column_index);
if(!genreID.contains(filename))
{
genreID.add(filename);
}
Log.i("Local Genres ", "Genre ID" + genreID);
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
String filename1 = musiccursor.getString(music_column_index);
if(!genresName.contains(filename1))
{
genresName.add(filename1);
}
Log.i("Local Genres ", "Genres Name " + genresName);
/*
* music_column_index = musiccursor
* .getColumnIndexOrThrow(MediaStore.Audio.Genres._COUNT);
*
* String filename3 = musiccursor.getString(music_column_index);
* artistName.add(filename3);
*
* Log.i("Local Albums ", "Album ID for Gen " + artistName);
*/
} while (musiccursor.moveToNext());
}
for (int j = 0; j < genreID.size(); j++) {
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i < path12.size(); i++) {
Log.i("EEEEEE", "Inside If path12.get(i) :"+path12.get(i));
Log.i("EEEEEE", "Inside If genreID.get(j) :"+genreID.get(j));
Log.i("EEEEEE", "Inside If Integer.parseInt(path12.get(i)) :"+Integer.parseInt(path12.get(i)));
Log.i("EEEEEE", "Inside If j : "+j);
if (path12.get(i).equalsIgnoreCase(genreID.get(j)) || Integer.parseInt(path12.get(i))>j) {
Log.i("EEEEEE", "Inside If");
arr.add(path.get(i));
}
else
Log.i("xxxxxxx", "Inside else");
arr.add(path.get(i));
}
Log.i("EEEEEE", "Inside outerloop " + arr);
pathDisplay.add(arr);
}
}
}
ExpandableListGenreAdapter.java
package com.PageViewerTilesDemo.src;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ExpandableListGenreAdapter extends BaseExpandableListAdapter{
private Context context;
private ArrayList<String> artist;
private ArrayList<String> genres;
private ArrayList<ArrayList<String>> children;
public ArrayList<String> pathmain ;
public ArrayList<Integer> genresID;
public ArrayList<Integer> albumID;
public ExpandableListGenreAdapter(Context context, ArrayList<String> path, ArrayList<String> groups,ArrayList<String> artist,
ArrayList<ArrayList<String>> children, ArrayList<Integer> albumID) {
this.context = context;
this.genres = groups;
this.artist = artist;
this.pathmain = path;
this.children = children;
this.albumID=albumID;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return children.get(groupPosition).get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
/*public Bitmap getAlbumart(int album_id)
{
Bitmap bm = null;
try
{
final Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
ParcelFileDescriptor pfd = context.getContentResolver()
.openFileDescriptor(uri, "r");
if (pfd != null)
{
FileDescriptor fd = pfd.getFileDescriptor();
bm = BitmapFactory.decodeFileDescriptor(fd);
}
} catch (Exception e) {
}
return bm;
}*/
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final String vehicle = (String) getChild(groupPosition, childPosition);
Log.i("ExpandableListAdapter", "Group Position "+groupPosition);
Log.i("ExpandableListAdapter", "Vehicle "+vehicle);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.tvChild);
ImageView imageview1=(ImageView)convertView.findViewById(R.id.ImageView01);
// bm=getAlbumart(albumids.get(1));
// Log.i("LIST ADAPTER","###################ALBUM IDS "+albumids.get(0)+"BITMAPPPPP###"+bm);
// imageview1.setImageBitmap(coverart.get(childPosition));
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.flag = true;
TestFragment3.flag = true;
Firstpage.flag = true;
Log.i("ExpandableListGenreAdapter", "path "+childPosition);
MainActivity.currentPosition = groupPosition;
Log.i("ExpandableListGenreAdapter", "currentPosition "+MainActivity.currentPosition);
MainActivity.genre=true;
MainActivity.currentgenreposition = albumID.get(childPosition);
Log.i("ExpandableListGenreAdapter", "currentGenrePosition "+MainActivity.currentgenreposition);
MainActivity.Media_full_path = "/sdcard/"+vehicle;
Log.i("ExpandableListAdapter", "Onclick "+MainActivity.Media_full_path);
((Activity)context).finish();
}
});
tv.setText(" " + vehicle.toString());
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return children.get(groupPosition).size();
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return genres.get(groupPosition);
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return genres.size();
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String group = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_layout, null);
}
TextView txtArtistsName = (TextView) convertView.findViewById(R.id.txtArtistsName);
TextView txtartistssongs = (TextView) convertView.findViewById(R.id.txtartistssongs);
txtArtistsName.setText(group);
txtartistssongs.setText(genres.get(groupPosition)+" Song(s)");
return convertView;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
Please Suggest me Where is i am missing from the Above Code. Thank You.
Hi hope this will help you. It displays the genres and their songs.
int index;
long genreId;
Uri uri;
Cursor genrecursor;
Cursor tempcursor;
String[] proj1 = {MediaStore.Audio.Genres.NAME, MediaStore.Audio.Genres._ID};
String[] proj2 = {MediaStore.Audio.Media.DISPLAY_NAME};
genrecursor = managedQuery(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, proj1, null, null, null);
if (genrecursor.moveToFirst()) {
do {
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
Log.i("Tag-Genre name", genrecursor.getString(index));
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
genreId = Long.parseLong(genrecursor.getString(index));
uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);
tempcursor = managedQuery(uri, proj2, null,null,null);
Log.i("Tag-Number of songs for this genre", tempcursor.getCount() + "");
if (tempcursor.moveToFirst()) {
do {
index = tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
Log.i("Tag-Song name", tempcursor.getString(index));
} while(tempcursor.moveToNext());
}
} while(genrecursor.moveToNext());
}
I updated the answer of #Abhijeet for work with old versions
public void getGenres(int total) {
int index;
long genreId;
Uri uri;
Cursor genrecursor;
Cursor tempcursor;
String[] proj1 = {MediaStore.Audio.Genres.NAME, MediaStore.Audio.Genres._ID};
String[] proj2={MediaStore.Audio.Media.DISPLAY_NAME};
String result;
genrecursor = MyApplication.getAppContext().getContentResolver().query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, proj1, null, null, null);
ArrayList<Genre> genres = new ArrayList<Genre>();
Genre genre = null;
if (genrecursor!=null && genrecursor.moveToFirst()) {
do {
genre = new Genre();
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
if (BuildConfig.DEBUG) Log.i("Tag-Genre name", genrecursor.getString(index));
genre.setName(genrecursor.getString(index));
if(genre.getName().equalsIgnoreCase("")) {
genre.setName("no-genre");
}
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
genreId = Long.parseLong(genrecursor.getString(index));
uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);
tempcursor = MyApplication.getAppContext().getContentResolver().query(uri, proj2, null, null, null);
if (BuildConfig.DEBUG) Log.i("Tag-Number of songs for this genre", tempcursor.getCount()+"");
genre.setNumberSongs( tempcursor.getCount());
if (!genres.contains(genre)) {
genres.add(genre);
}
if (tempcursor.moveToFirst()) {
do {
index = tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
if (BuildConfig.DEBUG) Log.i("Tag-Song name", tempcursor.getString(index));
for(int i = 0;i<songs.size();i++) {
if (BuildConfig.DEBUG) Log.i("SONG", songs.get(i).getDisplayName()+ " - "+ tempcursor.getString(index));
if (tempcursor!=null && songs!=null && tempcursor.getString(index).equalsIgnoreCase(songs.get(i).getDisplayName()) ) {
songs.get(i).setGenre(genre.getName());
if (genre.isOldVersion()) {
genre.setNumberSongs(genre.getNumberSongs()+1);
}
if (genre.getNumberSongs()==0) { //Is an oldversion of android, less than 3.0
genre.setOldVersion(true);
genre.setNumberSongs(1);
}
}
}
} while(tempcursor.moveToNext());
}
} while(genrecursor.moveToNext());
}
orderList(genres);
result = "";
for(int i = 0; i < 10 && i<genres.size() ;i++) {
result += genres.get(i).toString()+",";
}
result += "Total:"+total;
}

Fetch contact photo in android gives null

I want to fetch the photo of the contact while a user enters number.By using phone number i am getting users name but for image it shows null.
my code is following :
public class NewtempActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final EditText edit = (EditText) findViewById(R.id.editText1);
TextView txt = (TextView) findViewById(R.id.textView1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Girish", "Clicked");
String name = getContactNameFromNumber(edit.getText()
.toString(), getApplicationContext());
img.setImageBitmap(BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID));
Log.d("Girish",
""
+ (BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID)));
Toast.makeText(getApplicationContext(), name, name.length())
.show();
}
});
}
public String getContactNameFromNumber(String number, Context ctx) {
/*
* // define the columns I want the query to return String[] projection
* = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
* ContactsContract.PhoneLookup.NUMBER, };
*/
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
// Cursor c = ctx.getContentResolver().query( contactUri, projection,
// null,
Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
return name;
}
// return the original number if no match was found
return number;
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
// InputStream input = ContactsContract.Contacts.Photo
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
Uri photoUri = Uri.withAppendedPath(contactUri,
Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri, null, null, null,
null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
}
please suggest me where i am doing wrong.I have added read contact permission also
by going through your code i came to know like You are trying to get the contact name from the number. and using that you want the contact image.. but you never called the functions which you made for the contact pic..:).. so what you can do is take id from the contact number and take photo on that id. so you will get the photo for the number..
package com.android.SampleProject;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class NewtempActivity extends Activity {
private long id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final EditText edit = (EditText) findViewById(R.id.editText1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("Girish", "Clicked");
String name = getContactNameFromNumber(edit.getText()
.toString(), getApplicationContext());
img.setImageBitmap(BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID));
img.setImageBitmap(loadContactPhoto(getContentResolver(), id));
Log.d("Girish",
""
+ (BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID)));
Toast.makeText(getApplicationContext(), name, name.length())
.show();
}
});
}
public String getContactNameFromNumber(String number, Context ctx) {
/*
* // define the columns I want the query to return String[] projection
* = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
* ContactsContract.PhoneLookup.NUMBER, };
*/
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
// Cursor c = ctx.getContentResolver().query( contactUri, projection,
// null,
Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
id = c.getLong(c
.getColumnIndex(ContactsContract.PhoneLookup._ID));
return name;
}
// return the original number if no match was found
return number;
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
// InputStream input = ContactsContract.Contacts.Photo
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
Uri photoUri = Uri.withAppendedPath(contactUri,
Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri, null, null, null,
null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
}

Categories

Resources