Issue in fetching image from SD card and displaying on an ImageView - java

I found a program on this page to fetch image from sd card and show it on an imageView. I am getting issue at this line -
bitmap = BitmapFactory.decodeFile(picturePath);
I am getting correct value of picturePath variable but in the above line it is setting bitmap value as null. I had visited various threads and almost everyone is using this same line. I am not getting what is wrong with my code
Here is my complete code -
private Button upload;
ImageView imgView;
EditText caption;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.imageView);
upload = (Button) findViewById(R.id.Upload);
caption = (EditText) findViewById(R.id.caption);
imgView.setImageResource(R.drawable.ic_menu_gallery);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 2);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(picturePath);
imgView.setImageBitmap(bitmap);
caption.setText("Hello");
}
}

Try putting this in your AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
After that, make sure you have the permission enabled in the App Info screen on your device.

Related

API 25 Image capturing

i was building my app on API level 23 ,then i have changed API level to 25 the same code is not working now , here's my code :
public class expert extends Activity implements View.OnClickListener {
Button btnsetwall;
ImageButton imgbtntakeph;
ImageView Imview;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expert);
Imview = (ImageView) findViewById(R.id.imageView22);
btnsetwall = (Button) findViewById(R.id.button2);
btnsetwall.setOnClickListener(this);
}
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Imview.setImageBitmap(imageBitmap);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), imageBitmap);
// CALL THIS METHOD TO GET THE ACTUAL PATH
Toast.makeText(getBaseContext(),"Here "+ getRealPathFromURI(tempUri), Toast.LENGTH_LONG).show();
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
when i try to pick image from gallery or to get captured image my app crashes and i get UriString Exception
can any one tell the reason ?? and how to solve !
thanks in advance

Show selected image in another activity

I've searched on stackoverflow but never found a solution
Here is my situation:
I have a button which start an intent to pick an image
How can I resize proportionally (to keep the aspect ration) and display it on another activity (in imageview)?
I also want to save this resized image to user storage. How can I do that?
Thanks!
Here is my code
MainActivity.java
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, getString(R.string.completeaction)),
PICK_FROM_FILE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RequestExternal && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String [] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
selectedphoto = BitmapFactory.decodeFile(filePath);
cursor.close();
Intent intent = new Intent(MainActivity.this,PhotoResized.class);
intent.putExtra("data", selectedphoto);
startActivity(intent);
}
}
PhotoResized.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photoresized);
img = (ImageView) findViewById(R.id.imageView1);
}
For resizing the image use sampling technique provided by dev.android here
Use Lrucache for storing images. Use technique shown here

Error with image view when displaying an image by camera capturing

i am new to android and i am trying to make my phone cam take a picture and display it in an image view. When the image is captured, it is saved correctly but after that the app stops working when the image should be displayed in an image view. Any help is appreciated. I searched some topics but still nothing works.
Here is the code:
package myfirstapp.myapps.me.camera;
import ...
public class MainActivity extends ActionBarActivity {
ImageButton camBtn;
ImageView imageView;
ScrollView scrollView;
private File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OpenCam(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFile=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"image.jpg");
Uri tempURI=Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, tempURI);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0)//==0 the same where startActivityForResult(intent, 0) so we are in the same process
{
switch (resultCode){
case Activity.RESULT_OK:
if(imageFile.exists())
{
Toast.makeText(MainActivity.this, "Image was saved at "+imageFile.getAbsolutePath(), Toast.LENGTH_SHORT)
.show();
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
}
else
{
Toast.makeText(MainActivity.this, "Image wasn't saved", Toast.LENGTH_SHORT)
.show();
}
break;
case Activity.RESULT_CANCELED:
Toast.makeText(MainActivity.this, "Image capture was cancelled", Toast.LENGTH_SHORT)
.show();
break;
}
}
}
}
Stacktrace
Caused by: java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=0, result=-1, data=null} to activity
{myfirstapp.myapps.me.camera/myfirstapp.myapps.me.camera.MainActivity}:
java.lang.NullPointerException at
android.app.ActivityThread.deliverResults(ActivityThread.java:3410) at
android.app.ActivityThread.performResumeActivity(ActivityThread.java:2817)
at
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2859)
Please go through this Code:
public static final int REQUEST_IMAGE_CAPTURE = 1;
public static final int RESULT_LOAD_IMAGE = 10;
private Bitmap myBitmap;
ImageView myImage ;
public void OpenCam(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
And also,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
{
Bundle extras = data.getExtras();
myBitmap= (Bitmap) extras.get("data");
myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
}
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
myBitmap= BitmapFactory.decodeFile(picturePath);
// photoUri = picturePath;
myImage.setImageBitmap(myBitmap);
}
}
Why are you first saving and trying to show the saved image file. Use the returned data from onActivityResult. Before file is actually created in the memory, broadcast is sent so it can refresh the directory and show the new file. But better is to use what camera intent is returning as data.
Replace your this code
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
with this
ImageView myImage = (ImageView) findViewById(R.id.imageView);
Bitmap photo = (Bitmap) data.getExtras().get("data");
myImage.setImageBitmap(photo);
first : comment the line
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // no need to write for capture camera
second : use this line
imageFile=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc); // abc folder name
instead of
imageFile=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"image.jpg");
Note : your code work upto kitkat but lollipop it will crash because in lollipop imageFile return null so Uri failed to convert in file . Hope your problem will resolve . and one more thing before open camera u should check that sdcard permission .

Select a image from the gallery and show it in another Activity

I am making an android application in which i have to select image from gallery by clicking a button and then display it in another activity with two text fields, the problem is i am able to open the gallery and select image from it but i am not able to display image in another activity...
here is my code...
PictureOptions.java
public void buttonGalleryOpen(View view)
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String [] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
selectedphoto = BitmapFactory.decodeFile(filePath);
cursor.close();
Intent intent = new Intent(PictureOptions.this,ShowImage.class);
intent.putExtra("data", selectedphoto);
startActivity(intent);
}
PictureOptions.xml
<Button
android:id="#+id/buttonGalleryOpen"
android:layout_width="fill_parent"
android:layout_height="66dp"
android:layout_weight="0.34"
android:onClick="buttonGalleryOpen"
android:text="#string/button_gallery_open" />
ShowImage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_image);
ImageView imageview = (ImageView)findViewById(R.id.ImageShow);
Bitmap selectedphoto =(Bitmap)this.getIntent().getParcelableExtra("data");
imageview.setImageBitmap(selectedphoto);
}
ShowImage.xml
<ImageView
android:id="#+id/ImageShow"
android:layout_width="200dp"
android:layout_height="200dp" />
All things are working fine and second activity(ShowImage) is also opening except that no iamge is displying....dont know why..?HELP
This line in your code does not make sense:
intent.putExtra("data", "selectedphoto");
You are adding here string "selectedphoto" which is in no way connected to selectedphoto variable you initialised earlier. You could put your bitmap to intent extra as byte array but this is inefficient, especially when the image is large.
Instead of passing bitmap to ShowImage activity, pass your URI and then retrieve actual bitmap in ShowImage activity exactly as you do now in your PictureOptions activity.
intent.setData( uri );
In your ShowImage activity do:
URI imageUri = getIntent().getData();
Yo have a typo in intent.putExtra("data", "selectedphoto");, you are passing a String not the bitmap. Change it in
Intent intent = new Intent(PictureOptions.this,ShowImage.class);
intent.putExtra("data", selectedphoto);
startActivity(intent);
removing the double quote from selectedphoto
private void selectImage() {
final CharSequence[] items = { "Photo Library", "Camera", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select");
Utils.hideSoftKeyboard(getActivity());
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Camera")) {
// camera intent
} else if (items[item].equals("Photo Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, getActivity());
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(tempPath, btmapOptions);
resized = Bitmap.createScaledBitmap(bitmap,
(int) (bitmap.getWidth() * 0.8),
(int) (bitmap.getHeight() * 0.8), true);
profileEditImageView.setImageBitmap(resized);
}
}
}
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

save path of image imported from gallery into sql database and display it in an imageview later

I'm trying to save the path of an image imported from the gallery using this method:
case R.id.media:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
return true;
Here is the on activity result method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
final Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = (cursor.getString(columnIndex));
cursor.close();
mImage = picturePath;
ImageView imageView = (ImageView) findViewById(R.id.note_image);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
imageView.setClickable(true);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewImageIntent = new Intent(android.content.Intent.ACTION_VIEW, selectedImage);
startActivity(viewImageIntent);
}
});
}
}
And here is the populate field method:
mImage =(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_IMAGE)));
But this is not working, the path doesnt get saved and when i close the activity and start the activity again, the image is gone. How can i fix this?

Categories