Null image on firebase storage. How to save it original? - java

I have tried to solve an issue on my app but I couldn't find a solution. I want the app to upload the images on Firebase Storage after the post is clicked. The problem is that when I click post the images are uploaded as .null and I can't add them as posts on my app here is a photo of Firebase Storage:
Here is the code of PostsActivity:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.selfcial.R;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.theartofdev.edmodo.cropper.CropImage;
import java.util.HashMap;
public class PostActivity extends AppCompatActivity {
Uri imageUri;
String myUrl;
StorageTask uploadTask;
StorageReference storageReference;
ImageView close, image_added;
TextView post;
EditText description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
close = findViewById(R.id.close);
image_added = findViewById(R.id.image_added);
post = findViewById(R.id.postPhoto);
description = findViewById(R.id.description);
storageReference = FirebaseStorage.getInstance().getReference("posts");
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PostActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
CropImage.activity()
.setAspectRatio(1, 1)
.start(PostActivity.this);
}
private String getFileExtension(Uri uri) {
ContentResolver contentResolver = this.getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void uploadImage() {
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Posting please wait..");
progressDialog.show();
if (imageUri != null) {
StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
uploadTask = fileReference.putFile(imageUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if (task.isSuccessful()) {
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();
myUrl = downloadUri.toString();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("posts");
String postId = reference.push().getKey();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("postId", postId);
hashMap.put("postImage", myUrl);
hashMap.put("description", description.getText().toString());
hashMap.put("publisher", FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.child(postId).setValue(hashMap);
progressDialog.dismiss();
startActivity(new Intent(PostActivity.this, MainActivity.class));
finish();
}else {
Toast.makeText(PostActivity.this, "Failed.", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PostActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}else {
Toast.makeText(this, "No image selected.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
imageUri = result.getUri();
image_added.setImageURI(imageUri);
}else {
Toast.makeText(this, "Something gone wrong", Toast.LENGTH_SHORT).show();
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
}
}
I thought that I have to initialize Uri inside onCreate method but nothing changed. What should it be?

I found the solution for anyone else who has the same issue, the solution is that I should have added a ! into this if, like this:
if (!task.isSuccessful()) {
throw task.getException();
}

It has been noticed that the method you are using to retrieve the file mime type doesn't work on some devices. You could try some other alternatives like using apache commonsIO lib or alternatively try this code :
public String getMimeType(Uri uri) {
String mimeType = null;
if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
ContentResolver cr = getAppContext().getContentResolver();
mimeType = cr.getType(uri);
} else {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
fileExtension.toLowerCase());
}
return mimeType;
}

Related

Task is not yet completed while using firebase

I am creating app that stores music from device to firebase. I am using Firebase storage, and database, all is working but but when I upload it it shows me progress bar with progress and after that app crashes I found that file is uploaded in storage but not came it database
Getting following error:
2020-07-08 13:57:47.766 32456-32456/xyz.hannanshaikh.firebasemusic E/AndroidRuntime: FATAL EXCEPTION: main
Process: xyz.hannanshaikh.firebasemusic, PID: 32456
java.lang.IllegalStateException: Task is not yet complete
at com.google.android.gms.common.internal.Preconditions.checkState(Unknown Source:29)
at com.google.android.gms.tasks.zzu.zzb(Unknown Source:121)
at com.google.android.gms.tasks.zzu.getResult(Unknown Source:12)
at xyz.hannanshaikh.firebasemusic.MainActivity$3.onSuccess(MainActivity.java:105)
at xyz.hannanshaikh.firebasemusic.MainActivity$3.onSuccess(MainActivity.java:98)
at com.google.firebase.storage.StorageTask.lambda$new$0(com.google.firebase:firebase-storage##19.1.1:123)
at com.google.firebase.storage.StorageTask$$Lambda$1.raise(Unknown Source:6)
at com.google.firebase.storage.TaskListenerImpl.lambda$onInternalStateChanged$2(com.google.firebase:firebase-storage##19.1.1:90)
at com.google.firebase.storage.TaskListenerImpl$$Lambda$3.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Here is code:
package xyz.hannanshaikh.firebasemusic;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "MainActivity";
private boolean checkPermission = false;
Uri uri;
String songName, songUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.nav_upload) {
if (validatePermission()) {
pickSongs();
}
}
return super.onOptionsItemSelected(item);
}
private void pickSongs() {
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload, 1);
Log.d(LOG_TAG,"Intent sent for result");
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
uri = data.getData();
Cursor mCursor = getApplicationContext().getContentResolver()
.query(uri, null, null, null);
int indexedName = Objects.requireNonNull(mCursor).getColumnIndex(OpenableColumns.DISPLAY_NAME);
mCursor.moveToFirst();
songName = mCursor.getString(indexedName);
mCursor.close();
uploadToFirebaseStorage();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadToFirebaseStorage() {
Log.d(LOG_TAG,"Method: uploadToFirebaseStorage");
StorageReference storageReference = FirebaseStorage.getInstance().getReference()
.child("Songs").child(Objects.requireNonNull(uri.getLastPathSegment()));
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.show();
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) {
Uri urlSong = uriTask.getResult();
songUrl = Objects.requireNonNull(urlSong).toString();
uploadDetailsToDatabase();
progressDialog.dismiss();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
int currentProgress = (int) progress;
progressDialog.setMessage("Uploaded: " + currentProgress + "%");
}
});
}
private void uploadDetailsToDatabase() {
Songs songObj = new Songs(songName, songUrl);
FirebaseDatabase.getInstance().getReference("Songs")
.push().setValue(songObj).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(MainActivity.this,"Song Uploaded",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//Validate permission with Dexter library
private boolean validatePermission() {
Dexter.withContext(MainActivity.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
checkPermission = true;
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
checkPermission = false;
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
return checkPermission;
}
}
I think the way you try to upload the song in the database (in Realtime Database I suppose) is wrong. In the method uploadDetailsToDatabase, write:
Declare the reference, in the begining of the class:
DatabaseReference songsDatabase;
Initialize the reference, in onCreate() method, with the path of the song table inside the database:
songsDatabase = FirebaseDatabase.getInstance().getReference("songs");
Add the song object in the realtime database:
Songs songObj = new Songs(songName, songUrl);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
songsDatabase.child(songName).setValue(songObj).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(MainActivity.this,"Song Uploaded",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
In that way, you create a data(table) in the Realtime Databse, with the name of the song, as the name of this table (songName). Inside this table, you have 2 fields: The song name, and the url of the song.
You may find usefull this answer:
how to resolve java.lang.IllegalStateException: Task is not yet complete Error when uploading image to Firebase storage?
You should avoid using while loop inside a callback listener, instead you can check on the other listener method onComplete() if the upload has been successful or not.

Breaking my neck with ProgressDialog and dismiss method issues

I've made a recipe app, i've been fixing a few issues because i couldn't get the app running but it seems that everytime a fix an error another one shows up, my project can't resolve method dismiss() i don't know what to do, i've made this app accordingly to an Youtube channel but it's giving me lots of issues, i don't know if i missed some code or if it's something else, i've also noticed that there are many things in my Dialog.java that cannot be resolved, such as setDefaultIcon, WindowDecorActionBar, #UnsupportedAppUsage, isDestroyed, setShowHideAnimationEnabled, IdRes among lots of other things, i don't even know where all of that comes from i'm a bit lost here.
This is my Upload_Recipe activity:
package com.example.recipeapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.text.DateFormat;
import java.util.Calendar;
public class Upload_Recipe extends AppCompatActivity {
ImageView recipeImage;
Uri uri;
EditText txt_name, txt_description, txt_price;
String imageUrl;
Object progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload__recipe);
recipeImage = (ImageView) findViewById(R.id.iv_foodImage);
txt_name = (EditText) findViewById(R.id.txt_recipe_name);
txt_description = (EditText) findViewById(R.id.text_description);
txt_price = (EditText) findViewById(R.id.text_price);
}
public void btnSelectImage(View view) {
Intent photoPicker = new Intent(Intent.ACTION_PICK);
photoPicker.setType("image/*");
startActivityForResult(photoPicker, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
uri = data.getData();
recipeImage.setImageURI(uri);
} else Toast.makeText(this, "Você não selecionou uma imagem", Toast.LENGTH_SHORT).show();
}
public void uploadImage() {
StorageReference storageReference = FirebaseStorage.getInstance()
.getReference()
.child("RecipeImage")
.child(uri.getLastPathSegment());
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isComplete()) ;
Uri urlImage = uriTask.getResult();
if (urlImage != null) {
imageUrl = urlImage.toString();
}
uploadRecipe();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
}
});
}
public void btnUploadRecipe(View view) {
uploadImage();
}
public void uploadRecipe() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Enviando Receita...");
progressDialog.show();
progressDialog.dismiss();
finish();
FoodData foodData = new FoodData(txt_name.getText().toString()
, txt_description.getText().toString(), txt_price.getText().toString()
, imageUrl);
String myCurrentDateTime = DateFormat.getDateTimeInstance()
.format(Calendar.getInstance().getTime());
FirebaseDatabase.getInstance()
.getReference("Recipe")
.child(myCurrentDateTime).setValue(foodData).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(Upload_Recipe.this, "Receita Enviada", Toast.LENGTH_SHORT).show();
finish();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Upload_Recipe.this, "Falha ao Enviar", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
private void ProgressDialog(Object progressDialog) {
this.progressDialog = progressDialog;
ProgressDialog(progressDialog);
}
}
You write progressDialog.dismiss(); this line into uploadRecipe method.
uploadRecipe();
progressDialog.dismiss(); //Remove this line

I can select an image from the device but it wont upload on and due to that, I am unable to create a user

For my app to register a user all it fills needs to be filled. However when I select an image when clicking on the image view; it doesn't come up, and after filling the other detail I can't create a new user due to the the imageview not being filled. I don't have no errors in my logcat.It only stopped creating a new user after implementing the Image part in the code.
package com.example.appdemo;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
public class RegistrationActivity extends AppCompatActivity {
private EditText userName, userPassword, userEmail,userAge;
private Button regButton;
private TextView userLogin;
private ImageView userProfilePic;
private FirebaseAuth firebaseAuth;
String email, name, age, password;
private FirebaseStorage firebaseStorage;
private static int PICK_IMAGE = 123;
Uri imagePath;
private StorageReference storageReference;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == PICK_IMAGE && requestCode == RESULT_OK && data.getData() != null){
imagePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imagePath);
userProfilePic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setupUIViewas();
firebaseAuth = FirebaseAuth.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
userProfilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");// for document //application/* audio/* mp3/*
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "select image"),PICK_IMAGE);
}
});
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(validate()){
//upload data to database
String user_email = userEmail.getText().toString().trim();
String user_password = userPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(user_email,user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//have to put the verification code here.
sendUserData();
// signs out user after registration and send you to login
firebaseAuth.signOut();
Toast.makeText(RegistrationActivity.this,"Registration successful",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(RegistrationActivity.this,MainActivity.class));
}else{ Toast.makeText(RegistrationActivity.this,"Registration failed please try again",Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegistrationActivity.this,MainActivity.class));
}
});
}
private void setupUIViewas(){
userName = (EditText) findViewById(R.id.etUserName);
userPassword = (EditText) findViewById(R.id.etUserPassword);
userEmail = (EditText) findViewById(R.id.etUserEmail);
regButton = (Button) findViewById(R.id.btnRegister);
userLogin = (TextView) findViewById(R.id.tvUserLogin);
userAge = (EditText) findViewById(R.id.etAge);
userProfilePic = (ImageView) findViewById(R.id.ivProfile);
}
private Boolean validate(){
Boolean result = false;
name = userName.getText().toString();
password = userPassword.getText().toString();
email = userEmail.getText().toString();
age = userAge.getText().toString();
if(name.isEmpty()|| password.isEmpty()||email.isEmpty() || age.isEmpty() || imagePath == null){
Toast.makeText(this, "Please fill in all the details", Toast.LENGTH_SHORT).show();
}else {
result = true;
}
return result;
}
private void sendUserData(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myref = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic");//User Id/Images/profile_pic.jpg
UploadTask uploadTask = imageReference.putFile(imagePath);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this,"File upload failed!",Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(RegistrationActivity.this,"File upload successful!",Toast.LENGTH_SHORT).show();
}
});
UserProfile userProfile = new UserProfile(age,email,name);
myref.setValue(userProfile);
}
}
Check the condition you wrote in onActivityResult :)
The second requestCode should be resultCode.
Change:
(requestCode == PICK_IMAGE && requestCode == RESULT_OK &&
data.getData() != null)
To:
(requestCode == PICK_IMAGE && resultCode == RESULT_OK &&
data.getData() != null)

How do I upload multiple images to Firebase's realtime database?

enter image description here
I want to upload multiple images to Firebase's realtime database. It is working with a single image, but not multiple.
I know I have to give a different path for every individual image, but I don't understand how to do this.
Could anyone help me to make changes to my code or at least guide me to solving my issue? I scoured online resources for the answer but have yet to find the answer. Thanks in advance!
How can I upload multiple images to Firebase's realtime database, based on my code what do I have to integrate/implement to do this?
package com.amazoneindia.amazone_india;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.FileNotFoundException;
import java.io.IOException;
import static android.app.Activity.RESULT_OK;
/**
* A simple {#link Fragment} subclass.
*/
public class Upload_apk extends Fragment {
Button bt1,bt2;
TextView tv;
Button btnss1,btnss2,btnss3,btnss4,btnss5;
TextView tvss1,tvss2,tvss3,tvss4,tvss5;
private EditText Name, Email, Pass, Ph, AppTitle, Appdescript;
private FirebaseAuth mAuth;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private ImageView imageView;
private ImageView imagess1,imagess2,imagess3,imagess4,imagess5;
private Uri imageUri;
public static final String FB_STORAGE_PATH = "image/";
public static final String FB_DATABASE_PATH = "image";
public static final int REQUEST_CODE=1234;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_upload_apk, container, false);
mStorageRef = FirebaseStorage.getInstance().getReference();
mDatabaseRef = FirebaseDatabase.getInstance().getReference(FB_DATABASE_PATH);
imageView = view.findViewById(R.id.etimage);
imagess1=view.findViewById(R.id.imagess1);
imagess2=view.findViewById(R.id.imagess2);
imagess3=view.findViewById(R.id.imagess3);
imagess4=view.findViewById(R.id.imagess4);
imagess5=view.findViewById(R.id.imagess5);
Name = view.findViewById(R.id.etname);
Email = view.findViewById(R.id.etemail);
Pass = view.findViewById(R.id.etpassword);
Ph = view.findViewById(R.id.etphone);
AppTitle=view.findViewById(R.id.ettitle);
Appdescript=view.findViewById(R.id.etdescrip);
tv=view.findViewById(R.id.upload_tv);
tvss1=view.findViewById(R.id.tvss1);
tvss2=view.findViewById(R.id.tvss2);
tvss3=view.findViewById(R.id.tvss3);
tvss4=view.findViewById(R.id.tvss4);
tvss5=view.findViewById(R.id.tvss5);
bt1=view.findViewById(R.id.browsebtn);
btnss1=view.findViewById(R.id.btnss1);
btnss2=view.findViewById(R.id.btnss2);
btnss3=view.findViewById(R.id.btnss3);
btnss4=view.findViewById(R.id.btnss4);
btnss5=view.findViewById(R.id.btnss5);
bt2=view.findViewById(R.id.upload_btn);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
btnss1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
btnss2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
btnss3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
btnss4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
btnss5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (imageUri!=null){
final ProgressDialog dialog=new ProgressDialog(getContext());
dialog.setTitle("Uploading Image....");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.show();
bt1.setVisibility(View.GONE);
tv.setVisibility(View.GONE);
btnss1.setVisibility(View.GONE);
tvss1.setVisibility(View.GONE);
btnss2.setVisibility(View.GONE);
tvss2.setVisibility(View.GONE);
btnss3.setVisibility(View.GONE);
tvss3.setVisibility(View.GONE);
btnss4.setVisibility(View.GONE);
tvss4.setVisibility(View.GONE);
btnss5.setVisibility(View.GONE);
tvss5.setVisibility(View.GONE);
StorageReference ref =mStorageRef.child(FB_STORAGE_PATH + System.currentTimeMillis() +"."+getImageExt(imageUri));
ref.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
dialog.dismiss();
Toast.makeText(getActivity(),"Image Uploaded",Toast.LENGTH_SHORT).show();
ImageUpload imageUpload=new ImageUpload(Name.getText().toString(),Email.getText().toString(),Pass.getText().toString(),Ph.getText().toString(),AppTitle.getText().toString(),Appdescript.getText().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploaded=mDatabaseRef.push().getKey();
mDatabaseRef.child(uploaded).setValue(imageUpload);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
dialog.dismiss();
Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int progress=(int)(100 * taskSnapshot.getBytesTransferred()/ taskSnapshot.getTotalByteCount());
dialog.setProgress(progress);
}
});
}else {
Toast.makeText(getActivity(),"Please select image",Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_CODE && resultCode == RESULT_OK && data !=null && data.getData() != null){
imageUri=data.getData();
try{
Bitmap bm= MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),imageUri);
imageView.setImageBitmap(bm);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getImageExt(Uri uri){
ContentResolver contentResolver=getActivity().getContentResolver();
MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
}
Save the picked images in a bitmap list
bitmaps[i] = MediaStore.Images.Media.getBitmap(getContentResolver(), fileList[i]);
Method for uploading multiple images to the firebase
private void uploadImages() {
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.setCancelable(false);
progressDialog.show();
uri = new Uri[bitmaps.length];
for (int i = 0; i < bitmaps.length; i++) {
if (bitmaps[i] == null) {
break;
} else {
uri[i] = getImageUri(this, bitmaps[i]);
Log.e("ImageUploadActivity", "---///" + i + "--" +
uri[i].toString());
mStorageReferenceImages = storageReference.child("images");
StorageReference ref =
mStorageReferenceImages.child(uri[i].getLastPathSegment());
ref.putFile(uri[i])
.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot
taskSnapshot)
{
progressDialog.dismiss();
Toast.makeText(ImageUploadActivity.this, "Uploaded",
Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ImageUploadActivity.this, "Failed " +
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());
progressDialog.setMessage("Uploaded " + (int)
progress + "%");
}
});
}
}
}
}
Method to convert bitmap into uri
/*--convert bitmap to uri--*/
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(),
inImage, "Title", null);
return Uri.parse(path);
}
you can add check boxes for all the image_screenshots and then when you press opload button
make a logic to findout which checkbox is selected and according to that u can upload screenshots, like logic -> when btn upload pressed add if statement to check the conditions of the checkboxes , add 3 seperate if stetments for 3 screen shots
on Button pressed{
if(checkbox1.isChecked()) { uploadimage}
if(checkbox2.isChecked()) { uploadimage}
if(checkbox3.isChecked()) { uploadimage}
}

Image is not uploading from my gallery through Bitmap

This is my RegistrationActivity.java where I want user to choose image while registering time. Everything works fine except image updation! When I register a new user and when I click in image, it opens my image gallery, I choose any image, and it back to register activity but it won't update. Also I'm unable to register because that image is not uploading successfully and I sat (if
imagepath == null), so that's why toast error is coming that fill all the details.
NOTE:
1. I tried multiple images, same issue, also I resize some images and tried.
2.There is no error in logcat.
3.Default image is showing perfectly when we first time try to register that time I sat android logo which is default.
4.I can't register without selecting any image because imagepath == null and I exactly want that user should not register if he/she not upload the image.
5.I sat imageview size :
android:layout_width="150dp"
android:layout_height="150dp"
in my activity_registration.xml file. Is there cause any problem?
package com.jimmytrivedi.loginapp;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
public class RegistrationActivity extends AppCompatActivity {
private EditText userName, userEmail, userPassword, userAge;
private Button SignUp;
private TextView userLogin;
private FirebaseAuth firebaseAuth;
private ImageView profile;
private FirebaseStorage firebaseStorage;
private static int PICK_IMAGE = 123;
String name, email, password, age;
Uri imagePath;
private StorageReference storageReference;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE && requestCode == RESULT_OK && data.getData() != null) {
imagePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath);
profile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setUpUIViews();
firebaseAuth = FirebaseAuth.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
SignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
//upload data to the database
String user_email = userEmail.getText().toString().trim();
String user_password = userPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(user_email, user_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
sendEmailVerification();
} else {
Toast.makeText(RegistrationActivity.this, "Registration failed!", Toast.LENGTH_SHORT)
.show();
}
}
});
}
}
});
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}
});
}
private void setUpUIViews() {
userName = findViewById(R.id.userName);
userEmail = findViewById(R.id.userEmail);
userPassword = findViewById(R.id.userPassword);
SignUp = findViewById(R.id.userRegister);
userLogin = findViewById(R.id.userLogin);
userAge = findViewById(R.id.userAge);
profile = findViewById(R.id.profile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE);
}
});
}
private boolean validate() {
Boolean result = false;
name = userName.getText().toString();
email = userEmail.getText().toString();
password = userPassword.getText().toString();
age = userAge.getText().toString();
if (name.isEmpty() || password.isEmpty() || email.isEmpty() || age.isEmpty()
|| imagePath == null) {
Toast.makeText(this, "Please enter all the details", Toast.LENGTH_SHORT)
.show();
} else {
result = true;
}
return result;
}
private void sendEmailVerification() {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
sendUserData();
Toast.makeText(RegistrationActivity.this, "Successfully registered, Verification email has been sent",
Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
finish();
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
} else {
Toast.makeText(RegistrationActivity.this, "Verification email hasn't been sent",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void sendUserData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myReference = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.
child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
UploadTask uploadTask = imageReference.putFile(imagePath);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Upload failed", Toast.LENGTH_SHORT)
.show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(RegistrationActivity.this, "Upload successful", Toast.LENGTH_SHORT)
.show();
}
});
UserProfile userProfile = new UserProfile(age, email, name);
myReference.setValue(userProfile);
}
}
Replace your sendUserData with this
private void sendUserData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myReference = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.
child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
imageReference.putFile(imagePath).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Upload failed", Toast.LENGTH_SHORT)
.show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(RegistrationActivity.this, "Upload successful", Toast.LENGTH_SHORT)
.show();
}
});
UserProfile userProfile = new UserProfile(age, email, name);
myReference.setValue(userProfile);
}

Categories

Resources