I want to build this app, where you can select one picture from camera or from gallery. This picture is not set as ImageView. Now how can I build an OnClickListener with the uploadbutton, which uploads the image to firebase?
public class MainActivity extends AppCompatActivity {
private StorageReference mStorage;
private static final int GALLERY_INTENT = 2;
private ImageButton mCamera;
private ImageButton mGallery;
private ImageView mImageview;
private static final int CAMERA_REQUEST_CODE = 1;
private ImageButton mUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mGallery = (ImageButton) findViewById(R.id.UpGallery);
mUpload = (ImageButton) findViewById(R.id.UpImage);
mCamera = (ImageButton) findViewById(R.id.UpCamera);
mImageview = (ImageView) findViewById(R.id.imageView1);
mImageview.buildDrawingCache();
mImageview.setDrawingCacheEnabled(true);
mImageview.buildDrawingCache();
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
mGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
mCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, CAMERA_REQUEST_CODE);
}
});
mUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
final Uri uri = data.getData();
Picasso.with(MainActivity.this).load(uri).fit().centerCrop().into(mImageview);
}
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImageview.setImageBitmap(photo);
Uri uri1 = data.getData();
Picasso.with(MainActivity.this).load(uri1).fit().centerCrop().into(mImageview);
}
}
}
final StorageReference storageRef = FirebaseStorage.getInstance().getReferenceFromUrl("gs://{your-storage-name-from-firebase}.appspot.com");
mImageview.setDrawingCacheEnabled(true);
mImageview.buildDrawingCache();
Bitmap bitmap = mImageview .getDrawingCache();
ByteArrayOutputStream baas = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baas);
byte[] data = baas.toByteArray();
UploadTask uploadTask = storageRef.child("{image-folder}").child("unique-id-image").putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this, "Picture upload failed", Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String downloadUrl = taskSnapshot.getDownloadUrl();
}
});
Hope this helps.
Related
I'm trying to upload some pictures and videos from the gallery to the Firebase Storage. I tried For the images I had no problems, but for the videos yes. I tried with several tutorial found on google but none worked.
How could I do? This is the code I have written so far:
public class GalleryActivity extends AppCompatActivity {
private Button chooseImage;
private Button chooseVideo;
private Button sendToCloud;
private ImageView selectedImage;
private VideoView selectedVideo;
private TextView txtDescription;
private static final int PICK_IMAGE = 100;
private static final int PICK_VIDEO = 200;
private Uri mImageUri;
//Firebase stuff
private FirebaseStorage storage;
private StorageReference storageReference;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
txtDescription = findViewById(R.id.diplay);
selectedImage = findViewById(R.id.image_taken);
selectedVideo = findViewById(R.id.video_taken);
chooseImage = findViewById(R.id.imageBtn);
chooseVideo = findViewById(R.id.videoBtn);
sendToCloud = findViewById(R.id.send_to_cloud);
// get the Firebase storage reference
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImageFromGallery();
}
});
chooseVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseVideoFromGallery();
}
});
sendToCloud.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(selectedImage.getDrawable() != null) {
uploadImage();
}
//check if videoview is empty and call uploadVideo()
}
});
}
private void chooseVideoFromGallery() {
Intent i = new Intent();
i.setType("video/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "choose App"), PICK_VIDEO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
if (requestCode == PICK_IMAGE) {// img from gallery
previewImage(data);
} else if (requestCode == PICK_VIDEO) {
previewVideo(data);
}
}
}
private void previewVideo() {
try {
txtDescription.setVisibility(View.GONE);
selectedImage.setVisibility(View.GONE);
selectedVideo.setVisibility(View.VISIBLE);
selectedVideo.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void previewImage(Intent data) {
try {
txtDescription.setVisibility(View.GONE);
selectedVideo.setVisibility(View.GONE);
selectedImage.setVisibility(View.VISIBLE);
Uri imgUri = data.getData();
InputStream imageStream = GalleryActivity.this.getContentResolver().openInputStream(imgUri);//2
Bitmap selectedImageBitmap = BitmapFactory.decodeStream(imageStream);//3}
mImageUri = imgUri;
selectedImage.setImageBitmap(selectedImageBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Thanks in advance to everyone
This is the working code:
if (resultCode == RESULT_OK) {
if (requestCode == PICK_VIDEO) {
Uri videoUri= data.getData();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
String filename = "give a unique filename for each";
videoRef = storageRef.child("/videos/" + uid+ "/" + filename);
uploadVideo(videoUri);
}
}
Upload Video here:
private void uploadVideo(Uri videoUri) {
if(videoUri != null){
UploadTask uploadTask = videoRef.putFile(videoUri);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>({
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful())
Toast.makeText(getContext(), "Video Upload Completed", Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
updateProgress(taskSnapshot);
}
});
}else {
Toast.makeText(getContext(), "upload failed!", Toast.LENGTH_SHORT).show();
}
}
// StorageReference videoRef;
i am uploading video to firebase storage. i want to show the thumbnail of selected video on app screen
i have tried uploading image with the same code and it gives me the image preview of selected image, but it doesnot show any preview or thumbnail of selected video
moreover i want to know hoe to give the path of selected video as well..
main activity
public class MainActivity extends AppCompatActivity {
private static final int PICK_VIDEO_REQUEST = 3;
Button chooseImg, uploadImg;
ImageView imgView;
int PICK_IMAGE_REQUEST = 111;
Uri filePath;
ProgressDialog pd;
//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://<<ur app url>>"); //change the url according to your firebase app
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseImg = (Button)findViewById(R.id.chooseImg);
uploadImg = (Button)findViewById(R.id.uploadImg);
imgView = (ImageView)findViewById(R.id.imgView);
pd = new ProgressDialog(this);
pd.setMessage("Uploading....");
chooseImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_VIDEO_REQUEST);
}
});
uploadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null) {
pd.show();
StorageReference childRef = storageRef.child("vide.mp4");
//uploading the image
UploadTask uploadTask = childRef.putFile(filePath);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select a video", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
//getting image from gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
imgView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I have a code for upload an image to Firebase Storage. The code was running well but when I updated Android Studio there is a problem with code. Can you please suggest how should I change the code?
private StorageReference mStorage;
private static final int GALLERY_INTENT = 2;
private ProgressDialog mProgressDialog;
private ImageView imageViewProfilePicturePreview;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mProgressDialog = new ProgressDialog(this);
mDatabase = FirebaseDatabase.getInstance().getReference();
mStorage = FirebaseStorage.getInstance().getReference();
imageViewProfilePicturePreview = (ImageView) findViewById(R.id.imageViewProfilePicturePreview);
}
...
#Override
public void onClick(View view) {
...
if (view == textViewUploadPhoto) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
}
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
mProgressDialog.setMessage("Uploading...");
mProgressDialog.show();
StorageReference imageRef = mStorage.child(email);
StorageReference imageImagesRef = mStorage.child("photos/" + email);
imageRef.getName().equals(imageImagesRef.getName()); // true
imageRef.getPath().equals(imageImagesRef.getPath()); // false
Uri uri = data.getData();
imageViewProfilePicturePreview.setImageURI(uri);
imageViewProfilePicturePreview.setDrawingCacheEnabled(true);
imageViewProfilePicturePreview.buildDrawingCache();
Bitmap bitmap = imageViewProfilePicturePreview.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data2 = baos.toByteArray();
UploadTask uploadTask = imageImagesRef.putBytes(data2);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), "Sorry, your image wasn't set, please try again",
Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
mProgressDialog.dismiss();
Picasso.with(getApplicationContext()).load(downloadUrl).fit().centerCrop().into(imageViewProfilePicturePreview);
Toast.makeText(getApplicationContext(), "Upload done",
Toast.LENGTH_SHORT).show();
}
});
}
}
Thanks for all help.
Hi i'm having trouble entering data into firebase.
I can insert image data from album to firebase but i can not put image data from camera to firebase that i just photo. Please help me :)
//activitylapor
public class Lapor extends AppCompatActivity {
private ImageButton mSelectImage;
private EditText mPostNamaPelapor;
private EditText mPostNoTelpon;
private EditText mPostLokasiKejadian;
private EditText mPostKeteranganBencana;
private EditText mPostWaktuBencana;
private Uri mImageUri = null;
//private static final int GALLERY_REQUEST = 1;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String userChoosenTask;
private ImageView ivImage;
private StorageReference mStorage;
private DatabaseReference mDatabase;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Lapor");
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostNamaPelapor = (EditText) findViewById(R.id.namaPelapor);
mPostNoTelpon = (EditText) findViewById(R.id.noTelpon);
mPostLokasiKejadian = (EditText) findViewById(R.id.lokasiKejadian);
mPostKeteranganBencana = (EditText) findViewById(R.id.keteranganBencana);
ivImage = (ImageView) findViewById(R.id.ivImage);
Button mSubmitBtn = (Button) findViewById(R.id.submitBtn);
mProgress = new ProgressDialog(this);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
mSubmitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startPosting();
}
});
}
private void startPosting() {
mProgress.setMessage("Posting Lapor");
mProgress.show();
final String namapelapor_val = mPostNamaPelapor.getText().toString().trim();
final String notelpon_val = mPostNoTelpon.getText().toString().trim();
final String lokasikejadian_val = mPostLokasiKejadian.getText().toString().trim();
final String keteranganbencana_val = mPostKeteranganBencana.getText().toString().trim();
if (!TextUtils.isEmpty(namapelapor_val) && !TextUtils.isEmpty(notelpon_val) && !TextUtils.isEmpty(lokasikejadian_val)
&& !TextUtils.isEmpty(keteranganbencana_val) && mImageUri != null) {
StorageReference filepath = mStorage.child("Foto_Lapor").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("namapelapor").setValue(namapelapor_val);
newPost.child("nomortelpon").setValue(notelpon_val);
newPost.child("lokasikejadian").setValue(lokasikejadian_val);
newPost.child("keteranganbencana").setValue(keteranganbencana_val);
assert downloadUrl != null;
newPost.child("foto").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(new Intent(Lapor.this, Terimakasih.class));
finish();
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (userChoosenTask.equals("Ambil Foto"))
cameraIntent();
else if (userChoosenTask.equals("Ambil dari Album"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
private void selectImage() {
final CharSequence[] items = {"Ambil Foto", "Ambil dari Album",
"Batal"};
AlertDialog.Builder builder = new AlertDialog.Builder(Lapor.this);
builder.setTitle("Ambil Gambar");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(Lapor.this);
if (items[item].equals("Ambil Foto")) {
userChoosenTask = "Ambil Foto";
if (result)
cameraIntent();
} else if (items[item].equals("Ambil dari Album")) {
userChoosenTask = "Ambil dari Album";
if (result)
galleryIntent();
} else if (items[item].equals("Batal")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE) {
Uri mImageUri = data.getData();
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(4, 3)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
mImageUri = result.getUri();
ivImage.setImageURI(mImageUri);
}
else if (requestCode == REQUEST_CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
ivImage.setImageBitmap(thumbnail);
}
}
}
}
Thanks
Here is how i have done,its working for me,
In OnActivity Result,
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl(AppConstants.STORAGE_BUCKET);
final String imageName = "INSTA_"+System.currentTimeMillis()+".JPEG";
StorageReference imagePathReference;
imagePathReference = storageRef.child("---your storage path---"+ imageName);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, bos2);
byte[] dataNew2 = bos2.toByteArray();
uploadTask = imagePathReference2.putBytes(dataNew2);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if(FirebaseAuth.getInstance().getCurrentUser() != null){
initToSendMessageToFirebase(fileUri, MESSAGE_TYPE_IMAGE,taskSnapshot,"",imageName);
}
}
});
On Clicking launch Camera,
Declare Uri fileUri ; -- global
private void launchCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
try {
fileUri = Uri.fromFile(createImageFile());
} catch (IOException e) {
e.printStackTrace();
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, RC_CAMERA);
}
}
}
My Main2Activity class
public class Main2Activity extends AppCompatActivity {
private static int PICK_IMAGE_REQUEST = 1;
ImageView imgView;
static final String TAG = "Main2Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void loadImagefromGallery(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && null != data) {
final Uri uri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true);
imgView = (ImageView) findViewById(imageView);
imgView.setImageBitmap(scaled);
Button button3 = (Button) findViewById(bt_tab3);
button3.setOnClickListener
(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Main3Activity.class);
intent.setData(uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
});
} else {
Toast.makeText(this, "No.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Oops! Sorry", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
And the Main3Activity
public class Main3Activity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
imageView = (ImageView) findViewById(R.id.imageView2);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri imageUri = getIntent().getData();
imageView.setImageURI(imageUri);
}
}
How can I show same gallery image in MainActivity and another Activity?
Move your Button related codes into onCreate() and send Uri as String using intent extras.
Update Main2Activity as below:
public class Main2Activity extends AppCompatActivity {
static final String TAG = "Main2Activity";
private static int PICK_IMAGE_REQUEST = 1;
ImageView imgView;
Button button3;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imgView = (ImageView) findViewById(R.id.imageView);
button3 = (Button) findViewById(R.id.bt_tab3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Main3Activity.class);
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
}
});
}
public void loadImagefromGallery(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && null != data) {
// Get uri
imageUri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true);
// Set image
imgView.setImageBitmap(scaled);
} else {
Toast.makeText(this, "No.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Oops! Sorry", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
Get Uri as string from intent and construct Uri from string using Uri.parse() method.
Update Main3Activity as below:
public class Main3Activity extends AppCompatActivity {
ImageView imageView;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
imageView = (ImageView) findViewById(R.id.imageView2);
if (getIntent().getExtras() != null) {
imageUri = Uri.parse(getIntent().getStringExtra("imageUri"));
imageView.setImageURI(imageUri);
}
}
}
Pass the file path from the uri as String like this to Main3Activity.
button3.setOnClickListener
(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Main3Activity.class);
intent.putExtra("filePath", uri.getPath());
startActivity(intent);
}
});
And in Main3Activity get the data passed from the calling Activity like this.
public class Main3Activity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
imageView = (ImageView) findViewById(R.id.imageView2);
File file = new File(getIntent().getStringExtra("filePath"));
setImageFromFileIntoImageView(file);
}
private void setImageFromFileIntoImageView (File imgFile)
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
}
}
}
You need to add the following permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
based on you not accepting previous answers here is a different approach :
first convert your image to byte array like :
Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is bitmap object
byte[] b = baos.toByteArray();
then convert that into string like :
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
then from your first activity make an intent and put that string as an extra like:
Intent imageIntent = new Intent(context,Main3Activity.class);
imageIntent.putExtra("image",encodedImage);
startActivity(imageIntent);
and after that it is so easy to get this string in the next activity using getIntent and then getExtra
hope this helps.