This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
Closed 2 years ago.
An image can be chosen by clicking the 'CHOOSE IMAGE' button and it will be shown in an imageview
and will be uploaded to firebase storage after clicking 'SAVE IMAGE'.If it succeeds then data about that image will be uploaded to realtime firebase database. But nothing happens after clicking the 'SAVE IMAGE' button. What is the problem there?
These are my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button chooseButton,saveButton,displayButton;
private EditText imagenameEdittext;
private ImageView imageView;
private ProgressBar progressBar;
private Uri imageUri;
private StorageReference storageReference;
private DatabaseReference databaseReference;
private StorageTask uploadTask;
private static final int IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseReference = FirebaseDatabase.getInstance().getReference("Upload");
storageReference = FirebaseStorage.getInstance().getReference("Upload");
chooseButton = findViewById(R.id.chooseImageButtonid);
saveButton = findViewById(R.id.saveImageButtonid);
displayButton = findViewById(R.id.displayImageButtonid);
progressBar = findViewById(R.id.progressbarid);
imageView = findViewById(R.id.imageviewid);
imagenameEdittext = findViewById(R.id.imagenameEdittextid);
chooseButton.setOnClickListener(this);
saveButton.setOnClickListener(this);
displayButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.chooseImageButtonid:
openFileChooser();
break;
case R.id.saveImageButtonid:
if(uploadTask!=null && uploadTask.isInProgress()){
Toast.makeText(this, "Uploading in progress", Toast.LENGTH_SHORT).show();
}
else{
saveData();
}
saveData();
break;
case R.id.displayImageButtonid:
break;
}
}
public void openFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==IMAGE_REQUEST && resultCode==RESULT_OK && data!=null && data.getData()!=null){
imageUri = data.getData();
Picasso.get().load(imageUri).into(imageView);
}
}
public String getFileExtension(Uri imageUri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(imageUri));
}
private void saveData(){
final String imageName = imagenameEdittext.getText().toString().trim();
if(imageName.isEmpty()){
imagenameEdittext.setError("Enter the image name");
imagenameEdittext.requestFocus();
return;
}
StorageReference ref = storageReference.child(System.currentTimeMillis()+"."+getFileExtension(imageUri));
ref.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
Toast.makeText(MainActivity.this, "Image is stored Successfully", Toast.LENGTH_SHORT).show();
Upload upload = new Upload(imageName,taskSnapshot.getStorage().getDownloadUrl().toString());
String uploadId = databaseReference.push().getKey();
databaseReference.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, "Image store failed", Toast.LENGTH_SHORT).show();
}
});
}
}
please can u tell me if the imageuri is not null?
try to print imageuri in log to check if it is not null.
Related
I have been struggling to get download url for an image uploaded to firebase storage from my app.
I want to send this url to firestore databse (not realtime database).
I am setting itemImageUri to uri.toString() but in onCreate() method itemImageUrl is null and shows null in firestore. I cannot use CollectionRefernece addItemRef in onSuccess method as it gives error for all string variables: Variable is accessed from within inner class needs to be declared final.
public class AddItemActivity extends AppCompatActivity {
public class AddItemActivity extends AppCompatActivity {
public static final int PICK_IMAGE_REQUEST = 1;
public static final String TAG = "Error!";
public static final String UPLOAD_TAG = "Image uploaded";
private Uri imageUri = null;
private TextInputEditText textFieldTitle;
private TextInputEditText textFieldDesc;
private AutoCompleteTextView dropdownItemType;
private TextInputEditText textFieldAddress;
private TextInputEditText textFieldAvailability;
private MaterialButton buttonSubmitItem;
private MaterialButton buttonAddImage;
private ImageView imageViewItem;
private String itemImageUrl;
private Bitmap bitmap;
private Uri itemImageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
imageViewItem = findViewById(R.id.imageView_camera);
textFieldTitle = findViewById(R.id.textField_title);
textFieldDesc = findViewById(R.id.textField_description);
dropdownItemType = findViewById(R.id.dropdown_itemType);
//Select type dropdown
String[] itemTypes = new String[] {
"Food",
"Clothing",
"Footwear"
};
ArrayAdapter<String> itemsDropdownAdpater = new ArrayAdapter<>(AddItemActivity.this, R.layout.dropdown_item_type, itemTypes);
dropdownItemType.setAdapter(itemsDropdownAdpater);
textFieldAddress = findViewById(R.id.textField_address);
textFieldAvailability = findViewById(R.id.textField_availability);
buttonAddImage = findViewById(R.id.button_addImage);
buttonSubmitItem = findViewById(R.id.button_submitItem);
buttonAddImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(AddItemActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(AddItemActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(AddItemActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
choseImage();
}
} else {
choseImage();
}
}
});
buttonSubmitItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitItem();
}
});
}
private void choseImage() {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(AddItemActivity.this);
}
private void submitItem() {
String title = textFieldTitle.getText().toString();
String desc = textFieldDesc.getText().toString();
String type = dropdownItemType.getText().toString();
String address = textFieldAddress.getText().toString();
String availability = textFieldAvailability.getText().toString();
if (title.trim().isEmpty() ||
desc.trim().isEmpty() ||
type.trim().isEmpty() ||
availability.trim().isEmpty()) {
Toast.makeText(this, "Fields cant be empty", Toast.LENGTH_SHORT).show();
return;
}
handleUpload(bitmap);
CollectionReference addItemRef = FirebaseFirestore.getInstance()
.collection("ItemList");
addItemRef.add(new ItemListModel(title, desc, type, address, availability, itemImageUrl));
Toast.makeText(this, "Item added", Toast.LENGTH_SHORT).show();
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
imageUri = result.getUri();
imageViewItem.setImageURI(imageUri);
imageViewItem.invalidate();
BitmapDrawable drawable = (BitmapDrawable) imageViewItem.getDrawable();
bitmap = drawable.getBitmap();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void handleUpload(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final StorageReference reference = FirebaseStorage.getInstance().getReference()
.child("itemImages")
.child(System.currentTimeMillis() + ".jpeg");
reference.putBytes(baos.toByteArray())
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
getItemImageUrl(reference);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "onFailure: ", e.getCause());
}
});
}
private void getItemImageUrl(StorageReference reference) {
reference.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
itemImageUrl = uri.toString();
}
});
}
}
Determining the download URL requires a call to the servers, which means it happens asynchronously. For this reason, any code that needs the download URL needs to be inside the onSuccess of getDownloadURL() or be called from there.
So:
private void getItemImageUrl(StorageReference reference) {
reference.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
itemImageUrl = uri.toString();
... here you can write itemImageUrl to the database
}
});
}
Also see:
How to get the download url from Firebase Storage?
In NodeJS, to get a link for a document stored in Firebase Storage.
const options = {
version: 'v2', // defaults to 'v2' if missing.
action: 'read',
expires: Date.now() + 1000 * 60 * 60, // one hour
};
let url = storage
.bucket(bucketname)
.file(filename)
.getSignedUrl(options);
First upload the file to the Storage, then call your upload method to the database on the addOnCompleteListener :
final StorageReference fileReference = storageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(uriList.get(i)));
uploadTask = fileReference.putFile(uriList.get(i));
uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful() && task.getException() != null) {
throw task.getException();
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
if(downloadUri != null) {
itemImageUrl = downloadUri.toString()
// create your object
// upload your object to the database here
}
}
}
});
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 want to upload video to the firebase storage inside a folder with unique names.
What i am doing current in my code is, i am trying to record a video and i want to upload it to the firebase storage.
Please review my code and help me with an appropriate answer
public class MainActivity extends AppCompatActivity {
private Uri videouri;
Button button;
private StorageReference videoRef;
private DatabaseReference ref;
private static final int REQUEST_CODE = 101;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoRef= FirebaseStorage.getInstance().getReference("videos");
ref = FirebaseDatabase.getInstance().getReference("videos");
VideoView videoView=findViewById(R.id.videoView);
button=findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
upload();
Double abc=Math.random();
Log.i("info", "onCreate: "+abc);
String filename="video";
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
videoRef =storageRef.child("/videos"+"/"+videouri+".mp4");
}
});
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
public void upload() {
if (videouri != null) {
final UploadTask uploadTask = videoRef.putFile(videouri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Success on upload", Toast.LENGTH_SHORT).show();
}
});
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
updateProgress(taskSnapshot);
}
});
} else {
Toast.makeText(this, "Nothing to Upload", Toast.LENGTH_SHORT).show();
}
}
public void updateProgress(UploadTask.TaskSnapshot taskSnapshot) {
long fileSize = taskSnapshot.getTotalByteCount();
long UploadBytes = taskSnapshot.getBytesTransferred();
long progress = (100 * UploadBytes) / fileSize;
ProgressBar progressBar = (ProgressBar) findViewById(R.id.pbar);
progressBar.setProgress((int) progress);
}
public void record(View view) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent, REQUEST_CODE);
}
protected void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode, resultCode, data);
videouri=data.getData();
if(resultCode==1){
Toast.makeText(this, "Video saved to:\n"+videouri, Toast.LENGTH_LONG).show();
}else if(resultCode==RESULT_CANCELED){
Toast.makeText(this, "RECORDING CANCELLED.", Toast.LENGTH_SHORT).show();
}else{
// Toast.makeText(this, "failed to record", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Video saved to:\n"+videouri, Toast.LENGTH_LONG).show();
}
}
}
You're setting the videoRef after you start to upload the video, which means the value is never user.
The simplest way to fix it is with something like this:
public void upload() {
if (videouri != null) {
String filename = UUID.randomUUID().toString;
videoRef = FirebaseStorage.getInstance().getReference("videos")
.child("videos").child(filename+".mp4");
final UploadTask uploadTask = videoRef.putFile(videouri);
uploadTask.addOnFailureListener(new OnFailureListener() {
...
The above will generate a unique filename every time you upload a file.
An alternative for the file name can be to base it on the current timestamp:
String filename = System.currentTimeMillis().toString;
This typically makes it easier to find new files, as they'll be at the bottom of the list. It has a small chance of not being unique, but it's not very likely in early stages.
Another alternative for the file name is to base it on the file that was selected. But in that case, uploading the same source file will end up overwriting the data on the same location on the server.
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>
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();
}
}
}