Unable to retrieve profile image from firebase storage [duplicate] - java

This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
How to get URL from Firebase Storage getDownloadURL
(13 answers)
Closed 2 years ago.
I make a chatting app with android studio. I want to create settings activity. I successfully load profile image to firebase storage. But when I retrieve profile image from storage it seems end of the onactivityresult. But when I go back to main activity the profile image is disappearing I want when I enter to settings activity profile image is retrieves. I try to do with picasso & glide but not working.
enter code here
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Toolbar mToolbar;
private CircleImageView set_profile_image;
private EditText set_user_name , set_profile_status;
private Button update_settings_button;
private String CurrentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
define();
RetrieveUserInfo();
}
private void define() {
set_profile_image = (CircleImageView) findViewById(R.id.set_profile_image);
set_user_name = (EditText) findViewById(R.id.set_user_name);
set_profile_status = (EditText) findViewById(R.id.set_profile_status);
update_settings_button = (Button) findViewById(R.id.update_settings_button);
mAuth = FirebaseAuth.getInstance();
CurrentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
loadingBar = new ProgressDialog(this);
}
public void set_profile_image_click(View view){
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){
Uri ImageUri = data.getData();
CropImage.activity()
.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){
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Your Profile Image is Updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
final Uri resultUri = result.getUri();
StorageReference FilePath = UserProfileImagesRef.child(CurrentUserID + ".jpg");
FilePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull final Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Profile Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getUploadSessionUri().toString();
RootRef.child("Users").child(CurrentUserID).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Image Uploaded Database Successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message , Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
Glide.with(SettingsActivity.this).load(new File(resultUri.getPath())).into(set_profile_image);
}
}
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(CurrentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image")))){
String RetrieveUserName = dataSnapshot.child("name").getValue().toString();
String RetrieveProfileStatus = dataSnapshot.child("status").getValue().toString();
String RetrieveProfileImage = dataSnapshot.child("image").getValue().toString();
set_user_name.setText(RetrieveUserName);
set_profile_status.setText(RetrieveProfileStatus);
//Picasso.get().load(RetrieveProfileImage).into(set_profile_image);
Glide.with(SettingsActivity.this).load(new File(RetrieveProfileImage.)).into(set_profile_image);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
String RetrieveUserName = dataSnapshot.child("name").getValue().toString();
String RetrieveProfileStatus = dataSnapshot.child("status").getValue().toString();
set_user_name.setText(RetrieveUserName);
set_profile_status.setText(RetrieveProfileStatus);
}
else{
//set_user_name.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Please update your profile Settings", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void update_settings_button_click(View view){
UpdateSettings();
}
private void UpdateSettings() {
String setUserName = set_user_name.getText().toString();
String setProfileStatus = set_profile_status.getText().toString();
if (TextUtils.isEmpty(setUserName)){
Toast.makeText(this, "Please write your User Name", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setProfileStatus)){
Toast.makeText(this, "Please write your Status", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String , String> ProfileMap = new HashMap<>();
ProfileMap.put("uid" , CurrentUserID);
ProfileMap.put("name" , setUserName);
ProfileMap.put("status" , setProfileStatus);
RootRef.child("Users").child(CurrentUserID).setValue(ProfileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
}else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message , Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SettingsActivity.this , MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}

Related

No suitable method found for into(Uri)

I want to allow the user to upload two images,Cover and Logo.Then have them saved in firestore.I get an error at
Picasso.get().load(uri).into(Logo); line saying
no suitable method found for into(Uri)
method RequestCreator.into(Target) is not applicable
(argument mismatch; Uri cannot be converted to Target)
method RequestCreator.into(ImageView) is not applicable
(argument mismatch; Uri cannot be converted to ImageView)
package com.example.littlemarketplaceapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
public class Shop extends AppCompatActivity {
private ImageButton Logoimage;
private ImageButton Cover;
private EditText ShopnameEditText;
private TextView ShowShopName;
private Button SaveButton;
DatabaseReference databaseReference1;
private FirebaseAuth mAuth;
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference storageReference1 = FirebaseStorage.getInstance().getReference();
Uri Logo;
Uri coverUri;
private Uri uri;
int coverOrLogo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop);
Intent intent = getIntent();
String emaila = intent.getExtras().getString("emaili");
String passworda = intent.getExtras().getString("passwordi");
String fullnamea = intent.getExtras().getString("fullnamei");
String usernamea = intent.getExtras().getString("usernamei");
String mobilea = intent.getExtras().getString("mobilei");
String Shopname;
Logoimage = findViewById(R.id.shoplogobutton);
Cover = findViewById(R.id.coverphotobutton);
ShowShopName = findViewById(R.id.shopname);
ShopnameEditText = findViewById(R.id.shopnameedittext);
Shopname = ShopnameEditText.getText().toString().trim();
String key = databaseReference1.push().getKey();
//Saves Owner's Data
SaveButton.setOnClickListener(v -> {
ForOwner s_owner = new ForOwner(fullnamea, usernamea, emaila, mobilea, passworda, Shopname);
databaseReference1.child(key).setValue(s_owner);
Toast.makeText(getApplicationContext(), "Registration complete", Toast.LENGTH_SHORT).show();
});
//Uploads the Logo
Logoimage.setOnClickListener(view -> {
//open Gallery
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(openGalleryIntent, 1000);
});
//Uploads the Cover photo
Cover.setOnClickListener(view -> {
//open Gallery
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(openGalleryIntent, 2000);
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #androidx.annotation.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
Uri imageUri1 = data.getData();
Logoimage.setImageURI(imageUri1);
uploadImageToFirebase(imageUri1, 1);
} else if (requestCode == 2000 && resultCode == Activity.RESULT_OK) {
Uri imageUri2 = data.getData();
Cover.setImageURI(imageUri2);
uploadImageToFirebase(imageUri2, 0);
}
}
//}
private <final_fileRef> void uploadImageToFirebase(Uri imageUri1, int coverOrLogo) {
//upload image to firebase
StorageReference fileRef = null;
if (coverOrLogo == 1) {
fileRef = storageReference.child("logo.jpg");
} else if (coverOrLogo == 0) {
fileRef = storageReference.child("cover.jpg");
}
fileRef.putFile(imageUri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileRef.putFile(imageUri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(Uri uri) {
if (coverOrLogo == 1) {
Picasso.get().load(uri).into(Logo);
}
if (coverOrLogo == 0) {
Picasso.get().load(uri).into(Cover);
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Shop.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
In your code Logo is Uri
You need this:
Picasso.get().load(uri).into(imageView);
where imageView is ImageView object in your layout

Disabling Edittexts at start and Navigate to another activity if data not available

I have two activities SetupActivity , DashboardActivity. I'm Using Firebase Authentication and checking user existence. The flow of application for a new user is
open App->MainActivity->RegisterFragment->SetupActivity->DashboardActivity. This is my SetupActivity.Java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.kloadingspin.KLoadingSpin;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import br.com.simplepass.loadingbutton.customViews.CircularProgressButton;
import de.hdodenhof.circleimageview.CircleImageView;
public class SetupActivity extends AppCompatActivity implements LocationListener, View.OnClickListener {
private static final int REQUEST_LOCATION = 1 ;
private TextInputLayout TIPFullname, TIPCurrentLocation, TIPMobile, TIPBloodGroup, TIPLastDonated;
private TextInputEditText FullName, CurrentLocation, Mobile, BloodGroup, LastDonated;
private AutoCompleteTextView PermanentLocation;
private CircularProgressButton SaveInformationButton;
private CircleImageView ProfileImage;
private SimpleDateFormat dateFormatter;
private LocationManager locationManager;
private LocationListener locationListener;
private DatePickerDialog datePickerDialog;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
private StorageReference UserProfileImageRef;
private ValidationHelper validation;
KLoadingSpin a;
String currentUserID;
final static int Gallery_Pick = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
String[] cities = getResources().getStringArray(R.array.cities);
// Toast.makeText(this, "First select profile image and then enter details", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
a = findViewById(R.id.KLoadingSpin);
TIPFullname = findViewById(R.id.tip_fullname);
TIPCurrentLocation = findViewById(R.id.tip_curr_location);
TIPBloodGroup = findViewById(R.id.tip_blood_group);
TIPLastDonated = findViewById(R.id.tip_last_donated);
TIPMobile = findViewById(R.id.tip_mobile);
FullName = findViewById(R.id.reg_fullname);
CurrentLocation = findViewById(R.id.reg_curr_location);
Mobile = findViewById(R.id.reg_mobile);
BloodGroup = findViewById(R.id.reg_blood_group);
PermanentLocation = findViewById(R.id.reg_per_location);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.dropdown_menu_popup_item,cities);
PermanentLocation.setAdapter(adapter);
PermanentLocation.setThreshold(2);
LastDonated = findViewById(R.id.reg_last_donated);
LastDonated.setInputType(InputType.TYPE_NULL);
SaveInformationButton = findViewById(R.id.btn_save);
ProfileImage = findViewById(R.id.setup_profile_image);
validation = new ValidationHelper(this);
TIPCurrentLocation.setEndIconOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
getLocation();
}
});
SetDateTimeField();
SaveInformationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkValidation();
SaveAccountSetupInformation();
}
});
ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("profileimage")) {
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(SetupActivity.this).load(image).placeholder(R.drawable.default_profile).into(ProfileImage);
} else {
Toast.makeText(SetupActivity.this, "Please select profile image first.", Toast.LENGTH_LONG).show();
tipDisabled();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SetDateTimeField() {
LastDonated.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
LastDonated.setText(dateFormatter.format(newDate.getTime().toString()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public void onClick(View view) {
if(view == LastDonated) {
datePickerDialog.show();
}
}
private void checkValidation() {
if (!validation.isEditTextFilled(BloodGroup, TIPBloodGroup, "Enter Blood Group")) {
return;
}
if (!validation.isEditTextBloodGroup(BloodGroup, TIPBloodGroup, "Enter Correct BloodGroup!!")) {
return;
}
}
private void getLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION},
75
);
}
isLocationEnabled();
Location loc=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
String longitude = "Longitude: " +loc.getLongitude();
String latitude = "Latitude: " +loc.getLatitude();
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = " "+cityName;
CurrentLocation.setText(s);
}
private boolean isLocationEnabled(){
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
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) {
a.setVisibility(View.VISIBLE);
a.startAnimation();
a.setIsVisible(true);
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Toast.makeText(SetupActivity.this, "Please Wait", Toast.LENGTH_SHORT).show();
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UsersRef.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SetupActivity.this, "Please Wait", Toast.LENGTH_LONG).show();
Intent selfIntent = new Intent(SetupActivity.this, SetupActivity.class);
startActivity(selfIntent);
tipEnabled();
Toast.makeText(SetupActivity.this, "Your Profile image looks great!!!...", Toast.LENGTH_SHORT).show();
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
} else {
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
tipDisabled();
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
}
}
});
}
});
}
}
});
} else {
Toast.makeText(SetupActivity.this, "Error: Image not selected or not cropped", Toast.LENGTH_SHORT).show();
tipDisabled();
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
}
}
}
private void SaveAccountSetupInformation() {
String fullname = FullName.getText().toString();
String currentlocation = CurrentLocation.getText().toString();
String mobile = Mobile.getText().toString();
String permanentlocation = PermanentLocation.getText().toString();
String bloodgroup = BloodGroup.getText().toString();
String lastdonated = LastDonated.getText().toString();
if (TextUtils.isEmpty(currentlocation)) {
Toast.makeText(this, "Please click button and get your current city...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(mobile)) {
Toast.makeText(this, "Please write your mobile no...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(permanentlocation)) {
Toast.makeText(this, "Please enter your permanent city...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(fullname)) {
Toast.makeText(this, "Please enter your full name...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(bloodgroup)) {
Toast.makeText(this, "Please enter your bloodgroup...", Toast.LENGTH_SHORT).show();
}
else {
a.setVisibility(View.VISIBLE);
a.startAnimation();
a.setIsVisible(true);
SaveInformationButton.startAnimation();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
HashMap userMap = new HashMap();
userMap.put("bloodgroup", bloodgroup);
userMap.put("fullname", fullname);
userMap.put("mobile", mobile);
userMap.put("currentlocation", currentlocation);
userMap.put("permanentlocation", permanentlocation);
userMap.put("timesdonated","0");
userMap.put("lastdonatedon",lastdonated);
UsersRef.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(SetupActivity.this, "your Account is created Successfully.", Toast.LENGTH_LONG).show();
} else {
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
SaveInformationButton.revertAnimation();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Error Occured: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void tipDisabled()
{
TIPCurrentLocation.setEnabled(false);
TIPMobile.setEnabled(false);
TIPBloodGroup.setEnabled(false);
TIPFullname.setEnabled(false);
TIPLastDonated.setEnabled(false);
PermanentLocation.setEnabled(false);
}
private void tipEnabled()
{
TIPCurrentLocation.setEnabled(true);
TIPMobile.setEnabled(true);
TIPBloodGroup.setEnabled(true);
TIPFullname.setEnabled(true);
TIPLastDonated.setEnabled(true);
PermanentLocation.setEnabled(true);
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SetupActivity.this, DashboardActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
public void onLocationChanged(Location loc) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this,"Enable Location and Internet to get Location",Toast.LENGTH_LONG);
}
}
` Here i want the user to select the profile picture first and then have to fill text in edittexts. So,i need to disable all the edittexts and after the profile image is set i have to enable them. for this purpose i have written tipdisabled() and tipEnabled() methods. But i donno where to use them correctly. Please Clarify this.
You can merge your code like this:
private void tipEnabled(Boolean isEnabled)
{
TIPCurrentLocation.setEnabled(isEnabled);
TIPMobile.setEnabled(isEnabled);
TIPBloodGroup.setEnabled(isEnabled);
TIPFullname.setEnabled(isEnabled);
TIPLastDonated.setEnabled(isEnabled);
PermanentLocation.setEnabled(isEnabled);
}
To achieve your flow, put tipEnabled(false) inside your choose image click Listener and tipEnabled(true) in the onResult, which i think in your case is onActivityResult().
You should seggerate you code as right now your activity looks like a data dump which is handling too many responsibilities at the moment. Try creating Presenter classes, Controller classes or ViewModel classes to delegate all this functioning to them. You Activity should only act as a container and should not be doing validations or any logical processing but rather doing delegation.

Check if a perticular value exist in Firebase Database [duplicate]

This question already has answers here:
Checking if a particular value exists in the Firebase database
(6 answers)
Closed 2 years ago.
I'm developing an android application using java and Firebase. This is my code for creating a user profile and store the data in firebase database.
package com.eNotification.getnotify;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.eNotification.getnotify.utils.Utils;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.google.firebase.storage.UploadTask;
import com.mikhaellopez.circularimageview.CircularImageView;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.util.ArrayList;
import java.util.List;
public class MainActivityCreateProfile extends AppCompatActivity {
private static final int STORAGE_PERMISSION_CODE=1;
private TextInputLayout dUsername,dRegNo;
private TextInputEditText dEditUsername,dEditRegNo;
private CircularImageView dProfileImage;
private Spinner dCourse;
private TextView selected;
private Button dDoneBtn;
private String uid,email;
private String select="Select course",maxid,s;
private Uri selectedImage=null,uri;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private StorageReference storageReference;
private FirebaseStorage firebaseStorage;
private StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("USERS");
storageReference = firebaseStorage.getReference("Profile images");
uid = getIntent().getStringExtra("uid");
email = getIntent().getStringExtra("email");
dProfileImage = findViewById(R.id.dProfileImg);
dUsername = findViewById(R.id.dUsername);
dRegNo = findViewById(R.id.dRegNo);
dEditUsername = findViewById(R.id.dEditUsername);
dEditRegNo = findViewById(R.id.dEditReg);
selected = findViewById(R.id.course);
dCourse = findViewById(R.id.dCourse);
List<String> categories = new ArrayList<>();
categories.add(0,"Select course");
categories.add("BCA");
categories.add("BBA");
categories.add("BCOM");
categories.add("BA");
ArrayAdapter<String> dataAdapter;
dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dCourse.setAdapter(dataAdapter);
dCourse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// if (parent.getItemAtPosition(position).equals("Select course")){
// Toast.makeText(MainActivityCreateProfile.this, "Select the course", Toast.LENGTH_SHORT).show();
//} else {
selected.setText(parent.getSelectedItem().toString());
//}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivityCreateProfile.this, "Select a course", Toast.LENGTH_SHORT).show();
}
});
dDoneBtn = findViewById(R.id.dDoneBtn);
dDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputValidation();
}
});
dProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivityCreateProfile.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivityCreateProfile.this, "You have already granted permission", Toast.LENGTH_SHORT).show();
SelectImage();
} else {
requestStoragePermission();
}
}
});
}
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivityCreateProfile.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This Permission is needed for uploading the Image")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivityCreateProfile.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
SelectImage();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}
public void SelectImage() {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
selectedImage = result.getUri();
Picasso.get().load(selectedImage).into(dProfileImage);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void inputValidation() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
//Username validation
if (!Utils.inputValidation(dEditUsername)) {
Toast.makeText(this, "Enter the username", Toast.LENGTH_SHORT).show();
return;
} else if (!Utils.usernameVerify(dEditUsername)) {
Toast.makeText(this, "A Username should not exceed 15 characters", Toast.LENGTH_SHORT).show();
return;
} else {
dUsername.setErrorEnabled(false);
}
//Reg no Validation
if (!Utils.inputValidation(dEditRegNo)) {
Toast.makeText(this, "Enter the Register No", Toast.LENGTH_SHORT).show();
return;
} else if (!Utils.regNoVerify(dEditRegNo)) {
Toast.makeText(this, "Enter correct Register No", Toast.LENGTH_SHORT).show();
return;
}
createProfile();
}else {
Toast.makeText(this, "Check internet connection", Toast.LENGTH_SHORT).show();
}
}
public String GetFileExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;
}
private void createProfile(){
final String username = dEditUsername.getText().toString();
final String regNo = dEditRegNo.getText().toString();
final String course = dCourse.getSelectedItem().toString();
maxid = databaseReference.push().getKey();
if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(regNo))) {
if (!course.equals(select)) {
databaseReference.orderByChild("regNo").equalTo(regNo).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityCreateProfile.this, "Reg no. exist", Toast.LENGTH_SHORT).show();
} else {
s = "https://firebasestorage.googleapis.com/v0/b/getnotify-da5c1.appspot.com/o/Permanent%2Fuser.png?alt=media&token=017d9013-ede2-49c7-b53b-6e96d90e3398";
UserDetails userDetails = new UserDetails(s, username, regNo, course, email);
databaseReference.child(maxid).setValue(userDetails);
Toast.makeText(MainActivityCreateProfile.this, "Upload Successful", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityCreateProfile.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Select a course", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Enter username and Register No.", Toast.LENGTH_SHORT).show();
}
}
}
I'm facing a problem where i want to check whether the Register No. already exist in the database or not
and this is code to check that.
databaseReference.orderByChild("regNo").equalTo(regNo).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityCreateProfile.this, "Reg no. exist", Toast.LENGTH_SHORT).show();
} else {
s = "https://firebasestorage.googleapis.com/v0/b/getnotify-da5c1.appspot.com/o/Permanent%2Fuser.png?alt=media&token=017d9013-ede2-49c7-b53b-6e96d90e3398";
UserDetails userDetails = new UserDetails(s, username, regNo, course, email);
databaseReference.child(maxid).setValue(userDetails);
Toast.makeText(MainActivityCreateProfile.this, "Upload Successful", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityCreateProfile.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
The code works correctly. It detects if the value exist in database and shows Toast message Reg No. exist. If the value does not exist it successfully creates the child in database but it also displays Toast message Reg No. exist instead of Upload successful. I'm new to these concept so if you know anything please help.
Database node
As per Hussain Answer. addValueEventListener() is called each time there is changes in Your Database to overcome this situation you can call addListenerForSingleValueEvent(). Which will called once.
Other than that there is no Get option in Realtime Database
databaseReference.orderByChild("regNo").equalTo(regNo)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//Do what you want to try
}else{
//Create New Node in Database
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is what might be going wrong with the code. You are trying to check if the regno exist with addValueEventListener on user databaseReference.
From Android Documentation addValueEventListener does this
Add a listener for changes in the data at this location. Each time time the data changes, your listener will be called with an immutable snapshot of the data.
Therefore, when the dataSnapshot does not exists it creates a new node and eventually addValueEventListener fires again and your toast prints Reg no. exist.
What you can do is
databaseReference
.child(regNo)
.addListenerForSingleValueEvent(new ValueEventListenerAdapter() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// Document exists
} else {
// Do something
}
}
});

How can I alert the user if he doesn't pick any photo from gallery while registering?

In the register page, when a user clicks on the "ImageUserPhoto", he can pick an image from the gallery. My code works fine when he picks the photo and fills up all given fields. But if he doesn't pick any photo, the app crashes. How can I give a warning if he doesn't choose any photo in the same section where I check all the fields?
Thanks in advance!!
package com.ayon.austmart.activities;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.ayon.austmart.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import de.hdodenhof.circleimageview.CircleImageView;
public class RegisterActivity extends AppCompatActivity {
CircleImageView ImgUserPhoto;
static int PReqCode = 1;
static int REQUESCODE = 1;
Uri pickedImgUri;
private EditText userEmail, userPassword, userPassword2, userName;
private ProgressBar loadingProgress;
private Button regBtn;
private Intent homeIntent;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
userEmail = findViewById(R.id.Email);
userPassword = findViewById(R.id.Password);
userPassword2 = findViewById(R.id.ConfirmPassword);
userName = findViewById(R.id.Name);
loadingProgress = findViewById(R.id.progressBarRegister);
regBtn = findViewById(R.id.buttonRegister);
loadingProgress.setVisibility(View.INVISIBLE);
mAuth = FirebaseAuth.getInstance();
ImgUserPhoto = findViewById(R.id.avatar);
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
regBtn.setVisibility(View.INVISIBLE);
loadingProgress.setVisibility(View.VISIBLE);
final String email = userEmail.getText().toString();
final String password = userPassword.getText().toString();
final String password2 = userPassword2.getText().toString();
final String name =userName.getText().toString();
if(email.isEmpty() || name.isEmpty() || password.isEmpty() || password2.isEmpty() || !password.equals(password2))
{
//something goes wrong... display an error message
showMessage("Please verify full fields!!");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else
{
//Everything is ok..
createUserAccount(email,name,password);
}
}
});
ImgUserPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= 22)
{
checkAndRequestForPermission();
}
else
{
openGallery();
}
}
});
}
private void createUserAccount(String email, final String name, String password) {
//this method create user account with valid email and pass
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
//user account is created successfully
showMessage("Account Created!");
//now update the pro pic and username
updateUserInfo(name,pickedImgUri,mAuth.getCurrentUser());
}
else
{
showMessage("Account creation failed"+task.getException().getMessage());
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
}
});
}
private void updateUserInfo(final String name, Uri pickedImgUri, final FirebaseUser currentUser){
StorageReference mStorage = FirebaseStorage.getInstance().getReference().child("user_photos");
final StorageReference imageFilePath = mStorage.child(pickedImgUri.getLastPathSegment());
imageFilePath.putFile(pickedImgUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image uploaded successfully
//getting image url
imageFilePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// uri contains user image url
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(uri)
.build();
currentUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
//user info updated successfully
showMessage("Register Complete!");
updateUI();
}
}
});
}
});
}
});
}
private void updateUI() {
homeIntent = new Intent(getApplicationContext(), Home.class);
startActivity(homeIntent);
finish();
}
//message show
private void showMessage(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
private void openGallery() {
//Open gallery intent and wait for user to pick an image
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,REQUESCODE);
}
public void checkAndRequestForPermission()
{
if(ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(RegisterActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE))
{
Toast.makeText(RegisterActivity.this,"Please accept for required permission",Toast.LENGTH_SHORT ).show();
}
else
{
ActivityCompat.requestPermissions(RegisterActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PReqCode);
}
}
else
openGallery();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == REQUESCODE && data !=null)
{
//user has successfully picked an image...
//saving its reference to a Uri variable
pickedImgUri = data.getData();
ImgUserPhoto.setImageURI(pickedImgUri);
}
}
}
your pickedImgUri is null if the user does not select the image from gallery.
So when you call createUserAccount() when register button is clicked and user has not selected the image pickedImgUri is not updated as per your code.
Hence updateUserInfo() will fail calling an exception which causes the crash.
please add a null checker like
if(pickedImgUri!=null){
//then update the user account
}
If you are interested in forcing the user to select the profile photo then simply use above checker and alert user to please select a photo first but i'd advice against that. Not everyone likes to upload a photo. use any generic avatar png file instead when user does not want to update/remove the avatar.
Happy coding
Thanks a lot!! I have added a few lines and it worked!!! Thank you very much!!
if(email.isEmpty() || name.isEmpty() || password.isEmpty() || password2.isEmpty() || !password.equals(password2))
{
//something goes wrong... display an error message
showMessage("Please verify full fields!!");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else
{
if(pickedImgUri == null)
{
showMessage("Please select an image");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else {
createUserAccount(email, name, password);
//Everything is ok..
}
}
}
});

Selecting Image Is Greyed Out - Android Studio

I am trying to find what the issue is with this. When I go to select a photo everything on my phone is greyed out. Any ideas? and yes I have my permission set up correctly.
private EditText userName, userPassword, userEmail, userAge;
private Button regButton;
private TextView userLogin;
private FirebaseAuth firebaseAuth;
private ImageView userProfilePic;
String email, name, age, password;
private FirebaseStorage firebaseStorage;
private static int PICK_IMAGE = 123;
Uri imagePath;
private StorageReference storageReference;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data.getData() != null){
imagePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath);
userProfilePic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Full activity
package com.technicalpixels.busybuddiepav10;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
public class RegistrationActivity extends AppCompatActivity{
private EditText userName, userPassword, userEmail, userAge;
private Button regButton;
private TextView userLogin;
private FirebaseAuth firebaseAuth;
private ImageView userProfilePic;
String email, name, age, password;
private FirebaseStorage firebaseStorage;
private static int PICK_IMAGE = 123;
Uri imagePath;
private StorageReference storageReference;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data.getData() != null){
imagePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath);
userProfilePic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setupUIViews();
firebaseAuth = FirebaseAuth.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
userProfilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("images/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE);
}
});
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(validate()){
//Upload data to the database
String user_email = userEmail.getText().toString().trim();
String user_password = userPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(user_email, user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
sendEmailVerification();
sendUserData();
firebaseAuth.signOut();
Toast.makeText(RegistrationActivity.this, "Successfully Registered, Upload complete!", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}else{
Toast.makeText(RegistrationActivity.this, "Registration Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}
});
}
private void setupUIViews(){
userName = (EditText)findViewById(R.id.etUserName);
userPassword = (EditText)findViewById(R.id.etUserPassword);
userEmail = (EditText)findViewById(R.id.etUserEmail);
regButton = (Button)findViewById(R.id.btnRegister);
userLogin = (TextView)findViewById(R.id.tvUserLogin);
userAge = (EditText)findViewById(R.id.etAge);
userProfilePic = (ImageView)findViewById(R.id.ivProfile);
}
private Boolean validate(){
Boolean result = false;
name = userName.getText().toString();
password = userPassword.getText().toString();
email = userEmail.getText().toString();
age = userAge.getText().toString();
if(name.isEmpty() || password.isEmpty() || email.isEmpty() || age.isEmpty() || imagePath == null){
Toast.makeText(this, "Please enter all the details", Toast.LENGTH_SHORT).show();
}else{
result = true;
}
return result;
}
private void sendEmailVerification(){
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if(firebaseUser!=null){
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserData();
Toast.makeText(RegistrationActivity.this, "Successfully Registered, Verification mail sent!", Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
finish();
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}else{
Toast.makeText(RegistrationActivity.this, "Verification mail has'nt been sent!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void sendUserData(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic"); //User id/Images/Profile Pic.jpg
UploadTask uploadTask = imageReference.putFile(imagePath);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Upload failed!", Toast.LENGTH_SHORT).show();
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Toast.makeText(RegistrationActivity.this, "Upload successful!", Toast.LENGTH_SHORT).show();
}
});
UserProfile userProfile = new UserProfile(age, email, name);
myRef.setValue(userProfile);
}
}
Tried your code:
Replace with this:
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);

Categories