Profile image disappeared on backPress Button - java

I have an activity that contains an ImageView for showing user photo.
the user select an image from phone gallery and when he is done the image upload to firebase storage and return to the ImageView.
the problem is: when the user go to another activity (or on back button pressed) and return to UserProfile activity the image is no longer exist inside the ImageView.
how can i load the image when UserProfile activity start?
this is my UserProfile Activity
public class UserProfile extends AppCompatActivity {
private static final int GALLERY_INTENT = 2 ;
private ImageButton userImage;
private Button save_changes;
private EditText user_name;
private StorageReference mStorage;
private Uri mImageUri ,downloadUri;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
mAuth = FirebaseAuth.getInstance();
userImage = (ImageButton) findViewById(R.id.profileImage);
save_changes = (Button) findViewById(R.id.savechanges);
user_name = (EditText) findViewById(R.id.user_name2);
mStorage = FirebaseStorage.getInstance().getReference();
userImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_INTENT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON).
setAspectRatio(1,1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mImageUri = result.getUri();
}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
save_changes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = user_name.getText().toString();
StorageReference filepath = mStorage.child("photos").child(mAuth.getCurrentUser().getUid()).child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(UserProfile.this).load(downloadUri).into(userImage);
Toast.makeText(UserProfile.this,"התמונה עלתה בהצלחה",Toast.LENGTH_SHORT).show();
}
});
}
});
}
}

I haven't tried this but you can do one thing create a static variable of Bitmap type when the image is selected assign that bitmap variable the value of bitmap from gallery.
And on your onStart of your activity first check if that static bitmap variable is null if not so put the bitmap into your imageView

When you launched another activity from current activity your previous activity gets destroyed. so all the variables and the image which set to the image view also garbage collected.
For that you can save your bitmap inside onSaveInstance()
Overide below method inside your activity
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putParcelable("BitmapImage", bitmap);
}
Write below code inside onCreate() which we can get the saved bitmap
if (savedInstanceState != null) {
image = savedInstanceState.getParcelable("BitmapImage");
targetImage.setImageBitmap(image); // set the bitmap.
}
If you have imagePath we can also save that and get that using same approach.
Hope these help you.

Related

Issue swapping image

I have a ProfileActivity:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final ImageView exampleImage = (ImageView) this.findViewById(R.id.exampleImageView);
exampleImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// [TODO] Implement application behavior when the user clicks the profile picture
//Toast.makeText(ProfileActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
startActivity(new Intent(ProfileActivity.this, GalleryActivity.class));
}
});
}
and I have a second activity called 'GalleryActivity'. the concept is to let the user choose a image from the gallery and then use it to replace the original Profile image.
public class GalleryActivity extends AppCompatActivity {
ImageView imageView;
private static final int PICK_IMAGE = 100;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
}
however, when I click on a image of the gallery, instead of taking it as new profile image, it take me back to the original image.
what is happening and how I can solve it?
You can use Github Library it will help you.
Here is the Link.
ImagePicker.Companion.with(this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(1024) //Final image size will be less than 1 MB(Optional)
.maxResultSize(1080, 1080)
.start();//Final image resolution will be less than 1080 x 1080(Optional)
On Activity Result.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
selectedFileURI = data.getData();
if (selectedFileURI != null && !Objects.requireNonNull(selectedFileURI.getPath()).isEmpty()) {
btnUpdate.setVisibility(View.GONE);
civUser.setImageURI(selectedFileURI);
Glide.with(context).load(selectedFileURI).into(civUser);
btnUploadDp.setVisibility(View.VISIBLE);
} else {
Functions.showSnackBar(context, "Cannot Get this Image");
}
}
}
}
Refernce Link.

'startActivityForResult(android.content.Intent, int)' is deprecated

I'm developing an intern project about a college app, while running this part of the app suddenly get close. this is the part where I can upload the photos to the gallery. I am not getting any error but here startActivityForResult(pickImage,REQ); it is saying like 'startActivityForResult(android.content.Intent, int)' is deprecated as a warning.
private String category;
private final int REQ= 1;
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_image);
selectImage = findViewById(R.id.addGalleryImage);
imageCategory = findViewById(R.id.image_category);
uploadImage = findViewById(R.id.uploadImageBtn);
galleryImageView = findViewById(R.id.galleryImageView);
String[] items = new String[]{"Select Category", "Convovation", "INdependence Day","Other Events"};
imageCategory.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items));
imageCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
category = imageCategory.getSelectedItem().toString();
}
});
selectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void openGallery(){
Intent pickImage = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickImage,REQ);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
galleryImageView.setImageBitmap(bitmap);
}
}
}
If you want to pick image from the device then go for a newer alternative of startActiityForResult(), it's - ActivityResultLauncher
Just follow these steps :-
First create the ActivityResultLauncher like this :
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new
GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
// Handle the returned Uri
}
});
Then, launch system image picker on button click or however you want.
#Override
public void onCreate(#Nullable savedInstanceState: Bundle) {
Button selectButton = findViewById(R.id.select_button);
selectButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Pass in the mime type you'd like to allow the user to select
// as the input
mGetContent.launch("image/*");
}
});
}
As you can see, you are not seeing the REQUEST_CODE anywhere. So with ActivityResultLauncher, you don't have to worry about checking different requestcodes for different tasks. ActivityResultLauncher gives you the final result if everything is ok.
You can find more about it here :- https://developer.android.com/training/basics/intents/result
Finally I found the answer on google official website.
If you need requestCode todo something , just put the requestCode into the intent.
Good luck!
ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent intent = result.getData();
// Handle the Intent
}
}
});
#Override
public void onCreate(#Nullable savedInstanceState: Bundle) {
// ...
Button startButton = findViewById(R.id.start_button);
startButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// The launcher with the Intent you want to start
mStartForResult.launch(new Intent(this, ResultProducingActivity.class));
}
});
}

How to pick two different images from gallery seperately in the same activity and load them into their imageviews at different clicks?

Am building a mobile app for our local football team.I want to able to pick the logo images for the two teams that will have an upcoming game.
So picking the images from the Gallery and save them.
I have created the openGalleryMethods to open Gallery and then onbtain the image that is selected at the first pick.
Then call the openGallery Method again and pick the image that is picked the second time on another imageView.
public class MatchFixturesActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
private EditText HostTeamInput,VisitingTeamInput,
StadiumHostingGame,LeagueOfPlay,DateOfGameDisplay;
private CircleImageView HostTeamLogo,VisitingTeamLogo;
private TextView DisplayTimeOfGame;
private Button TimeOfGameBtn,DateOfGameBtn,SavingInfoButton;
private static final int GalleryPick = 1;
private static final int GalleryPick2 = 1;
private Uri ImageUrl1,ImageUrl2;
private String HostTeamName,VisitingTeamName,StadiumHostName
,LeagueName,DateOfPlayInput,TimeInput,RandomKey,downloadImageUrl,downloadImageUrl1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match_fixtures);
HostTeamLogo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenGallery();
}
});
VisitingTeamLogo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenGallery1();
}
});
}
private void OpenGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GalleryPick);
}
private void OpenGallery1() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GalleryPick);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode==RESULT_OK && data!=null){
ImageUrl1 = data.getData();
HostTeamLogo.setImageURI(ImageUrl1);
}else{
ImageUrl2 = data.getData();
VisitingTeamLogo.setImageURI(ImageUrl2);
}
}
}
I expect the logo of the hosting team to be loaded into the imageview at first pick and then the second pick the logo for the visitong team to be loaded in its se[erate imageView
Guys thank and fortunately have got the answer. I had to define my GalleryPicks as
GalleryPick and GalleryPick1 and defined as
private static final int GalleryPick = 1;
private static final int GalleryPick2 = 2;
With this,every thing worked perfectly well with the same code

Access camera for multiple buttons

How do I set up multiple buttons to access the camera and save the photo?
I have figured out how to have one button do this task, but cannot figure out how to get multiple buttons to do this.
My Java Code so far:
package com.example.android.phototaker;
public class MainActivity extends AppCompatActivity {
ImageView result;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button click = (Button)findViewById(R.id.signbutton);
result = (ImageView)findViewById(R.id.imageView);
}
public void dispatchTakePictureIntent(View view) {
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) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
result.setImageBitmap(imageBitmap);
}
}
}
By multiple buttons do you mean, different buttons opening up the camera?
If so, you will need to add an onclick listener for those buttons.

Choose file from directory

How i can choose image from gallery and them put it on parse.com ?
There i open GALLERY:
#Override
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
i.setType("image/*");
i.setAction(Intent.ACTION_VIEW);
///// - here must be code tat can choose file that i must upload to parse
////
There is code that can upload image to parse.com :
I think it will be something like this
ParseObject image = new ParseObject("guestList");
image.put("photo", image);
image.saveInBackground();
UPD
public class SendGuestPhoto extends Activity {
ImageView imageView;
private static final int PICK_IMAGE = 100;
String path;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_guest_photo);
imageView = (ImageView) findViewById(R.id.image_view);
Button button_choose_guest_photo = (Button)findViewById(R.id.button_choose_guest_photo);
button_choose_guest_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
}
private void openGallery() {
Intent gallery =
new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
Uri imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
public void SendPhoto(){
Button button_send_guest_photo = (Button)findViewById(R.id.button_send_guest_photo);
button_send_guest_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseObject photos = new ParseObject("guestsImages");
photos.put("photos", ????????????????);
photos.saveInBackground();
}
});
}
}

Categories

Resources