I trying to store an image into firebase storage with getDownloadUri but it's already deprecated so I using uri to store image but I have an error in this line: String link = uri.toString;
And the error is cannot resolve symbol uri
private DatabaseReference Userdatabase;
private StorageReference storageReference;
private FirebaseAuth firebaseAuth;
private StorageTask mUploadTask;
private Uri imageUri;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
imageView = (ImageView) findViewById(R.id.imageView);
firebaseAuth = FirebaseAuth.getInstance();
Userdatabase = FirebaseDatabase.getInstance().getReference("User");
progressDialog = new ProgressDialog(Signup.this);
storageReference = FirebaseStorage.getInstance().getReference("Seller");
signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterAccount();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
public void selectImage() {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, PICK_IMAGE_REQUEST);
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
#Override
public 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) {
imageUri = data.getData();
Picasso.with(this).load(imageUri).into(imageView);
}
}
public void RegisterAccount() {
final String email = emailText.getText().toString();
final String username = nameText.getText().toString();
final String pass = passwordText.getText().toString();
if ((TextUtils.isEmpty(address))) {
addressText.setError("address is required");
addressText.requestFocus();
return;
}
AddUser(email, username, pass, phone, comfirmpass, address);
}
public void AddUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String confirmPassword, final String Address) {
String email = UserEmail.replace(".", ",");
Userdatabase = FirebaseDatabase.getInstance().getReference("User").child(email);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String value = dataSnapshot.getValue(String.class);
Toasty.warning(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
return;
}
if (!dataSnapshot.exists()) {
if (imageUri != null) {
final StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
String link = uri.toString;
Toast.makeText(Signup.this, "Register successful", Toast.LENGTH_LONG).show();
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,
link);
Userdatabase.setValue(user);
}
});
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
firebaseAuth.createUserWithEmailAndPassword(UserEmail, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (!task.isSuccessful()) {
Log.i(TAG, "Buyer FirebaseAuth Register : Fail");
Toasty.error(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
} else {
Log.i(TAG, "Buyer FirebaseAuth Register : Success");
UserEmail.replace(".", ",");
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,link);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Userdatabase.setValue(user);
Log.i(TAG, "FirebaseDatabase Add Buyer : Success");
Toasty.success(getApplicationContext(), "Register Complete", Toast.LENGTH_SHORT, true).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w(TAG, "Database Error");
}
});
}
}
});
}
I had removed some of the code, so if you need more details pls comment below. your help is much appreciated
You are getting the following error:
cannot resolve symbol uri
Because you are calling toString() method on an object that does not exist. To solve this, please change the following line of code:
String link = uri.toString();
to
String link = downloadUri.toString();
Related
I'm so new in coding and now I'm trying to write a socialnetwork app but i faced an error and I couldn't find any answer for that.
I could save my profile picture to firebase storage successfully but it I have to connect it to database so that I can use it later.
here is my code:
public class SetUpActivity extends AppCompatActivity
{
private EditText UserName, FullName , CountryName;
private Button SaveInfoButton;
private CircleImageView UserProfileImage;
private ProgressDialog loadingBar;
private FirebaseAuth mAuth;
private DatabaseReference UserRef;
private StorageReference UserProfileImageRef;
String currentUserID;
final static int Gallery_Pick = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_up);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profile Image");
//storing profile image
UserName = (EditText) findViewById(R.id.setup_user_name);
FullName = (EditText) findViewById(R.id.setup_user_full_name);
CountryName = (EditText) findViewById(R.id.setup_user_country);
SaveInfoButton = (Button) findViewById(R.id.setup_information_button);
UserProfileImage = (CircleImageView) findViewById(R.id.set_up_profile_image);
loadingBar = new ProgressDialog( this);
SaveInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SaveAccountSetupInformation();
}
});
UserProfileImage.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_Pick);
}
});
UserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
if(snapshot.exists()) {
if (snapshot.hasChild("profileimage"))
{
String image = snapshot.child("profileimage").getValue().toString();
Picasso.get().load(image).placeholder(R.drawable.profile).into(UserProfileImage);
}
else
{
Toast.makeText(SetUpActivity.this, "Plese Select Profile Image First...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// some conditions for the picture
if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
{
Uri ImageUri = data.getData();
// crop the image
CropImage.activity(ImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
// Get the cropped image
if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{ // store the cropped image into result
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait, while we updating your profile image...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
Uri resultUri = result.getUri();
final StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
//StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UserRef.child("profileimage").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(SetUpActivity.this, "Image Stored", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SetUpActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
});
}
});
}
else
{
Toast.makeText(this, "Error Occured: Image can not be cropped. Try Again.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
private void SaveAccountSetupInformation()
{
String username = UserName.getText().toString();
String userfullname = FullName.getText().toString();
String country = CountryName.getText().toString();
if(TextUtils.isEmpty(username))
{
Toast.makeText(this,"Please Write Your UserName", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(userfullname))
{
Toast.makeText(this,"Please Write Your Full Name", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(country))
{
Toast.makeText(this,"Please Write Your Country", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Saving Information...");
loadingBar.setMessage("Please wait for a while...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
HashMap userMap = new HashMap();
userMap.put("username", username);
userMap.put("fullname", userfullname);
userMap.put("country", country);
userMap.put("status","Hey there, I am Using Pingoo");
userMap.put("gender", "none");
userMap.put("dob","None");
userMap.put("relationshipstatus","none");
UserRef.setValue(userMap).addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task)
{
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(SetUpActivity.this,"Your Account Has Been Created Successfully :) Enjoy!", Toast.LENGTH_LONG).show();
SendUserToMainActivity();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(SetUpActivity.this, "Oops!Something Went Wrong:(",Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
}
});
}
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SetUpActivity.this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
I would appreciate if anyone could give me solution cause it's my school project and I really need to do it.
I've tried to find answer but i couldn't find it anywhere :(((
thank you in advance.
I was trying to show user's profile in an activity. But when I try to do this, it only shows email. Name, photo, phone number is not showing. How can I show all the field of current user?I
I tried
getCurrentuser()
to get current user info and set them in the field. But it is not showing all the field.
SignUp.java
private EditText signUpnameId, signUpemailId,signUppasswordId,signUpPhoneId;
private Button signup_btn;
private TextView signUpSignIn;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private ImageView signUpimageView;
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
private DatabaseReference mDatabase;
private Uri imageUri;
private String imageurl;
private static final int IMAGE_REQUEST = 1;
private StorageReference storageReference,imagename;
private StorageTask uploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
this.setTitle("Sign Up Here");
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbarId);
signUpnameId = findViewById(R.id.signUpnameId);
signUpemailId = findViewById(R.id.signUpemailId);
signup_btn = findViewById(R.id.signup_btn);
signUpSignIn = findViewById(R.id.signUpSignIn);
signUppasswordId = findViewById(R.id.signUppasswordId);
signUpimageView =findViewById(R.id.signUpImageId);
signUpPhoneId = findViewById(R.id.signUpphoneId);
mDatabase = FirebaseDatabase.getInstance().getReference("Users");
storageReference = FirebaseStorage.getInstance().getReference("usersImage");
signUpSignIn.setOnClickListener(this);
signup_btn.setOnClickListener(this);
signUpimageView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.signup_btn:
userRegister();
break;
case R.id.signUpSignIn:
Intent intent = new Intent(getApplicationContext(),LogIn.class);
startActivity(intent);
break;
case R.id.signUpImageId:
if(uploadTask != null && uploadTask.isInProgress())
{
Toast.makeText(getApplicationContext(),"Upload in process.",Toast.LENGTH_SHORT).show();
}else {
showPictureDialog();
}
}
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(galleryIntent, GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY && data != null && data.getData() != null ) {
imageUri = data.getData();
try {
Picasso.get().load(imageUri).into(signUpimageView);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
private String getFileExtension(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void userRegister() {
final String name = signUpnameId.getText().toString();
final String email = signUpemailId.getText().toString().trim();
final String password = signUppasswordId.getText().toString().trim();
final String phoneNum = signUpPhoneId.getText().toString();
if(email.isEmpty())
{
signUpemailId.setError("Enter an email address");
signUpemailId.requestFocus();
return;
}
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
signUpemailId.setError("Enter a valid email address");
signUpemailId.requestFocus();
return;
}
//checking the validity of the password
if(password.isEmpty())
{
signUppasswordId.setError("Enter a password");
signUppasswordId.requestFocus();
return;
}
if(password.length() < 6)
{
signUppasswordId.setError("Password is too short. Password Should be more than 6");
signUppasswordId.requestFocus();
return;
}
//checking the validity of the password
if(name.isEmpty())
{
signUpnameId.setError("Enter a Name");
signUpnameId.requestFocus();
return;
}
if(imageUri == null)
{
signUpSignIn.setError("Please select an image first");
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful())
{
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
final StorageReference Imagename = storageReference.child("image"+imageUri.getLastPathSegment());
imageurl = imageUri.toString();
Imagename.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),"Place added Done!",Toast.LENGTH_SHORT).show();
Task<Uri> uriTask = taskSnapshot.getMetadata().getReference().getDownloadUrl();
while(!uriTask.isSuccessful());
Uri downloadUrl = uriTask.getResult();
UserInfo userInfo = new UserInfo(name,email,phoneNum,downloadUrl.toString());
String uploadId = mDatabase.push().getKey();
mDatabase.child(uploadId).setValue(userInfo);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
else
{
Toast.makeText(getApplicationContext(),"Error: "+task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
if(task.getException() instanceof FirebaseAuthUserCollisionException)
{
Toast.makeText(getApplicationContext(),"Already registered",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Eroor: "+ task.getException(),Toast.LENGTH_SHORT).show();
}
}
}
});
}
Profile.Java
private ImageView profileImageview;
private TextView profilenameview,profileemailview, profilephoneview;
private Button profilesignoutbtn;
private FirebaseUser firebaseUser;
private FirebaseAuth mAuth;
private FirebaseDatabase firebaseDatabase;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
profileImageview = findViewById(R.id.profileImageView);
profileemailview = findViewById(R.id.profileemailview);
profilenameview = findViewById(R.id.profilenameview);
profilephoneview = findViewById(R.id.profilephoneview);
progressBar = findViewById(R.id.progressbarproId);
profilesignoutbtn = findViewById(R.id.profilesignout_btn);
profilesignoutbtn.setOnClickListener(this);
// Initialize Firebase Auth
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Image");
mAuth = FirebaseAuth.getInstance();
String userKey = user.getUid();
databaseReference.child("Profile");
databaseReference.child(userKey);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("users").getValue(String.class);
profilenameview.setText(user.getDisplayName());
profileemailview.setText(user.getEmail());
Picasso.get().load(user.getPhotoUrl()).into(profileImageview);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
UserInfo.java
public class UserInfo{
String name,email,phoneNum,imageurl;
public UserInfo(String name, String email, String phoneNum, String imageurl) {
this.name = name;
this.email = email;
this.phoneNum = phoneNum;
this.imageurl = imageurl;
}
public UserInfo(String name, String email, String phoneNum, Uri uri) {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
}
Android studio is showing that
sendEmailVerification()
may produce NullPointerException. Besides
getReference()
and
getDownloadUrl()
also may produce NullPOinterException.How can I solve every issues and correctly get the expected output? Here is a screenshot of profile.
You aren't actually defining the name of the user ,
Use this in onCompleteListener method of firebase auth
new UserProfileChangeRequest.Builder()
.setDisplayName(nameUser)
.build();
First I retrieve user info from database, then I want to update the data, but when I click the "save" textview (which I already setOnClick), the progress dialog shows out, did not dismiss and the whole program just keep loading there
public class UserProfile extends Fragment {
private DatabaseReference databaseReference;
private StorageReference storageReference;
private String link;
private StorageTask mUploadTask;
private Uri imageUri;
private ProgressDialog progressDialog;
private final static int PICK_IMAGE_REQUEST = 1;
private CircleImageView circleImageView;
private EditText emailText,nameText,passwordText,confirmPasswordText,mobileText,addressText;
private TextView save;
private List<String> userList;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.user_profile, container, false);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
emailText = (EditText) view.findViewById(R.id.input_email);
nameText = (EditText) view.findViewById(R.id.input_name);
passwordText = (EditText) view.findViewById(R.id.input_password);
confirmPasswordText = (EditText) view.findViewById(R.id.input_reEnterPassword);
mobileText = (EditText) view.findViewById(R.id.input_mobile);
addressText = (EditText) view.findViewById(R.id.input_address);
circleImageView = (CircleImageView) view.findViewById(R.id.circleImageView);
save = (TextView) view.findViewById(R.id.Save);
progressDialog = new ProgressDialog(getContext());
emailText.setEnabled(false);
userList = new ArrayList<>();
String Email = getArguments().getString("Email");
String email = Email.replace(".", ",");
databaseReference = FirebaseDatabase.getInstance().getReference("User").child(email);
storageReference = FirebaseStorage.getInstance().getReference("User");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
userList.add(String.valueOf(snapshot.getValue()));
}
emailText.setText(userList.get(2));
nameText.setText(userList.get(6));
passwordText.setText(userList.get(4));
confirmPasswordText.setText(userList.get(1));
mobileText.setText(userList.get(5));
addressText.setText(userList.get(0));
Picasso.get().load(userList.get(3)).into(circleImageView);
return;
}
if (!dataSnapshot.exists()) {
Toast.makeText(getActivity(), "Data not exist!!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PICK_IMAGE_REQUEST);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
selectImage();
}
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateAccount();
}
});
return view;
}
public void selectImage() {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, PICK_IMAGE_REQUEST);
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getActivity().getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
#Override
public 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) {
imageUri = data.getData();
Picasso.get().load(imageUri).into(circleImageView);
}
}
public void UpdateAccount() {
final String email = emailText.getText().toString();
final String username = nameText.getText().toString();
final String pass = passwordText.getText().toString();
final String phone = mobileText.getText().toString();
final String comfirmpass = confirmPasswordText.getText().toString();
final String address = addressText.getText().toString();
if ((TextUtils.isEmpty(username))) {
nameText.setError("Username is required");
nameText.requestFocus();
return;
}
if ((TextUtils.isEmpty(pass))) {
passwordText.setError("Password is required");
passwordText.requestFocus();
return;
}
if ((TextUtils.isEmpty(phone))) {
mobileText.setError("Phone number is required");
mobileText.requestFocus();
return;
}
if ((TextUtils.isEmpty(comfirmpass))) {
confirmPasswordText.setError("Confirm password is required");
confirmPasswordText.requestFocus();
return;
}
if ((TextUtils.isEmpty(address))) {
addressText.setError("address is required");
addressText.requestFocus();
return;
}
progressDialog.setMessage("Updating your account");
progressDialog.show();
UpdateUser(email, username, pass, phone, comfirmpass, address);
}
public void UpdateUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String confirmPassword, final String Address) {
//first we encode the email into "," to enable check the firebase database
final String email = UserEmail.replace(".", ",");
databaseReference = FirebaseDatabase.getInstance().getReference("User").child(email);
Log.d("UserEmail", databaseReference.toString());
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
if (imageUri != null) {
final StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
link = downloadUri.toString();
final User user = new User(email, Username, Password, PhoneNumber, confirmPassword,
Address, link);
databaseReference.setValue(user);
Toasty.success(getActivity().getApplicationContext(), "Update Successful!!", Toast.LENGTH_SHORT, true).show();
progressDialog.dismiss();
}
});
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
I had removed some codes, if you need more info please leave a comment below
I has an error in this line : final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,link);
and the error is "Cannot solve symbol link"
private DatabaseReference Userdatabase;
private StorageReference storageReference;
private FirebaseAuth firebaseAuth;
private StorageTask mUploadTask;
private Uri imageUri;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
imageView = (ImageView) findViewById(R.id.imageView);
firebaseAuth = FirebaseAuth.getInstance();
Userdatabase = FirebaseDatabase.getInstance().getReference("User");
progressDialog = new ProgressDialog(Signup.this);
storageReference = FirebaseStorage.getInstance().getReference("Seller");
signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterAccount();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
public void selectImage() {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, PICK_IMAGE_REQUEST);
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
#Override
public 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) {
imageUri = data.getData();
Picasso.with(this).load(imageUri).into(imageView);
}
}
public void RegisterAccount() {
final String email = emailText.getText().toString();
final String username = nameText.getText().toString();
if ((TextUtils.isEmpty(address))) {
addressText.setError("address is required");
addressText.requestFocus();
return;
}
AddUser(email, username, pass, phone, comfirmpass, address);
}
public void AddUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String confirmPassword, final String Address) {
String email = UserEmail.replace(".", ",");
Userdatabase = FirebaseDatabase.getInstance().getReference("User").child(email);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String value = dataSnapshot.getValue(String.class);
Log.i(TAG, "UserEmail : " + value + " Had Already Exist");
Toasty.warning(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
return;
}
if (!dataSnapshot.exists()) {
if (imageUri != null) {
final StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
String link = downloadUri.toString();
Toast.makeText(Signup.this, "Register successful", Toast.LENGTH_LONG).show();
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,
link);
Userdatabase.setValue(user);
}
});
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
firebaseAuth.createUserWithEmailAndPassword(UserEmail, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (!task.isSuccessful()) {
Log.i(TAG, "Buyer FirebaseAuth Register : Fail");
Toasty.error(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
} else {
Log.i(TAG, "Buyer FirebaseAuth Register : Success");
UserEmail.replace(".", ",");
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,link);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Userdatabase.setValue(user);
Log.i(TAG, "FirebaseDatabase Add Buyer : Success");
Toasty.success(getApplicationContext(), "Register Complete", Toast.LENGTH_SHORT, true).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w(TAG, "Database Error");
}
});
}
}
});
}
I had removed some of the codes if you need more details pls leave a comment below. Anyone can help with this? your help is much appreciated
Declare link at the start of your class with the other variables, and then set link when you need it. It can't resolve symbol link because it doesn't exist in the context youre calling it.
private DatabaseReference Userdatabase;
private StorageReference storageReference;
private FirebaseAuth firebaseAuth;
private String link;
private StorageTask mUploadTask;
private Uri imageUri;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
imageView = (ImageView) findViewById(R.id.imageView);
firebaseAuth = FirebaseAuth.getInstance();
Userdatabase = FirebaseDatabase.getInstance().getReference("User");
progressDialog = new ProgressDialog(Signup.this);
storageReference = FirebaseStorage.getInstance().getReference("Seller");
signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterAccount();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
public void selectImage() {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, PICK_IMAGE_REQUEST);
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
#Override
public 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) {
imageUri = data.getData();
Picasso.with(this).load(imageUri).into(imageView);
}
}
public void RegisterAccount() {
final String email = emailText.getText().toString();
final String username = nameText.getText().toString();
if ((TextUtils.isEmpty(address))) {
addressText.setError("address is required");
addressText.requestFocus();
return;
}
AddUser(email, username, pass, phone, comfirmpass, address);
}
public void AddUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String confirmPassword, final String Address) {
String email = UserEmail.replace(".", ",");
Userdatabase = FirebaseDatabase.getInstance().getReference("User").child(email);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String value = dataSnapshot.getValue(String.class);
Log.i(TAG, "UserEmail : " + value + " Had Already Exist");
Toasty.warning(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
return;
}
if (!dataSnapshot.exists()) {
if (imageUri != null) {
final StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
link = downloadUri.toString();
Toast.makeText(Signup.this, "Register successful", Toast.LENGTH_LONG).show();
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,
link);
Userdatabase.setValue(user);
}
});
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
firebaseAuth.createUserWithEmailAndPassword(UserEmail, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (!task.isSuccessful()) {
Log.i(TAG, "Buyer FirebaseAuth Register : Fail");
Toasty.error(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
} else {
Log.i(TAG, "Buyer FirebaseAuth Register : Success");
UserEmail.replace(".", ",");
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,link);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Userdatabase.setValue(user);
Log.i(TAG, "FirebaseDatabase Add Buyer : Success");
Toasty.success(getApplicationContext(), "Register Complete", Toast.LENGTH_SHORT, true).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w(TAG, "Database Error");
}
});
}
}
});
}
You are getting that error, because the declaration of your:
String link = downloadUri.toString();
Is out of the scope. You cannot simply use the String link declared in addsuccesslistener, in your onComplete() method because is a total different scope. The String link can only be see,n in the scope where it have been declared. Beside that, both methods have an asynchronous behavior. So even if you make that variable, a global variable, it won't solve the problem. The simplest fix I can see, would be to use in your onComplete() method, the link as an empty String:
final User user = new User(
Address,
confirmPassword,
UserEmail,
Password,
PhoneNumber,
Username,
"" //empty String
);
And update accordingly, when you get it.
See also here more informations.
I am attempting to have the user upload an image and then have it then displayed as a profile picture. I am able to upload the image to firebase successfully but I am not able to display it I am following this thread
The current problem i am facing is on how to successfully get the image url to be able to display it
the current state of the code
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
//Android Layout
private CircleImageView mDisplayImage;
private TextView mName;
private TextView mStatus;
private Button mStatusBtn;
private Button mImageBtn;
private ProgressDialog mProgressDialog;
private static final int GALLERY_PICK = 1;
private StorageReference mImageStorage;
private Context context = user_profile.this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
mDisplayImage = (CircleImageView) findViewById(R.id.profile_picture);
mName = (TextView) findViewById(R.id.profile_user_name);
mStatus = (TextView) findViewById(R.id.profile_user_status);
mStatusBtn = (Button) findViewById(R.id.profile_change_status_btn);
mImageBtn = (Button) findViewById(R.id.profile_change_image_btn);
mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
mUserDatabase.keepSynced(true);
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = Objects.requireNonNull(dataSnapshot.child("name").getValue()).toString();
String status = Objects.requireNonNull(dataSnapshot.child("status").getValue()).toString();
String image = Objects.requireNonNull(dataSnapshot.child("image").getValue()).toString();
mName.setText(name);
mStatus.setText(status);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mStatusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String status_value = mStatus.getText().toString();
Intent status_intent = new Intent(user_profile.this, change_status.class);
status_intent.putExtra("status_value", status_value);
startActivity(status_intent);
}
});
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "Select Image"), GALLERY_PICK);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
String imageUri = data.getDataString();
CropImage.activity(Uri.parse(imageUri))
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog = new ProgressDialog((user_profile.this));
mProgressDialog.setTitle("Uploading");
mProgressDialog.setMessage("Pleas Stand By");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
String current_user_id = mCurrentUser.getUid();
StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + (".jpeg"));
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
final String download_url = Objects.requireNonNull(task.getResult()).getStorage().getDownloadUrl().toString();
mUserDatabase.child("image").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Glide
.with(context)
.load()
.into(mDisplayImage);
mProgressDialog.dismiss();
Toast.makeText(user_profile.this, "Succesful Upload", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(user_profile.this, "Error Up Loading", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
public String niceRefLink (String date){
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("profile_images");
return dateRef.toString();
}}
I believe the issue is with this block of code
public String niceRefLink (String date){
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("profile_images");
return dateRef.toString();
}}
When the image is attempted to be displayed glide says that it is unable to locate the image this is how my database is looking
I tried to use the method niceRefLink to display the image but I was unsuccessful i have also tried the download_url string i have created but also did not work
HI, i tried the answer you submitted but I am still having issues the image is successfully getting uploaded to the database but it is still not getting displayed when i run the app i am getting the toast upload successful but the image stays as the preview image.
private String mImageUri;
private void getUserInfo(){
mUserDatabase.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("image")!=null){
mImageUri = map.get("image").toString();
Glide.with(getApplication()).load(mImageUri).into(mDisplayImage);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This code is, How to get image url and how to display in ImageView.
private void getUserInfo(){
mCustomerDatabase.child("Users").child(current_uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("image")!=null){
mProfileImageUrl = map.get("image").toString();
Glide.with(getApplication()).load(mProfileImageUrl).into(profileImage);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Hope it's help full and Enjoy.