recyclerview footer click to load images - android

I'm trying to achieve some thing like the image below. Here when recyclerview is empty it will show the camera imageview in footer and when I click on the image, I can select image from camera or gallery (which will be saved in an internal storage folder) and display them in recyclerview. But I'm getting ArrayIndexOutOfBoundsException in onBindViewHolder in case 1. How to display images from internal folder?
java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1
at java.util.ArrayList.get(ArrayList.java:413)
at com.sam.testapp.ImageAdapter.onBindViewHolder(ImageAdapter.java:85)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6279)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6312)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5258)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5521)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5363)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5359)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2141)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1525)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1488)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:585)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3506)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2969)
// Activity
public class MainActivity extends AppCompatActivity{
Toolbar toolbar;
RecyclerView recycler;
ImageAdapter adapter;
private ArrayList<Object> itemList;
String[] items = new String [] {"http://i.imgur.com/7P2v384.jpg", "http://i.imgur.com/Fb95GwC.jpg", "http://i.imgur.com/qciJxBg.jpg","http://i.imgur.com/h2jgdAd.jpg"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recycler = (RecyclerView)findViewById(R.id.recycler);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, OrientationHelper.HORIZONTAL, false);
recycler.setLayoutManager(linearLayoutManager);
recycler.setItemAnimator(new DefaultItemAnimator());
adapter = new ImageAdapter(MainActivity.this, itemList);
recycler.setAdapter(adapter);
//Collections.addAll(itemList, items);
itemList = new ArrayList<Object>(Arrays.asList(items));
itemList.add(1);
}
}
// Adapter
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private static final int TYPE_FOOTER = 0;
private static final int TYPE_ITEM = 1;
final CharSequence[] items = {
"Camera", "Gallery", "Cancel"
};
private ArrayList<Object> finalImages = new ArrayList<>();
private static final String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TESTAPP";
public ImageAdapter(Context context, ArrayList<Object> itemList) {
this.finalImages = itemList;
this.mContext = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case 0:
View v0 = LayoutInflater.from(parent.getContext()).inflate(R.layout.customrowlayout, parent, false);
viewHolder = new VHFooter(v0);
break;
case 1:
View v1 = inflater.inflate(R.layout.imagerowlayout, parent, false);
viewHolder = new VHItem(v1);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0:
VHFooter vh0 = (VHFooter) holder;
vh0.imgv.setImageResource(R.drawable.camera);
vh0.imgv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
break;
case 1:
VHItem vh1 = (VHItem) holder;
String path = (String) finalImages.get(position);
if (!TextUtils.isEmpty(path)) {
Picasso.with(mContext).load(path).into(vh1.image);
}
break;
}
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
((Activity) mContext).startActivityForResult(intent, 0);
dialog.dismiss();
} else if (item == 1) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
((Activity) mContext).startActivityForResult(intent, 1);
dialog.dismiss();
} else if (item == 2) {
dialog.dismiss();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 0) {
savefile(data, true);
loadfile();
} else if (resultCode == RESULT_OK && requestCode == 1) {
savefile(data, false);
loadfile();
}
}
private void savefile(Intent data, boolean isCamera) {
if (isCamera) {
Bitmap bmap = (Bitmap) data.getExtras().get("data");
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, "myimage.jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Uri uri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bmap = (BitmapFactory.decodeFile(picturePath));
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ENGLISH).format(new Date());
File file = new File(directory, "IMG_" + timeStamp + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void loadfile() {
File directory = new File(file_path);
File newfile[] = directory.listFiles();
Log.e("sammy_arrlistsize_befor", " " + finalImages.size());
if (finalImages != null) finalImages.clear();
for (int i = 0; i < newfile.length; i++) {
String path = "file://" + newfile[i].getAbsolutePath();
finalImages.add(path);
Log.e("sammy_imagepath", " " + path);
}
Log.e("sammy_arrlistsize_after", " " + finalImages.size());
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return this.finalImages.size();
}
#Override
public int getItemViewType(int position) {
if (finalImages.get(position) instanceof String) {
return TYPE_ITEM;
} else if (finalImages.get(position) instanceof Integer) {
return TYPE_FOOTER;
}
return -1;
}
class VHItem extends RecyclerView.ViewHolder {
ImageView image;
public VHItem(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
}
}
class VHFooter extends RecyclerView.ViewHolder {
ImageView imgv;
public VHFooter(View itemView) {
super(itemView);
imgv = (ImageView) itemView.findViewById(R.id.imgv);
}
}
}

First in MainActivity
private ArrayList<Object> itemList = new ArrayList<>();
itemList.addAll(yourStringList);
itemList.add(1);
then use below adapter class
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private static final int TYPE_FOOTER = 0;
private static final int TYPE_ITEM = 1;
final CharSequence[] items = {
"Camera", "Gallery", "Cancel"
};
private ArrayList<Object> finalImages = new ArrayList<>();
private static final String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TESTAPP";
public ImageAdapter(Context context, ArrayList<Object> itemList) {
this.finalImages = itemList;
this.mContext = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case 0:
View v0 = LayoutInflater.from(parent.getContext()).inflate(R.layout.customrowlayout, parent, false);
viewHolder = new VHFooter(v0);
break;
case 1:
View v1 = inflater.inflate(R.layout.imagerowlayout, parent, false);
viewHolder = new VHItem(v1);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0:
VHFooter vh0 = (VHFooter) holder;
vh0.imgv.setImageResource(R.drawable.camera);
// Picasso.with(mContext).load(R.drawable.camera).into(vh0.imgv);
//piccaso is commented for now
vh0.imgv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
break;
case 1:
VHItem vh1 = (VHItem) holder;
String path = (String) finalImages.get(position);
if (!TextUtils.isEmpty(path)) {
Picasso.with(mContext).load(path).into(vh1.image);
}
break;
}
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
((Activity) mContext).startActivityForResult(intent, 0);
dialog.dismiss();
} else if (item == 1) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
((Activity) mContext).startActivityForResult(intent, 1);
dialog.dismiss();
} else if (item == 2) {
dialog.dismiss();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 0) {
savefile(data, true);
loadfile();
} else if (resultCode == RESULT_OK && requestCode == 1) {
savefile(data, false);
loadfile();
}
}
private void savefile(Intent data, boolean isCamera) {
if (isCamera) {
Bitmap bmap = (Bitmap) data.getExtras().get("data");
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, "myimage.jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Uri uri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bmap = (BitmapFactory.decodeFile(picturePath));
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ENGLISH).format(new Date());
File file = new File(directory, "IMG_" + timeStamp + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void loadfile() {
File directory = new File(file_path);
File newfile[] = directory.listFiles();
Log.e("sammy_arrlistsize_befor", " " + finalImages.size());
if (finalImages != null) finalImages.clear();
for (int i = 0; i < newfile.length; i++) {
String path = "file://" + newfile[i].getAbsolutePath();
finalImages.add(path);
Log.e("sammy_imagepath", " " + path);
}
Log.e("sammy_arrlistsize_after", " " + finalImages.size());
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return this.finalImages.size();
}
#Override
public int getItemViewType(int position) {
if (finalImages.get(position) instanceof String) {
return TYPE_ITEM;
} else if (finalImages.get(position) instanceof Integer) {
return TYPE_FOOTER;
}
return -1;
}
class VHItem extends RecyclerView.ViewHolder {
ImageView image;
public VHItem(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
}
}
class VHFooter extends RecyclerView.ViewHolder {
ImageView imgv;
public VHFooter(View itemView) {
super(itemView);
imgv = (ImageView) itemView.findViewById(R.id.imgv);
}
}
}

Your exception is being thrown because
#Override
public int getItemCount() {
return this.finalImages.size()+1;
}
should be
#Override
public int getItemCount() {
return this.finalImages.size();
}

Related

How can I update Gallery After a Photo had been taken?

I created a program to capture a photo but when i look at it in the Photo Gallery it does not appear immediately.
I Already used the command provided in the other questions in this site which is similar to this Code:
"sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));"
this is my entire code:
enter code here
public class PicturesActivity extends AppCompatActivity {
public static final int REQUEST_TAKE_PHOTO = 1;
public static final String ACCOUNTNUM = "AccountNum";
public static final String METERNO = "MeterNo";
public static final int CAMERA_PERMISSION_REQUEST_CODE = 4192;
private static final String ALBUM_NAME = "DailySelfie";
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String CAMERA_DIR = "/dcim/";
public static final String FILE_PATH_EXTRA = "image_currentPath";
private static final long INITIAL_ALARM_DELAY = 2 * 60 * 1000L;
public static final int REQUEST_CODE = 228;
private static final int CAMERA_REQUEST_CODE = REQUEST_CODE;
private ImageAdapter imageAdapter = null;
private String mCurrentPhotoPath = null;
private File capturedImage;
private AlarmManager alarmManager;
private Intent notificationReceiverIntent;
private PendingIntent notificationReceiverPendingIntent;
private ListView pictureList;
private SearchView searchText;
private File pictureFile;
private int pictureCounter = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pictures);
this.pictureList = (ListView) findViewById(R.id.picture_list);
this.searchText = (SearchView) findViewById(R.id.edit_image_search);
this.alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
this.imageAdapter = new ImageAdapter(getApplicationContext());
notificationReceiverIntent = new Intent(PicturesActivity.this, SelfieBroadCastReceiver.class);
notificationReceiverPendingIntent = PendingIntent.getBroadcast(PicturesActivity.this, 0, notificationReceiverIntent, 0);
getSupportActionBar();
this.pictureList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ImageRecord imageRecord = imageAdapter.getItem(position);
Intent picDetailIntent = new Intent(getApplicationContext(), PictureDetailActivity.class);
picDetailIntent.putExtra(FILE_PATH_EXTRA, imageRecord.getFullPath());
startActivity(picDetailIntent);
}
});
this.searchText.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//imageAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
imageAdapter.getFilter().filter(newText);
return false;
}
});
try {
this.pictureList.setAdapter(imageAdapter);
}catch (Exception e){
Toast.makeText(getApplication(),e.toString(),Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
renameFile(this.capturedImage);
}
}
#Override
protected void onResume() {
super.onResume();
this.setUpPicList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pictures_menu, menu);
return true;
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.show_camera:
if(checkSelfPermission(Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED){
try {
dispatchTakePictureIntent();
}catch (IOException e){}
}else{
String[] permissionRequest = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissionRequest, CAMERA_PERMISSION_REQUEST_CODE);
}
return true;
case R.id.set_alarm:
setAlarm();
return true;
case R.id.cancel_alarm:
cancelAlarm();
return true;
default:
return false;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==CAMERA_PERMISSION_REQUEST_CODE){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED & grantResults[1]== PackageManager.PERMISSION_GRANTED){
try {
dispatchTakePictureIntent();
}catch(IOException e){}
}else{
viewSnackBar(getString(R.string.camera_needed_permission));
}
}
}
private void dispatchTakePictureIntent() throws IOException{
pictureFile = createImageFiles();
Uri uriFile = FileProvider.getUriForFile(this, getApplicationContext().getPackageName()+ ".provider", pictureFile);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,uriFile);
takePictureIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(pictureFile)));
scanMedia(pictureFile.toString());
}
private File createImageFiles() {
SharedPreferences prefs = getSharedPreferences(ACCOUNTNUM, MODE_PRIVATE);
SharedPreferences meterNum = getSharedPreferences(METERNO, MODE_PRIVATE);
final String accountNumber = prefs.getString("accountNum", null);
final String MeterNumber = meterNum.getString("MeterNo", null);
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile = new File(picturesDirectory, accountNumber + "-" + MeterNumber.trim() + "-"+ pictureCounter + ".JPG");
pictureCounter++;
return imageFile;
}
private void scanMedia(String path) {
File file = new File(path);
Uri uri = Uri.fromFile(file);
Intent scanFileIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
sendBroadcast(scanFileIntent);
}
public void viewSnackBar(String message){
View parentLayout = findViewById(android.R.id.content);
Snackbar.make(parentLayout, message, Snackbar.LENGTH_LONG).show();
}
private void renameFile(File file) {
SharedPreferences prefs = getSharedPreferences(ACCOUNTNUM, MODE_PRIVATE);
final String accountNumber = prefs.getString("accountNum", null);
final Dialog dialog = new Dialog(PicturesActivity.this);
dialog.setContentView(R.layout.file_prompt);
final EditText editText = (EditText) dialog.findViewById(R.id.editTextDialogUserInput);
final Button button = (Button) dialog.findViewById(R.id.saveButton);
final File oldFile = file;
try {
editText.setText(accountNumber);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(editText.getText().toString())) {
String fileName = editText.getText().toString().toLowerCase() + "-";
try {
File newFile = File.createTempFile(fileName, JPEG_FILE_SUFFIX, getAlbumDir());
oldFile.renameTo(newFile);
setUpPicList();
dialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
dialog.show();
}catch (Exception e){
Toast.makeText(getApplication(), e.toString(),Toast.LENGTH_SHORT).show();
}
}
private File getAlbumDir(){
File storageDir = null;
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
storageDir = getAlbumStorageDir();
if(storageDir != null){
if(!storageDir.mkdirs()){
if(!storageDir.exists()){
Log.d("DailySelfie", "Failed to create directory");
return null;
}
}
}
} else {
Log.v("DailySelfie", "External Storage is not mounted READ/WRITE");
}
return storageDir;
}
///*************************
private File getAlbumStorageDir(){
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return picturesDirectory;
//return new File(Environment.getExternalStorageDirectory() + CAMERA_DIR + ALBUM_NAME);
}
private void galleryAddPic(){
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File file = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void setUpPicList(){
imageAdapter.removeAllViews();
File albumFile = getAlbumDir();
if(albumFile.isDirectory() && albumFile.exists()){
File[] files = albumFile.listFiles();
for(File file : files){
ImageRecord imageRecord = new ImageRecord(file);
imageAdapter.add(imageRecord);
}
}
}
}

Fragment Upload Image to ImageButton

I have tried many different approaches but none of them seem to help, so the problem is the following:
Image isn't uploading to imageButton. I have the path and I have checked it via debugger, added some Toasts to that the fragment gets to the onActivityResult and it does, but the image isn't uploading. Any ideas?
public class AddProductFragment extends Fragment {
private static final String TAG = "AddProductFragment";
private static final int GALLERY_INTENT = 2;
private Uri imageUri;
private ImageButton imageButton;
private EditText productName,produtPrice,productDescription;
private Button btnCancel,btnAdd;
private FirebaseDatabase mDb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDb = FirebaseDatabase.getInstance();
}
private void onClickEvents() {
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i,"Select Picture"),GALLERY_INTENT);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO: Edit this;
String name = productName.getText().toString();
String price = produtPrice.getText().toString();
String description = productDescription.getText().toString();
DatabaseOperation dbOps = new DatabaseOperation(mDb,getContext());
dbOps.AddProduct(imageUri,name,price,description);
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO: exit fragment
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_product, container, false);
imageButton = (ImageButton) v.findViewById(R.id.imageButton2);
productName = (EditText)v.findViewById(R.id.addProduct_productName);
produtPrice = (EditText)v.findViewById(R.id.addProduct_productPrice);
productDescription = (EditText)v.findViewById(R.id.addProduct_productDescription);
btnAdd = (Button) v.findViewById(R.id.addProduct_addBtn);
btnCancel = (Button) v.findViewById(R.id.addProduct_cancelBtn);
onClickEvents();
return v;
}
public Bitmap getBitmap(String path) {
Bitmap bitmap = null;
try {
File f = new File(path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
imageButton.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bitmap;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(AddProductFragment.this.getActivity(), "Number 1", Toast.LENGTH_SHORT).show();
if(requestCode == GALLERY_INTENT){
Toast.makeText(AddProductFragment.this.getActivity(), "Number 2", Toast.LENGTH_SHORT).show();
if(resultCode == Activity.RESULT_OK) {
Toast.makeText(AddProductFragment.this.getActivity(), "Number 3", Toast.LENGTH_SHORT).show();
String path = getPathFromCameraData(data, this.getActivity());
Toast.makeText(AddProductFragment.this.getActivity(), "Uploading", Toast.LENGTH_SHORT).show();
if (path != null) {
setFullImageFromFilePath( path);
Toast.makeText(AddProductFragment.this.getActivity(), "Uploaded", Toast.LENGTH_SHORT).show();
}
}
}
}
public void setFullImageFromFilePath( String imgPath) {
// btn.setImageBitmap(BitmapFactory.decodeFile(imgPath));
getBitmap(imgPath);
}
public static String getPathFromCameraData(Intent data, Context ctx) {
Uri selectedImage = data.getData();
String[] pathToFile = {MediaStore.Images.Media.DATA};
Cursor cursor = ctx.getContentResolver().query(selectedImage, pathToFile, null,
null, null);
if(cursor == null) return null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(pathToFile[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return picturePath;
}
}
case GALLERY_INTENT:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageURI(selectedImage);// To display selected image in image view
}

OnClick goto new Activity in GridView Android

I take a photo from the camera and store them in a GridView, now when i view them there is no OnClick function to Enlarge or Goto new Activity to Enlarge the selected image, Here's the code:
Where to implement the OnClick method to take the selected image to a new Activity and enlarge it
package com.example.veeresh.myphotogallery;
public class Photo_1 extends AppCompatActivity implements OnClickListener {
Button captureBtn = null;
final int CAMERA_CAPTURE = 1;
private Uri picUri;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private GridView grid;
private List<String> listOfImagesPath;
private String path;
private String pathMusic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
int pos = 0;
path = " ";
pathMusic = getIntent().getStringExtra("Store to Music");
if(pathMusic != null)
{
path = pathMusic;
}
captureBtn = (Button) findViewById(R.id.capture_btn1);
captureBtn.setOnClickListener(this);
grid = (GridView) findViewById(R.id.gridviewimg);
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if (listOfImagesPath != null) {
grid.setAdapter(new ImageListAdapter(this, listOfImagesPath));
}
}
#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 void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0.getId() == R.id.capture_btn1) {
try {
//use standard intent to capture an image
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//we will handle the returned data in onActivityResult
Toast.makeText(this, "Launching Camera", Toast.LENGTH_SHORT).show();
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
//display an error message
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
//user is returning from capturing an image using the camera
if (requestCode == CAMERA_CAPTURE) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
String imgcurTime = dateFormat.format(new Date());
File imageDirectory = new File(path);
imageDirectory.mkdirs();
String _path = path + imgcurTime + ".jpg";
try {
FileOutputStream out = new FileOutputStream(_path);
thePic.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (FileNotFoundException e) {
e.getMessage();
} catch (IOException e) {
e.printStackTrace();
}
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if (listOfImagesPath != null) {
grid.setAdapter(new ImageListAdapter(this, listOfImagesPath));
}
}
}
}
private List<String> RetriveCapturedImagePath() {
List<String> tFileList = new ArrayList<String>();
File f = new File(path);
if (f.exists()) {
File[] files = f.listFiles();
Arrays.sort(files);
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory())
continue;
tFileList.add(file.getPath());
}
}
return tFileList;
}
public class ImageListAdapter extends BaseAdapter {
private Context context;
private List<String> imgPic;
public ImageListAdapter(Context c, List<String> thePic) {
context = c;
imgPic = thePic;
}
public int getCount() {
if (imgPic != null)
return imgPic.size();
else
return 0;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; //Disable Dithering mode
bfOptions.inPurgeable = true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable = true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage = new byte[32 * 1024];
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
FileInputStream fs = null;
Bitmap bm;
try {
fs = new FileInputStream(new File(imgPic.get(position).toString()));
if (fs != null) {
bm = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
imageView.setImageBitmap(bm);
imageView.setId(position);
imageView.setLayoutParams(new GridView.LayoutParams(300, 600));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fs != null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageView;
}
}
}
Use setOnItemClickListener of girdview.
grid = (GridView) findViewById(R.id.gridviewimg);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(this, "you clicked at : " + position, Toast.LENGTH_LONG).show();
// put your intent here to open activity
}
});
put this code inside your onCreate(...) method.
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// do your stuff.
}
});

android custom listview with gallery images

I'm trying to add all the images contained in a folder in my custom listview, where I show a thumbnail of the photo and a little description.
I've found a lot of examples showing images from URL or drawable folder in Android Studio, but nothing working for me that loads a picture located in /storage/emulated/0/DCIM/Camera/AAAAMMGG_HHMMSS.jpg
Here is my code - MainActivity:
import android.content.ContentValues;
public class MainActivity extends ActionBarActivity implements OnClickListener {
public int PHOTO_REQUEST_CODE = 1;
private Uri fileUri;
private ArrayAdapter<String> adapter;
TextView ceScanResults;
ImageButton btnScan;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a toolbar to replace the action bar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
View addButton = findViewById(mci);
ArrayList<ListItem> listData = getListData();
final ListView listView = (ListView) findViewById(R.id.custom_list);
listView.setAdapter(new CustomListAdapter(this, listData));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
ListItem newsData = (ListItem) listView.getItemAtPosition(position);
Toast.makeText(MainActivity.this, "Selected :" + " " + newsData, Toast.LENGTH_LONG).show();
}
});
initViews();
}
private ArrayList<ListItem> getListData() {
ArrayList<ListItem> listMockData = new ArrayList<ListItem>();
String[] images = getResources().getStringArray(R.array.images_array);
String[] headlines = getResources().getStringArray(R.array.headline_array);
for (int i = 0; i < images.length; i++) {
ListItem newsData = new ListItem();
newsData.setUrl(images[i]);
newsData.setHeadline(headlines[i]);
newsData.setReporterName("CE code");
newsData.setDate("28/07/2015 - 10:31");
listMockData.add(newsData);
}
return listMockData;
}
private void initViews() {
//ceScanResults = (TextView) findViewById(R.id.ceResults);
btnScan = (ImageButton) findViewById(R.id.mci);
btnScan.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void initGalleryFetchImage() {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_OK);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Uri selectedImageUri = null;
String filePath = null;
if (requestCode == 1 && resultCode == RESULT_OK ) {
Uri selectedImage = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
try {
Bitmap bmp = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(selectedImage));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
selectedImageUri = fileUri;
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == 2) {
selectedImageUri = intent.getData();
}
if(selectedImageUri != null){
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
// bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
}
public String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
if(cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.mci) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, PHOTO_REQUEST_CODE);
String fileName = "new-photo-name.jpg";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image captured by camera");
//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
//create new Intent
startActivityForResult(intent, 1);
fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
try ( InputStream is = new URL(filePath).openStream() ) {
Bitmap bitmap = BitmapFactory.decodeStream( is );
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
}
}
And the code of my CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<ListItem> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<ListItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.reporterNameView = (TextView) convertView.findViewById(R.id.reporter);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListItem newsItem = listData.get(position);
holder.headlineView.setText(newsItem.getHeadline());
holder.reporterNameView.setText("" + newsItem.getReporterName());
holder.reportedDateView.setText(newsItem.getDate());
if (holder.imageView != null) {
new ImageDownloaderTask(holder.imageView).execute(newsItem.getUrl());
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView reporterNameView;
TextView reportedDateView;
ImageView imageView;
}
}
My class ImageDownloaderTask:
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.placeholder);
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
My ListItem.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:contentDescription="icon"
/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</LinearLayout>
Thanks a lot for your precious support!
Greetings,
Michele.
I'm using this library to load images from an URL
https://github.com/thest1/LazyList
try using code like this in Your adapter:
File img = new File("/sdcard/image.jpg");
if(img.exists()){
Bitmap bitmap = BitmapFactory.decodeFile(img.getAbsolutePath());
holder.imageView.setImageBitmap(bitmap);
}

Failed Binder Transaction after setting bitmaps

I can capture an image, either through camera or gallery. I also have two imageviews to set the captured images to it. But I always get the failed binder transaction when I try to start an intent with the passed two compressed bitmaps:
public class PostFragment extends Fragment implements OnClickListener {
View post_view;
Button button1, button0;
ActionBar actionBar;
private Uri mImageCaptureUri;
private ImageView mImageView, mImageView2;
private AlertDialog dialog;
private String imagepath = null;
Bitmap bitmap, bitmap1, bitmap2, bitmap_image1, bitmap_image2;
String krt, krt1, krt2;
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_FILE = 3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
post_view = inflater.inflate(R.layout.postoffer_fragment_layout,
container, false);
getActivity().getActionBar().setIcon(R.drawable.ic_offer);
button1 = (Button) post_view.findViewById(R.id.button1);
button1.setOnClickListener(this);
button0 = (Button) post_view.findViewById(R.id.button0);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
captureImageInitialization();
mImageView = (ImageView) post_view.findViewById(R.id.imageView1);
mImageView2 = (ImageView) post_view.findViewById(R.id.imageView2);
return post_view;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
// setText() sets the string value of the TextView
Intent intent = new Intent(getActivity(), OfferInformation.class);
if (krt1 != "" && krt2 != "") {
intent.putExtra("image", krt1);
intent.putExtra("image2", krt2);
startActivity(intent);
}
}
private void captureImageInitialization() {
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, PICK_FROM_CAMERA);
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
}
});
dialog = builder.create();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
if (mImageView.getDrawable() == null) {
bitmap1 = BitmapFactory.decodeFile(imagepath);
/*tbd
*/
} else if (mImageView.getDrawable() != null
&& mImageView2.getDrawable() == null) {
mImageView.setTag("2");
/*tbd
*/
}
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
if (mImageView.getDrawable() == null) {
bitmap1 = BitmapFactory.decodeFile(imagepath);
mImageView.setImageBitmap(bitmap1);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, baos1);
byte[] imageBytes1 = baos1.toByteArray();
krt1 = Base64.encodeToString(imageBytes1, Base64.DEFAULT);
} else if (mImageView.getDrawable() != null
&& mImageView2.getDrawable() == null) {
bitmap2 = BitmapFactory.decodeFile(imagepath);
mImageView2.setImageBitmap(bitmap2);
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
byte[] imageBytes2 = baos2.toByteArray();
krt2 = Base64.encodeToString(imageBytes2, Base64.DEFAULT);
}
break;
}
}
public String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, proj,
null, null, null);
if (cursor.moveToFirst()) {
;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
}

Categories

Resources