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();
}
}
}
Related
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);
}
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'm making a portfolio app that stores images on firebase with navigation drawer, and when i cleck my TextView which should open get the image on firebase itcrash and says this "Unable to find explicit activity class {com.example.johan.johansteve/com.example.johan.johansteve.ImageActivity}; have you declared this activity in your AndroidManifest.xml?"
private Uri mImageUri;
//get the image and use it to upload to the database
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mUploadTask;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_portfolio, container,false);
mButtonChooseImage = v.findViewById(R.id.buttonChooseImage);
mButtonUpload = v.findViewById(R.id.uploadButton);
mTextViewShowUploads = v.findViewById(R.id.Text_View_uploads);
mEditTextFileName = v.findViewById(R.id.edit_text_file_name);
mImageView = v.findViewById(R.id.imageViewAction);
mProgressBar = v.findViewById(R.id.progress_Bar);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
//setOnClickListener method used to put actions into our views
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
//method made to choose the type of file
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()){
Toast.makeText(getContext(),"upload in progress", Toast.LENGTH_SHORT).show();
}else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImagesActivity();
}
});
return v;
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*"); // declaration of the type of file to be selected
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST); //used it for identify the type of dta we are retrieving
}
// method called when the file is selected
#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) {
//process of image selecting using comparation
mImageUri = data.getData(); //used to upload in fireBase
Picasso.get().load(mImageUri).into(mImageView);
//mImageView.setImageURI(mImageUri); native way without picasso
}
}
private String getFileExtension(Uri uri){
ContentResolver cR = getContext().getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
//this method is only used to get extension from our file eg.jpg
}
private void uploadFile(){
if (mImageUri != null){
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
private static final String TAG ="ImagesActivity ";
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
},500);
//delays the progress bar to 5 seconds so teh user gets a visual feedback
Toast.makeText(getActivity(), "Upload Successful",Toast.LENGTH_LONG).show();
/**
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getStorage().getDownloadUrl().toString());
**/
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
Log.d(TAG, "onSuccess: fireBase download url: " + downloadUrl.toString());
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),downloadUrl.toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
//create a new entry with contents the meter data of our uploads
//recycler view will use these entries to get the data from there
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
}else{
Toast.makeText(getContext(),"No File Selected",Toast.LENGTH_SHORT).show();
}
}
private void openImagesActivity(){
Intent intent = new Intent(getActivity(),ImageActivity.class);
startActivity(intent);
}}
Just add ImageActivity to AndroidManifest.xml
<application
<activity android:name="com.example.johan.johansteve.ImageActivity"/>
</application>
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.
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);