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

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}
}

Related

How to directly get Content URI for PDF document to other application from file path?

package com.example.emailwithattachment;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button Send;
Button attachment;
TextView tvAttachment;
String email;
String subject;
String message;
Uri URI = null;
private static final int PICK_FROM_GALLERY = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
attachment = findViewById(R.id.btAttachment);
tvAttachment = findViewById(R.id.tvAttachment);
Send = findViewById(R.id.btSend);
Send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
//attachment button listener
attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFolder();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
URI = data.getData();
tvAttachment.setText(URI.getLastPathSegment());
tvAttachment.setVisibility(View.VISIBLE);
}
}
public void sendEmail() {
File file = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DOWNLOADS), "ADSB.pdf");
try {
String email = "xyz#abc.com";
String subject = "Mail Subject Required";
String message = "Testing mails";
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{email});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
if (URI != null) {
emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
}
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
this.startActivity(Intent.createChooser(emailIntent, "Sending email..."));
} catch (Throwable t) {
Toast.makeText(this, "Request failed try again: "+ t.toString(), Toast.LENGTH_LONG).show();
}
}
public void openFolder() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
}
}
From the code above, I can select the desired PDF file and send the content URI to Mail application.
But I want to directly get the content URI from the absolute address of the pdf file(Without choosing the pdf file from the location as the location is already known). I am not getting how to do this.

I am working on OCR reader application. below is my java code. My question is how to start another method if one is completed?

When the user captures the image, the device will automatically read aloud the text. for that i have implemented texttospeech method but when this activity stop i want to start another task. how will it can be done?
After reading the captured text, I want to implement another text-to-speech method how can i do this?
package com.example.software2.ocrhy;
import static android.Manifest.permission.CAMERA;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity2 extends AppCompatActivity {
private static final int REQUEST_SPEECH = 101;
private static final int REQ_CODE_SPEECH_INPUT = 100;
Button buttonCamera;
private Button button;
private TextView mVoiceInputTv;
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
private static TextToSpeech textToSpeech;
private String stringResult = null;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mVoiceInputTv = (TextView) findViewById(R.id.textView);
textView = (TextView) findViewById(R.id.textView);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.CANADA);
textToSpeech.setSpeechRate(1f);
Toast.makeText(MainActivity2.this, "tap on the screen and say yes for read and no for return to the main menu", Toast.LENGTH_SHORT).show();
textToSpeech.speak("tap on the screen and say yes for read and no for return to the main menu", TextToSpeech.QUEUE_ADD, null);
}
}
});
}
private void textRecognizer() {
Toast.makeText(MainActivity2.this, "Tap on the screen and listen ", Toast.LENGTH_SHORT).show();
textToSpeech.speak(" Tap on the screen take a picture of any text with your device and listen", TextToSpeech.QUEUE_FLUSH, null);
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.build();
surfaceView = findViewById(R.id.surfaceView);
Context context = this;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < sparseArray.size(); ++i) {
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() != null) {
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
private void resultObtained() {
setContentView(R.layout.activity_main2);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
});
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
if (mVoiceInputTv.getText().toString().contentEquals("time and date")) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
}
if (mVoiceInputTv.getText().toString().contentEquals("battery")) {
Intent intent = new Intent(getApplicationContext(), MainActivity6.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("location")) {
Intent intent = new Intent(getApplicationContext(), MainActivity8.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("weather")) {
Intent intent = new Intent(getApplicationContext(), MainActivity5.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak( "Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("calculator")) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
else if(mVoiceInputTv.getText().toString().contentEquals("exit")) {
finish();
}
else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("yes")) {
setContentView(R.layout.surface);
surfaceView = findViewById(R.id.surfaceView);
surfaceView.setOnClickListener((View v) -> {
capture();
});
textRecognizer();
mVoiceInputTv.setText(null);
} else if (mVoiceInputTv.getText().toString().contentEquals("no")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
break;
}
}
}
public boolean onKeyDown(int keyCode, #Nullable KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
textToSpeech.speak("You are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
textToSpeech.speak("you are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
},1000);
}
return true;
}
public void buttonStart(View view) {
startVoiceInput();
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
}
just use the same mode on text to speech ADD and it will play when the first one is done, ADD = ADD, FLUSH = reset
textToSpeech.speak("this will play when first is done",
TextToSpeech.QUEUE_ADD, null);
You have to call startVoiceInput() again.
You are setting this call for an onClick() handler on a TextView already.

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

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;
}

"How to fix "Image not uploading into firebase-storage using Picasso library"

I'm trying to make a profile activity where user's data will be shown and also user can edit their data also. Everything works fine. There is no error showing in the code but when i'm trying to upload an image using camera or gallery. It's not uploading in the firebase storage. Also no "Toast" message shows. I'm fully stucked in this problem. How to solve this problem? The following code is given below:
package com.example.muthomap;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
public class Profile extends AppCompatActivity {
//views
ImageView profilephoto;
private TextView pname,pemail,pphone;
private FloatingActionButton medit;
//Instance of FirebaseAuth
private FirebaseAuth mAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
//progress Dialog
ProgressDialog progressDialog;
//permissions constants
private static final int CAMERA_REQUEST_CODE=100;
private static final int STORAGE_REQUEST_CODE=200;
private static final int IMAGE_PICK_GALLERY_REQUEST_CODE=300;
private static final int IMAGE_PICK_CAMERA_REQUEST_CODE=400;
//arrays of permissions to be requested
String cameraPermissions[];
String storagePermissions[];
//uri of picked image
Uri image_uri;
//to check either profile or cover photo
String profileOrCoverPhoto;
//storage
StorageReference storageReference;
//path where imagees of profile and cover will be stored
String storagePath = "Users_Profile_Cover_Imgs/";
public Profile(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
profilephoto= findViewById(R.id.profile_photo);
pname= findViewById(R.id.profile_name);
pemail= findViewById(R.id.profile_email);
pphone= findViewById(R.id.profile_mobile);
medit= findViewById(R.id.edit);
//Initialize the FirebaseAuth instance
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference= firebaseDatabase.getReference("user").child("customers");
storageReference = FirebaseStorage.getInstance().getReference().child(storagePath);
//intitalize arrays of permissions
cameraPermissions= new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions= new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
progressDialog= new ProgressDialog(this);
progressDialog.setMessage("Updating User.....");
/*We need to get current signed in users email,name,phone etc. And we retrive user
detail using email.*/
/* by using OrderByChild query we will show the detail from a node whose
key named email has value equal to currently signed in email.
It will search all nodes, where the key matches it will get it's detail.
*/
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//check until getting required data
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//get data
String name = "" + ds.child("name").getValue();
String email = "" + ds.child("email").getValue();
String phone = "" + ds.child("phone").getValue();
String image = "" + ds.child("image").getValue();
//set data
pname.setText(name);
pemail.setText(email);
pphone.setText(phone);
try {
Picasso.get().load(image).resize(50, 50)
.centerCrop().into(profilephoto);
} catch (Exception e) {
//if there is any exceptions while getting image then set defaults
Picasso.get().load(R.drawable.ic_default_face).into(profilephoto);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//handleing floating Button
medit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShowEditProfileDialog();
}
});
}
private boolean checkStoragePermission(){
/*check if storage permission is enebled or not
return true if enebled
return false if not
*/
boolean result = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void requestStoragePermission(){
//request runtime storage permission
requestPermissions(storagePermissions,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission(){
/*check if storage permission is enebled or not
return true if enebled
return false if not
*/
boolean result = ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission(){
//request runtime camera permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(cameraPermissions,CAMERA_REQUEST_CODE);
}
}
private void ShowEditProfileDialog() {
/*show dialog of options
*1. Upload Photo
*2. Edit Name
*3. Edit phone
*/
//options ro show in Dialog
String options[ ] = {"Upload Photo","Edit Name","Edit phone"};
//alert Dialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
//title
builder.setTitle("Choose Actions");
//set items
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
if (which == 0){
//Edit Profile picture clicked
progressDialog.setMessage("Updating Profile Picture");
profileOrCoverPhoto = "image";
showImagePicDialog();
}
else if (which == 1){
//Edit Name clicked
progressDialog.setMessage("Updating Name");
showNamePhoneUpdateDialog("name");
}
else if (which == 2){
//Edit Phone clicked
progressDialog.setMessage("Updating Phone Number");
showNamePhoneUpdateDialog("phone");
}
}
});
builder.create().show();
}
private void showNamePhoneUpdateDialog(final String key) {
//custom dialog
AlertDialog.Builder builder= new AlertDialog.Builder(Profile.this);
builder.setTitle("Update "+ key);
//set layout of dialog
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10,10,10,10);
//add edit text
final EditText editText = new EditText(Profile.this);
editText.setHint("Enter "+key);
linearLayout.addView(editText);
builder.setView(linearLayout);
//add button to update
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//input text
String val = editText.getText().toString().trim();
//validate if user has entered somethig or not
if ((!TextUtils.isEmpty(val))){
progressDialog.show();
HashMap<String, Object> results = new HashMap<>();
results.put(key, val);
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this, ""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(Profile.this, "Please Enter ", Toast.LENGTH_SHORT).show();
}
}
});
//add button to cancel
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
//create and show dialog
builder.create().show();
}
private void showImagePicDialog() {
//options containing options Camera and Gallery
String options[ ] = {"Camera","Gallery"};
//alert Dialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
//title
builder.setTitle("Pick Image From");
//set items
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
if (which == 0){
//Camera Clicked
if (!checkCameraPermission()){
requestCameraPermission();
}
else {
pickFromCamera();
}
}
else if (which == 1){
//Gallery Picked
if (!checkStoragePermission()){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestStoragePermission();
}
}
else{
pickFromGallery();
}
}
}
});
builder.create().show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
/*This method called when user press Allow or Deny from permission request dialog
here we will handle permissions cases (allowed or denied)
*/
switch (requestCode){
case CAMERA_REQUEST_CODE:{
//picking from camera, first check if camera and storage permission allowed or not
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted= grantResults[1]==PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted){
//permission enebled
pickFromCamera();
}
else {
Toast.makeText(this, "Please eneble Camera and Storage permission",Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE:{
//picking from storage, first check if storage permission allowed or not
if (grantResults.length >0 ){
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted){
//permission enebled
pickFromGallery();
}
else {
Toast.makeText(this, "Please eneble Storage permission",Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//This method will be called after picking image from Camera or Gallery
if (resultCode == RESULT_OK){
if (resultCode == IMAGE_PICK_GALLERY_REQUEST_CODE){
//image is picked from gallery , get uri of image
image_uri = data.getData();
uploadProfilePhoto(image_uri);
}
if (resultCode == IMAGE_PICK_CAMERA_REQUEST_CODE){
//image is picked from Camera, get uri
uploadProfilePhoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfilePhoto(Uri uri) {
//show progress
progressDialog.show();
/*The parameter "image_uri" contains the uri of image picked either from camera or gallery
*Will use UID of the currently signed in user as name of the image so ther will be only one image
* profile and one image for cover for each user */
//path and name of image to be stored in firebase storage
String filePathAndName = storagePath+ ""+ profileOrCoverPhoto +"_"+ user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathAndName);
storageReference2nd.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();
//check if uploading is successfull
if (uriTask.isSuccessful()){
//image uploaded
//add url in user's database
HashMap<String,Object> results = new HashMap<>();
results.put(profileOrCoverPhoto, downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//url in database of user is added successfully
//dismiss progress bar
progressDialog.dismiss();
Toast.makeText(Profile.this, "Image Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Error Updating Image", Toast.LENGTH_SHORT).show();
}
});
}
else {
//error
progressDialog.dismiss();
Toast.makeText(Profile.this, "Some Error Occurd", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
//Intent of picking image from device camera
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
//put image uri
image_uri=Profile.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
//intent to open camera
Intent cameraIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_REQUEST_CODE);
}
private void pickFromGallery() {
//pick from gallery
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_REQUEST_CODE);
}
}
Logcat: Logcat log
https://i.stack.imgur.com/2NqTU.jpg

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