please help me, I success to pick an image with a gallery and camera. but image not showing in image view or firebase storage.
this is my manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>
this is my code to show or upload images
FirebaseAuth firebaseAuth;
FirebaseUser user;
ImageView ava,cover2;
TextView nametv,biotv;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
FloatingActionButton floatingActionButton;
ProgressDialog progressDialog;
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_CAMERA_CODE = 300;
private static final int IMAGE_PICK_GALLERY_CODE = 400;
String cameraPermissions[];
String storagePermissions[];
Uri image_uri;
String profilorcover;
StorageReference storageReference;
String storagePath = "Users_Profile_Cover_Imgs/";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_prof, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
progressDialog = new ProgressDialog(getActivity());
ava = view.findViewById(R.id.avaim);
nametv = view.findViewById(R.id.namatv);
biotv = view.findViewById(R.id.biotv);
cover2 = view.findViewById(R.id.rela);
floatingActionButton = view.findViewById(R.id.editbtn);
storageReference = getInstance().getReference();
camera permissions
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String name = ""+ ds.child("name").getValue();
String email = ""+ ds.child("email").getValue();
String bio = ""+ ds.child("bio").getValue();
String image = ""+ ds.child("image").getValue();
String cover = ""+ds.child("cover").getValue();
nametv.setText(name);
biotv.setText(bio);
try {
Picasso.get().load(image).into(ava);
}
catch (Exception e){
Picasso.get().load(R.drawable.ic_cam_name).into(ava);
}
try {
Picasso.get().load(cover).into(cover2);
}
catch (Exception e){
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editprofil();
}
});
return view;
}
private boolean checkstorage(){
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
private void reqstorage(){
requestPermissions(storagePermissions, STORAGE_REQUEST_CODE);
}
private boolean checkcam(){
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void reqcam(){
requestPermissions(cameraPermissions, CAMERA_REQUEST_CODE);
}
private void editprofil() {
String pengaturan[] = {"Edit Foto Profil", "Edit Foto Sampul", "Edit Nama", "Edit Bio"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Edit Profil");
builder.setItems(pengaturan, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0){
progressDialog.setMessage("Mengubah Profil");
profilorcover = "image";
showimage();
}
else if (i == 1){
progressDialog.setMessage("Mengubah Profil");
profilorcover = "cover";
showimage();
}
else if (i == 2){
progressDialog.setMessage("Mengubah Profil");
shownamebio("name");
}
else if (i == 3){
progressDialog.setMessage("Mengubah Profil");
shownamebio("bio");
}
}
});
builder.create().show();
}
private void showimage() {
String pengaturan[] = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Edit Profil");
builder.setItems(pengaturan, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0){
if (!checkcam()){
reqcam();
}
else{
memilih();
}
}
else if (i == 1){
if (!checkstorage()){
reqstorage();
}
else{
memilihgal();
}
}
}
});
builder.create().show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length >0){
boolean cameraacc = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writestor = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraacc && writestor){
memilih();
}
else {
Toast.makeText(getActivity(), "Setujui Kamera dan File Manager", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE:{
if (grantResults.length >0){
boolean writestor = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(writestor){
memilihgal();
}
else {
Toast.makeText(getActivity(), "Setujui File Manager", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == RESULT_OK){
if(requestCode == IMAGE_PICK_GALLERY_CODE){
image_uri = data.getData();
uploadprofile(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE){
uploadprofile(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadprofile(Uri uri) {
progressDialog.show();
String file = storagePath+ ""+ profilorcover +"_"+ user.getUid();
StorageReference storageReference2 = storageReference.child(file);
storageReference2.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloaduri = uriTask.getResult();
if (uriTask.isSuccessful()){
HashMap<String, Object> results = new HashMap<>();
results.put(profilorcover, downloaduri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Mengubah Gambar...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Tidak dapat mengubah gambar...", Toast.LENGTH_SHORT).show();
}
});
}
else{
progressDialog.dismiss();
Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void memilih() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent camerai = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camerai.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(camerai, IMAGE_PICK_CAMERA_CODE);
}
private void memilihgal() {
Intent gall = new Intent(Intent.ACTION_PICK);
gall.setType("image/*");
startActivityForResult(gall, IMAGE_PICK_GALLERY_CODE);
}
}
database
rule database
The way you're getting the download URL looks fishy. Having any sort of while (!uriTask.isSuccessful()); in your Android code is unlikely to ever give the desired result.
This is how I'd normalize it:
String file = storagePath+ ""+ profilorcover +"_"+ user.getUid();
StorageReference storageReference2 = storageReference.child(file);
storageReference2.putFile(uri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
HashMap<String, Object> results = new HashMap<>();
results.put(profilorcover, downloaduri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Mengubah Gambar...", Toast.LENGTH_SHORT).show();
}
}
});
} else {
progressDialog.dismiss();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
This is a pretty direct merge of your code with the flow from the Firebase documentation on getting a download URL after uploading an image.
That problem in the code requestcode == result_ok. That must change like resultcode==result_ok. That's why my problem solved.
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == RESULT_OK){
requestCode replace wirh resultCode.
if(requestCode == IMAGE_PICK_GALLERY_CODE){
image_uri = data.getData();
uploadprofile(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE){
uploadprofile(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Related
I was watching YouTube for the instruction implementing storing image to firebase storage.
But, I got an error with getDownloadUrl() I do not know why, it was given codes from firebase helper.
public class SellerPage extends AppCompatActivity {
EditText Address;
EditText price;
EditText description;
Button register;
Button chooseImage;
private FirebaseAuth auth;
private FirebaseFirestore mFirestore;
private StorageReference mStorageRef;
private static final int RESULT_LOAD_IMAGE = 1;
private static final int IMAGE_PICK_CODE = 1000;
private static final int PERMISSION_CODE = 1001;
ImageView View;
public Uri imgUir;
private StorageTask uploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_page);
auth = FirebaseAuth.getInstance();
mFirestore= FirebaseFirestore.getInstance();
mStorageRef = FirebaseStorage.getInstance().getReference("Images"); // Storage for the image
Address = (EditText) findViewById(R.id.Address);
price = (EditText) findViewById(R.id.Price);
description = (EditText) findViewById(R.id.description);
register = (Button) findViewById(R.id.addButton);
chooseImage = (Button) findViewById(R.id.image);
View = (ImageView) findViewById(R.id.imageView);
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Check runtime permission
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
// permission not granted. then request it
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissions, PERMISSION_CODE);
}else{
//permition already granted
pickImageFromGallay();
}
}else{
// OS is less than marshmello
pickImageFromGallay();
}
}
}
);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FileUploader();
addSellerInfo();
}
});
}
private void pickImageFromGallay(){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE && data != null){
imgUir = data.getData();
View.setImageURI(data.getData());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case PERMISSION_CODE:{
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
pickImageFromGallay();
}else{
Toast.makeText(this,"Permission denied!", Toast.LENGTH_SHORT).show();
}
}
}
}
private String getExtension(Uri uri){
ContentResolver cr = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
private void FileUploader(){
final StorageReference Ref = mStorageRef.child(System.currentTimeMillis()+ "." + getExtension(imgUir));
Ref.putFile(imgUir)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(SellerPage.this, "Uploading Image Successful", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
public void addSellerInfo(){
FirebaseUser user = auth.getCurrentUser();
String ID = user.getUid();
String addressStr = Address.getText().toString().trim();
String priceStr = price.getText().toString().trim();
String descriptionStr = description.getText().toString().trim();
CollectionReference parkspaces = mFirestore.collection("parkspaces");
sellerData parkspace = new sellerData(ID, addressStr, priceStr, descriptionStr);
parkspaces.add(parkspace);
}
}
call getDownloadUrl(), the call is asynchronous and you must subscribe on a success callback to obtain the results:
Ref.putFile(imgUir)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadPhotoUrl) {
Log.e("downloaduri", downloadPhotoUrl.toString());
Toast.makeText(SellerPage.this, "Uploading Image Successful", Toast.LENGTH_LONG).show();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
I wrote a code that lets people sign up to my up, but when I press the button the new user isn't created in the database (it stays null) what can i do?
here is the SignUpActivity.java:
public class SignUpActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText userEmail, userPassword1, userPassword2, userCode, userName, userDescription;
private ImageView image;
private ProgressDialog pDialog;
private boolean imagePressed = false;
private Uri filePath;
private FirebaseStorage storage;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
userCode = findViewById(R.id.userCode);
userDescription = findViewById(R.id.userDescription);
userEmail = findViewById(R.id.userEmail);
userName = findViewById(R.id.userName);
userPassword1 = findViewById(R.id.userPassword1);
userPassword2 = findViewById(R.id.userPassword2);
image = findViewById(R.id.userImageAdd);
mAuth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imagePressed = true;
chooseImage();
}
});
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Finals.PICK_IMAGE_REQUEST);
}
public void back(View view) {
finish();
}
public void submit(View view) {
pDialog = new ProgressDialog(this);
if (TextUtils.isEmpty(userEmail.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please enter email.", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(userPassword1.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please enter password.", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(userPassword2.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please repeat password.", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(userName.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please enter user name", Toast.LENGTH_SHORT).show();
} else if (!userPassword1.getText().toString().equals(userPassword2.getText().toString())) {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "The passwords don't match.", Toast.LENGTH_SHORT).show();
} else {
pDialog.setMessage("Creating account...");
pDialog.show();
pDialog.setCanceledOnTouchOutside(false);
if (imagePressed && filePath != null) {
final StorageReference ref = storageReference.child("users/" + UUID.randomUUID().toString());
ref.putFile(filePath).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downUri = task.getResult();
boolean isTrainer = trainer();
register(userEmail.getText().toString(), userPassword1.getText().toString(), userName.getText().toString(), userDescription.getText().toString(),
downUri.toString(), isTrainer);
}
}
});
} else {
boolean isTrainer = trainer();
register(userEmail.getText().toString(), userPassword1.getText().toString(), userName.getText().toString(), userDescription.getText().toString(),
Finals.DEFAULT_USER_IMAGE_URL, isTrainer);
finish();
}
}
}
private boolean trainer() {
boolean trainer = false;
if (!TextUtils.isEmpty(userCode.getText())) {
if (userCode.getText().toString().equals(Finals.T_CODE))
trainer = true;
else if (!userCode.getText().toString().equals(Finals.T_CODE)) {
pDialog.dismiss();
Toast.makeText(this, "Not a real trainer code!", Toast.LENGTH_SHORT).show();
}
}
return trainer;
}
private void register(final String regEmail, final String regPassword,
final String regName, final String regDesc, final String url, final boolean trainer) {
mAuth.createUserWithEmailAndPassword(regEmail, regPassword).addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser firebaseUser = mAuth.getCurrentUser();
String userId = firebaseUser.getUid();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("id", mAuth.getCurrentUser().getUid());
hashMap.put("name", regName);
hashMap.put("description", regDesc);
hashMap.put("isTrainer", trainer);
hashMap.put("imageUrl", url);
FirebaseDatabase.getInstance().getReference().child("users").child(userId).setValue(hashMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "Created user", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
} else {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
});
} else {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "Creation failed :" + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Finals.PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
this used to work on my previous phone but now it doesn't work on the new phone.
what could cause this bug?
Also the progress dialog wont show either.
when I try to access the code (say in this line - DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users").child(id);) it returns null.
I don't get the "Something went wrong" either, it just goes to the LoginActivity (not the main Activity for whatever reason) who called it , and then I can login using the new user i created but can't access the data(it's null).
These are the database rules:
{
"rules": {
".read": true,
".write": true
}
}
Somehow, rewriting the code differently fixed the bug
new code -
private Context mContext;
private String email, username, password1, password2, trainerCode, description, imageUrl = Finals.DEFAULT_USER_IMAGE_URL;
private EditText mEmail, mPassword1, mPassword2, mUsername, mTrainerCode, mDescription;
private Button btnSubmit, btnBack;
private ImageView imageView;
private ProgressDialog pDialog;
private String userID;
private boolean isTrainer, imagePressed = false;
private Uri filePath;
//firebase
private FirebaseAuth mAuth;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseStorage storage;
private StorageReference storageReference;
private View.OnClickListener imageClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
imagePressed = true;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Finals.PICK_IMAGE_REQUEST);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
mContext = SignUpActivity.this;
pDialog = new ProgressDialog(this);
mEmail = findViewById(R.id.userEmail);
mUsername = findViewById(R.id.userName);
btnSubmit = findViewById(R.id.btn_submit);
mPassword1 = findViewById(R.id.userPassword1);
mPassword2 = findViewById(R.id.userPassword2);
mTrainerCode = findViewById(R.id.userCode);
mDescription = findViewById(R.id.userDescription);
imageView = findViewById(R.id.userImageAdd);
btnBack = findViewById(R.id.backBtn);
btnSubmit.setOnClickListener(btnSubmitListener);
imageView.setOnClickListener(imageClickListener);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
}
private View.OnClickListener btnSubmitListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
email = mEmail.getText().toString();
username = mUsername.getText().toString();
password1 = mPassword1.getText().toString();
password2 = mPassword2.getText().toString();
trainerCode = mTrainerCode.getText().toString();
description = mDescription.getText().toString();
isTrainer = false;
if (checkInputs(email, username, password1, password2, trainerCode)) {
pDialog.setMessage("Creating User...");
pDialog.show();
if (imagePressed && filePath != null)
uploadImage();
else
registerNewUser();
}
}
};
private void uploadImage() {
final StorageReference ref = storageReference.child("users/" + UUID.randomUUID().toString());
ref.putFile(filePath).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
Uri downUri = task.getResult();
imageUrl = downUri.toString();
registerNewUser();
}
});
}
public void registerNewUser() {
mAuth.createUserWithEmailAndPassword(email, password1)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
} else {
userID = mAuth.getCurrentUser().getUid();
addNewUser();
}
}
});
}
private boolean checkInputs(String email, String name, String password1, String password2, String trainerCode) {
if (email.equals("")) {
Toast.makeText(mContext, "Please enter email", Toast.LENGTH_SHORT).show();
return false;
}
if (name.equals("")) {
Toast.makeText(mContext, "Please enter name", Toast.LENGTH_SHORT).show();
return false;
}
if (password1.equals("")) {
Toast.makeText(mContext, "Please enter password", Toast.LENGTH_SHORT).show();
return false;
}
if (password2.equals("")) {
Toast.makeText(mContext, "Please repeat password", Toast.LENGTH_SHORT).show();
return false;
}
if (!password1.equals(password2)) {
Toast.makeText(mContext, "Passwords don't natch", Toast.LENGTH_SHORT).show();
return false;
}
if (!trainerCode.equals("")) {
if (trainerCode.equals(Finals.T_CODE)) {
isTrainer = true;
return true;
} else {
Toast.makeText(mContext, "Not a real trainer code!", Toast.LENGTH_SHORT).show();
return false;
}
}
return true;
}
public void addNewUser() {
UserClass user = new UserClass(description, email, userID, imageUrl, isTrainer, username, password1);
myRef.child("users").child(userID).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
pDialog.dismiss();
Toast.makeText(mContext, "Created new User", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Finals.PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks a lot to all of you who have tried to help!
txt_category.getText().toString() this is not coming. It is coming null. Image url is coming but text is not coming in onActivityResult(). I want a single id in which both text category name and image should come. How can get editText from dialog box and put in hashMap inonactivity() method. App crashes everytime I because of null object reference. Not able to get text from the dialog box editText. It is coming null everytime. Image url is coming but text is not coming in onActivityResult(). I want a single id in which both category name and image should come. txt_category.getText().toString() this is not coming. It is coming null. Image url is coming but text is not coming in onActivityResult().
public class HomeFragment extends Fragment {
private DatabaseReference Rootref;
String d;
HashMap < String, String > hashMap, hashMap1;
FirebaseAuth mAuth;
FirebaseRecyclerAdapter adapter;
FirebaseUser firebaseUser;
private String currentUserId;
EditText txt_category;
Button btnSelect, btnUpload;
private ProgressDialog mProgressDialog;
String id;
private StorageReference imgStorageReference;
RecyclerView recycler_category;
Button btn_category, btn_subcat;
private static final int GALLERY_PICK = 1;
String catName;
public static final String UPDATE = "UPDATE";
public static final String DELETE = "DELETE";
View view;
TextView txt;
public HomeFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home, container, false);
intialise();
return view;
}
private void intialise() {
imgStorageReference = FirebaseStorage.getInstance().getReference();
hashMap1 = new HashMap < > ();
recycler_category.setLayoutManager(glm);
id = UUID.randomUUID().toString();
btn_category = view.findViewById(R.id.btn_category);
showDialog();
btn_category.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog()
}
});
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Enter Category Name : ");
builder.setMessage("Please fill full information");
LayoutInflater inflater = HomeFragment.this.getLayoutInflater();
final View custom_layout =
inflater.inflate(R.layout.custom_dialog_category, null);
btnSelect = custom_layout.findViewById(R.id.btnSelect);
btnUpload = custom_layout.findViewById(R.id.btnUpload);
builder.setView(custom_layout);
builder.setIcon(R.drawable.ic_shopping_cart_black_24dp);
Rootref = FirebaseDatabase.getInstance().getReference("Category");
final EditText txt_category =
custom_layout.findViewById(R.id.edit_text_cat);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImage();
}
});
builder.show();
}
private void chooseImage() {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(getContext(), HomeFragment.this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
Uri imageURI = data.getData();
CropImage.activity(imageURI).
setAspectRatio(1, 1).start(getContext(), HomeFragment.this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setTitle("Saving Changes");
mProgressDialog.setMessage("Wait untill changes are saved");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
StorageReference filepath =
imgStorageReference.child("Profile_images").child(id + ".jpg");
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener < UploadTask.TaskSnapshot > () {
#Override
public void onComplete(#NonNull Task < UploadTask.TaskSnapshot > task) {
if (task.isSuccessful()) {
imgStorageReference.child("Profile_images").
child(id + ".jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener < Uri > () {
#Override
public void onSuccess(Uri uri) {
String downloadUrl = uri.toString();
hashMap.put("imageURL", downloadUrl);
hashMap.put("category", txt_category.getText().toString());
Rootref.push().setValue(hashMap).addOnCompleteListener(new
OnCompleteListener < Void > () {
#Override
public void onComplete(#NonNull Task < Void > task) {
if (task.isSuccessful()) {
mProgressDialog.dismiss();
Toast.makeText(getContext(), " Image Updated",
Toast.LENGTH_SHORT).show();
onResume();
}
}
});
}
});
}
Toast.makeText(SettingsActivity.this, "Working",
Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getContext(), "Not Working",
Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
}
});
} else if (resultCode ==
CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
I want to upload a image to my Firebase Storage bucket, but it always returns a value from OnFailureListener.
Here's the code:
public class AddProductFragment extends Fragment {
private static final int IMAGE_REQUEST = 1;
private ProgressDialog progressDialog;
private Uri uri;
private EditText mTitle,mPrice;
private Button mBtn,mUpload;
private ImageView mImage;
private FirebaseStorage mStorageRef;
private StorageReference mRef;
public AddProductFragment() {
mStorageRef = FirebaseStorage.getInstance();
mRef = mStorageRef.getReference().child("images");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.add_product_fragment,container,false);
find(v);
onClick();
return v;
}
private void find(View v) {
mTitle = (EditText)v.findViewById(R.id.singleProductTitle);
mPrice = (EditText)v.findViewById(R.id.singleProductPrice);
mBtn = (Button) v.findViewById(R.id.addProductSelectImageBtn);
mImage = (ImageView)v.findViewById(R.id.addProductImage);
mUpload = (Button)v.findViewById(R.id.uploadBtn);
}
private void onClick() {
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select Picture"), IMAGE_REQUEST);
}
});
mUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMax(100);
progressDialog.setMessage("Uploading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
progressDialog.setCancelable(false);
String title = mTitle.getText().toString();
String price = mPrice.getText().toString();
if (!title.isEmpty() && !price.isEmpty()) {
Product product = new Product();
Uri file = Uri.fromFile(new File(getRealPathFromURI(uri)));
mRef.child("original").child(product.getStringId());
mRef.putFile(file).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//sets and increments value of progressbar
progressDialog.incrementProgressBy((int) progress);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "Error uploading....", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(getActivity(),"Upload successful",Toast.LENGTH_SHORT).show();
//TODO: redirect to the uploaded product;
progressDialog.dismiss();
}
});
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == IMAGE_REQUEST && resultCode == RESULT_OK) {
try {
uri = data.getData();
Bitmap bitmap = null;
if(uri != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
mImage.setImageBitmap(bitmap);
} else {
Toast.makeText(getActivity(), "Uri not found...", Toast.LENGTH_SHORT).show();
}
} catch (NullPointerException e) {
e.getMessage();
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String thePath = "no-path-found";
String[] filePathColumn = {MediaStore.Images.Media.DISPLAY_NAME};
Cursor cursor = getActivity().getContentResolver().query(contentURI, filePathColumn, null, null, null);
if(cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
thePath = cursor.getString(columnIndex);
}
cursor.close();
return thePath;
}
}
Here is the exception:
/com.example.cmd.pop E/StorageException:
/image-0-02-05-64dcdbd29d607a4421b258b2adbfb848cf3262ee096a8b0ab2dbecd22631feea-V.jpg:
open failed: ENOENT (No such file or directory)
java.io.FileNotFoundException:
/image-0-02-05-64dcdbd29d607a4421b258b2adbfb848cf3262ee096a8b0ab2dbecd22631feea-V.jpg:
open failed: ENOENT (No such file or directory)
Anyway i found the solution, the reference path was wrong
Changes in constructor
public AddProductFragment() {
mStorageRef = FirebaseStorage.getInstance();
mRef = mStorageRef.getReference().child("images/original/");
mThumbRef = mStorageRef.getReference().child("images/thumb");
}
And OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK) {
uri = data.getData();
String title = mTitle.getText().toString();
String price = mPrice.getText().toString();
if (!title.isEmpty() && !price.isEmpty()) {
Product product = new Product();
StorageReference thumbRef = mRef.child(product.getStringId()).child(uri.getLastPathSegment());
StorageReference imageRef = mRef.child(product.getStringId()).child(uri.getLastPathSegment());
imageRef.putFile(uri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d(TAG, e.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(getActivity(), "Upload successful", Toast.LENGTH_SHORT).show();
//TODO: redirect to the uploaded product;
}
});
thumbRef.putFile(uri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d(TAG, e.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(getActivity(), "Upload successful", Toast.LENGTH_SHORT).show();
//TODO: redirect to the uploaded product;
}
});
}
}
}
And added permission to manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
i'm using the firebase database for my chat application, When i click on the deactivate button it deletes the user from the Authentication section of firebase but not from the database section of firebase and my all user activity retrieve the user data from the database section. because of this when a user deactivate his account it get delete, but his account is still visible to the other user. below this i'm attaching my codes..
public class SettingsActivity extends AppCompatActivity{
ImageView ivCamera;
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
private CircleImageView mDisplayImage;
private TextView mName;
private TextView mStatus;
private Button mProfileBtn;
private Button mDeactivateBtn;
//private Button mImageBtn;
private static final int GALLERY_PICK = 1;
private StorageReference mImageStorage;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mDisplayImage = (CircleImageView) findViewById(R.id.settings_image);
mName = (TextView) findViewById(R.id.settings_name);
mStatus = (TextView) findViewById(R.id.settings_status);
mProfileBtn = (Button) findViewById(R.id.settings_profile_btn);
mDeactivateBtn = (Button) findViewById(R.id.deactivate_btn);
ivCamera = (ImageView) findViewById(R.id.ivCamera);
mProgressDialog = new ProgressDialog(this);
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 = dataSnapshot.child("name").getValue().toString();
final String image = dataSnapshot.child("image").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
mName.setText(name);
mStatus.setText(status);
if (!image.equals("default")) {
//Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
Picasso.with(SettingsActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.avatar).into(mDisplayImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//ivGallery =(ImageView) findViewById(R.id.ivGallery);
//ivGallery.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//}
//});
mProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name_value = mName.getText().toString();
String status_value = mStatus.getText().toString();
Intent status_Intent = new Intent(SettingsActivity.this, StatusActivity.class);
status_Intent.putExtra("status_value", status_value);
status_Intent.putExtra("name_value", name_value);
startActivity(status_Intent);
}
});
ivCamera.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, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri).setAspectRatio(1, 1).start(this);
//Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_LONG).show();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog = new ProgressDialog(SettingsActivity.this);
mProgressDialog.setTitle("Uploading Image.....");
mProgressDialog.setMessage("Please wait while we upload and process the image.");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
File thumb_filePath = new File(resultUri.getPath());
String current_user_id = mCurrentUser.getUid();
Bitmap thumb_bitmap = new Compressor(this)
.setMaxWidth(200)
.setMaxHeight(200)
.setQuality(75)
.compressToBitmap(thumb_filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final byte[] thumb_byte = baos.toByteArray();
StorageReference filePath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
final StorageReference thumb_filepath = mImageStorage.child("profile_images").child("thumbs").child(current_user_id + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
final String download_url = task.getResult().getDownloadUrl().toString();
UploadTask uploadTask = thumb_filepath.putBytes(thumb_byte);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
String thumb_downloadUrl = thumb_task.getResult().getDownloadUrl().toString();
if (thumb_task.isSuccessful()) {
Map update_hashMap = new HashMap();
update_hashMap.put("image", download_url);
update_hashMap.put("thumb_image", thumb_downloadUrl);
mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mProgressDialog.dismiss();
Toast.makeText(SettingsActivity.this, "Success Uploading.", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error in Uploading thumbnail.", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error in Uploading.", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
public static String random() {
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(10);
char tempChar;
for (int i = 0; i < randomLength; i++) {
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
}
return randomStringBuilder.toString();
}
public void deactivate(View view)
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user!=null)
{
mProgressDialog.setTitle("Deactivate Account");
mProgressDialog.setMessage("Deactivating...");
mProgressDialog.show();
mUserDatabase.child(mCurrentUser.getUid()).removeValue();
user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Account is Deactivated", Toast.LENGTH_LONG).show();
finish();
Intent intent = new Intent(SettingsActivity.this, RegisterActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Account could not be Deactivate", Toast.LENGTH_LONG).show();
}
mProgressDialog.dismiss();
}
});
}
}
}
i want that when the user deactivate his account it will not visible anymore in the all user activity
There are multiple ways to doing this.
When you delete account of user. You should delete all nodes attaching to that user. so that any activity related to user will not be visible to other users.!
if you don't want to remove from database section. you can put another key value with the name of status. if user status is deleted or disable. don't fetch the data of that user in activity.
Hope this will help you to answer your question.
if you've still questions in your mind, you can ask.
For deleting child:
rootRef.child(node).removeValue();
Simple deleting the node.
you can customize it according to your need.
DatabaseReference delete = FirebaseDatabase.getInstance().getReference().child("Node");
delete.setValue(null);