Select image from Gallery using Intent - android

I am trying to select and bring image from gallery, I could bring for 4.4.2 version but 5.0.0 or above it is not working.
When imageview1 is clicked:
imageview1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galeri_int = new Intent();
galeri_int.setType("image/*");
galeri_int.setAction(Intent.ACTION_GET_CONTENT);
galeri_int.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(galeri_int,44);
Log.d("tık","tıklandı");
}
});
OnActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
InputStream stream = null;
if(data !=null){
try {
stream = getContentResolver().openInputStream(data.getData());
bitmapx = BitmapFactory.decodeStream(stream);
stream.close();
Bitmap resized = resize(bitmapx,1000,1000);
imageview.setImageBitmap(resized);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is not working for 5.0.0 or above so what should I do?

try this
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose Picture"), 1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode==RESULT_CANCELED)
{
// action cancelled
}
if(resultCode==RESULT_OK)
{
Uri selectedimg = data.getData();
imageView.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedimg));
}
}

Finally, I solved my problem with changing click listener.
imageview1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,44);
Log.d("tık","tıklandı");
}
});

Related

An error occurs during the operation to place Uri as bitmap in imageView

public class addBoard extends AppCompatActivity {
private final int GET_GALLERY_IMAGE = 200;
Uri image;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addboard);
final EditText EDTITLE = findViewById(R.id.editTitle);
final EditText EDTEXT = findViewById(R.id.editText);
ImageView imgView = (ImageView)findViewById(R.id.imageView);
Button addPhoto = findViewById(R.id.photo);
addPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, GET_GALLERY_IMAGE);
}
});
try {
Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), image);
imgView.setImageBitmap(bm);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Button backButton = findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("Input_Title", EDTITLE.getText().toString());
intent.putExtra("Input_Text", EDTEXT.getText().toString());
intent.putExtra("Input_Image", image);
setResult(RESULT_OK, intent);
finish();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GET_GALLERY_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectImage = data.getData();
image = selectImage;
}
}
}
If you run this code in another project, there is no error, but if you use it in this project, you will get an error. Why is that?
Error :Caused by: java.lang.NullPointerException: uri
at com.example.toolbar.addBoard.onCreate**(addBoard.java:45)** // blue line
An error occurs during the operation to place Uri as bitmap in imageView.

Select an mp3 file from SD card

I need to ask the user to select a media file from his SD card for playing. The following code doesn't work:
edit:
after I choose a mp3 file from the sd card folder I can't start him (play him). I think that the problem is that it doesn't entering to the "onActivityResult" function.
Intent i = new Intent();
i.setType("audio/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, RESULT_OK);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==RESULT_OK)
{
Uri uri =data.getData();
if(uri!=null) {
try {
song.setDataSource(getApplicationContext(), uri);
song.prepare();
pl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
song.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(CONTEXT_RESTRICTED, RESULT_OK, data);
}
}
Your question doesn't include definitions of some variables so I added my own and it played. Try this:-
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
Intent i = new Intent();
i.setType("audio/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Uri uri = data.getData();
if (uri != null) {
try {
MediaPlayer song = new MediaPlayer();
song.setDataSource(getApplicationContext(), uri);
song.prepare();
song.start();
} catch (Exception e) {
}
}
super.onActivityResult(CONTEXT_RESTRICTED, RESULT_OK, data);
}
}
MediaPlayer Docs here

Return to MainActivity from another activity with error message

I am a bit new in android and I want to return to main activity from current activity with error message in dialog box.
I have written a script which make a call to rest api and if there is no data or error from response then i want to return to main activity with that error in dialog box.
Here is what i am doing
txtScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
private void selectImage(){
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from 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 == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
byte[] b;
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
String fileName = File.separator + System.currentTimeMillis() + ".jpg";
filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + fileName;
System.out.println(filePath);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
/*FileInputStream fis = null;
try{
fis = new FileInputStream(filePath);
}catch (FileNotFoundException e){
e.printStackTrace();
}*/
b = bytes.toByteArray();
encode_string = Base64.encodeToString(b, Base64.DEFAULT);
System.out.println(b);
System.out.println(encode_string);
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
obj = new JSONObject();
obj.put("image",encode_string);
obj.put("api_key",API_SECRET);
System.out.println(obj.toString());
}catch (Throwable t){
t.printStackTrace();
}
new Image().execute();
//new LongRunningGetIO().execute();
//ivImage.setImageBitmap(thumbnail);
}
This function is In Image class
#Override
protected void onPostExecute(Void r) {
progressDialog.dismiss();
if(responseBody == "Api key does not found/match"){
//here i want to return to main activity with error
}else {
byte[] imageAsBytes = Base64.decode(encode_string.getBytes(), Base64.DEFAULT);
//System.out.println(imageAsBytes);
Intent intent = new Intent(getActivity().getApplicationContext(), ViewActivity.class);
intent.putExtra("filePath", imageAsBytes);
//intent.putExtra("data", text);
startActivity(intent);
}
}
Any idea thanks in advance
use startActivityForResults for passing value from current activity to previous activity
call Activity
Intent intent=new Intent(MainActivity.this,CurrentActivity.class);
startActivityForResult(intent, 2);
Handle result on MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String error=data.getStringExtra("MESSAGE");
//display error
}
}
Async
#Override
protected void onPostExecute(Void r) {
progressDialog.dismiss();
if(responseBody == "Api key does not found/match"){
Intent intent=new Intent();
intent.putExtra("Error",message);
setResult(2,intent);
finish();
}else {
byte[] imageAsBytes = Base64.decode(encode_string.getBytes(), Base64.DEFAULT);
//System.out.println(imageAsBytes);
Intent intent = new Intent(getActivity().getApplicationContext(), ViewActivity.class);
intent.putExtra("filePath", imageAsBytes);
//intent.putExtra("data", text);
startActivity(intent);
}
}

image view:second image is replaced by the first image captured

hello i am struck in this coding first of all i am having two image view's when we click one of them the chooser dialog box will open which is having two option 1.take photo 2.select from gallery when i select from galley everything is working fine where as the problem is,
when we select take photo option and after we had captured the image when setting its preview for the first image its working fine where as the problem here is in the second image. when we select take photo option and after capturing the photo it is replacing the image of the first image with the second image.
This is Java Code:
public class PrescriptionUpload extends ActionBarActivity {
ImageView uploadimage1, uploadimage2;
Bitmap imagemap, imagemapsec;
int imageupload = 1;
int imagesecpload = 2;
int requestcamera = 0;
Button uploadpric;
StringBuilder sb;
String uploadimg2;
Toolbar include2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prescriptionimages);
include2= (Toolbar) findViewById(R.id.include2);
setSupportActionBar(include2);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
uploadimage1 = (ImageView) findViewById(R.id.uploadimage1);
uploadimage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectimage(imageupload);
}
});
uploadimage2 = (ImageView) findViewById(R.id.uploadimage2);
uploadimage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectimage(imagesecpload);
}
});
}
private void selectimage(final int number) {
final CharSequence[] items = {"Take Photo", "Choose from Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(PrescriptionUpload.this);
builder.setTitle("Add Prescription");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, requestcamera);
} else if (items[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
number);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == imageupload) {
try {
imagemap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
uploadimage1.setImageBitmap(imagemap);
uploadimage2.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == imagesecpload) {
try {
imagemapsec = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
uploadimage2.setImageBitmap(imagemapsec);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == requestcamera) {
if (uploadimage1.getId()==R.id.uploadimage1){
Bitmap testurl = (Bitmap) data.getExtras().get("data");
uploadimage1.setImageBitmap(testurl);
uploadimage2.setVisibility(View.VISIBLE);
}else if (uploadimage2.getId()==R.id.uploadimage2){
Bitmap testurltwo = (Bitmap) data.getExtras().get("data");
uploadimage2.setImageBitmap(testurltwo);
}
}
}
}
i had solved my problem using onActivityResult and with the increment of the variable

how to resize image from gallery

I want to select image from gallery and send it to Second activity but image is too big .
I need to resize it and I dont know how to do it:
buttonIntent.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_GALLERY);
method onresult
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = Media.getBitmap(this.getContentResolver(), uri);
imageView1.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
btnok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Showpic_resumeActivity.this,Showdata_result_resume.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, bs);
i.putExtra("byteArray", bs.toByteArray());
startActivity(i);
}
});
second activity
if (getIntent().hasExtra("byteArray")) {
Bitmap b = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"), 0, getIntent()
.getByteArrayExtra("byteArray").length);
image_resume.setImageBitmap(b);
}
Passing bitmaps from one activity to another activity is risk. Best way is just pass Uri instead of passing bitmaps from first activity to second and then convert Uri to bitmap when it requires.
Try this code:
Bitmap bmp=BitmapFactory.decodeResource(getResources(), your_image_loc);//ex:R.drawable.image1
int width=200;
int height=200;
Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmp, width, height, true);
img.setImageBitmap(resizedbitmap);
First Collect the URI
Uri uri = data.getData();
and pass the URI from One Activity to Other
btnok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Showpic_resumeActivity.this,Showdata_result_resume.class);
i.setData(uri );// Passing the URI
startActivity(i);
}
});
*And get Back the URI in Showdata_result_resume Activity*
Uri uri=getIntent().getData();
YOUR_IMAGVIEW.setImageURI(uri);// Set URI to your ImageView

Categories

Resources