This question already has answers here:
Checking if a particular value exists in the Firebase database
(6 answers)
Closed 2 years ago.
I'm developing an android application using java and Firebase. This is my code for creating a user profile and store the data in firebase database.
package com.eNotification.getnotify;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.eNotification.getnotify.utils.Utils;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
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.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.google.firebase.storage.UploadTask;
import com.mikhaellopez.circularimageview.CircularImageView;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.util.ArrayList;
import java.util.List;
public class MainActivityCreateProfile extends AppCompatActivity {
private static final int STORAGE_PERMISSION_CODE=1;
private TextInputLayout dUsername,dRegNo;
private TextInputEditText dEditUsername,dEditRegNo;
private CircularImageView dProfileImage;
private Spinner dCourse;
private TextView selected;
private Button dDoneBtn;
private String uid,email;
private String select="Select course",maxid,s;
private Uri selectedImage=null,uri;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private StorageReference storageReference;
private FirebaseStorage firebaseStorage;
private StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("USERS");
storageReference = firebaseStorage.getReference("Profile images");
uid = getIntent().getStringExtra("uid");
email = getIntent().getStringExtra("email");
dProfileImage = findViewById(R.id.dProfileImg);
dUsername = findViewById(R.id.dUsername);
dRegNo = findViewById(R.id.dRegNo);
dEditUsername = findViewById(R.id.dEditUsername);
dEditRegNo = findViewById(R.id.dEditReg);
selected = findViewById(R.id.course);
dCourse = findViewById(R.id.dCourse);
List<String> categories = new ArrayList<>();
categories.add(0,"Select course");
categories.add("BCA");
categories.add("BBA");
categories.add("BCOM");
categories.add("BA");
ArrayAdapter<String> dataAdapter;
dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dCourse.setAdapter(dataAdapter);
dCourse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// if (parent.getItemAtPosition(position).equals("Select course")){
// Toast.makeText(MainActivityCreateProfile.this, "Select the course", Toast.LENGTH_SHORT).show();
//} else {
selected.setText(parent.getSelectedItem().toString());
//}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivityCreateProfile.this, "Select a course", Toast.LENGTH_SHORT).show();
}
});
dDoneBtn = findViewById(R.id.dDoneBtn);
dDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputValidation();
}
});
dProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivityCreateProfile.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivityCreateProfile.this, "You have already granted permission", Toast.LENGTH_SHORT).show();
SelectImage();
} else {
requestStoragePermission();
}
}
});
}
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivityCreateProfile.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This Permission is needed for uploading the Image")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivityCreateProfile.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
SelectImage();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}
public void SelectImage() {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
selectedImage = result.getUri();
Picasso.get().load(selectedImage).into(dProfileImage);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void inputValidation() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
//Username validation
if (!Utils.inputValidation(dEditUsername)) {
Toast.makeText(this, "Enter the username", Toast.LENGTH_SHORT).show();
return;
} else if (!Utils.usernameVerify(dEditUsername)) {
Toast.makeText(this, "A Username should not exceed 15 characters", Toast.LENGTH_SHORT).show();
return;
} else {
dUsername.setErrorEnabled(false);
}
//Reg no Validation
if (!Utils.inputValidation(dEditRegNo)) {
Toast.makeText(this, "Enter the Register No", Toast.LENGTH_SHORT).show();
return;
} else if (!Utils.regNoVerify(dEditRegNo)) {
Toast.makeText(this, "Enter correct Register No", Toast.LENGTH_SHORT).show();
return;
}
createProfile();
}else {
Toast.makeText(this, "Check internet connection", Toast.LENGTH_SHORT).show();
}
}
public String GetFileExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;
}
private void createProfile(){
final String username = dEditUsername.getText().toString();
final String regNo = dEditRegNo.getText().toString();
final String course = dCourse.getSelectedItem().toString();
maxid = databaseReference.push().getKey();
if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(regNo))) {
if (!course.equals(select)) {
databaseReference.orderByChild("regNo").equalTo(regNo).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityCreateProfile.this, "Reg no. exist", Toast.LENGTH_SHORT).show();
} else {
s = "https://firebasestorage.googleapis.com/v0/b/getnotify-da5c1.appspot.com/o/Permanent%2Fuser.png?alt=media&token=017d9013-ede2-49c7-b53b-6e96d90e3398";
UserDetails userDetails = new UserDetails(s, username, regNo, course, email);
databaseReference.child(maxid).setValue(userDetails);
Toast.makeText(MainActivityCreateProfile.this, "Upload Successful", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityCreateProfile.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Select a course", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Enter username and Register No.", Toast.LENGTH_SHORT).show();
}
}
}
I'm facing a problem where i want to check whether the Register No. already exist in the database or not
and this is code to check that.
databaseReference.orderByChild("regNo").equalTo(regNo).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityCreateProfile.this, "Reg no. exist", Toast.LENGTH_SHORT).show();
} else {
s = "https://firebasestorage.googleapis.com/v0/b/getnotify-da5c1.appspot.com/o/Permanent%2Fuser.png?alt=media&token=017d9013-ede2-49c7-b53b-6e96d90e3398";
UserDetails userDetails = new UserDetails(s, username, regNo, course, email);
databaseReference.child(maxid).setValue(userDetails);
Toast.makeText(MainActivityCreateProfile.this, "Upload Successful", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityCreateProfile.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
The code works correctly. It detects if the value exist in database and shows Toast message Reg No. exist. If the value does not exist it successfully creates the child in database but it also displays Toast message Reg No. exist instead of Upload successful. I'm new to these concept so if you know anything please help.
Database node
As per Hussain Answer. addValueEventListener() is called each time there is changes in Your Database to overcome this situation you can call addListenerForSingleValueEvent(). Which will called once.
Other than that there is no Get option in Realtime Database
databaseReference.orderByChild("regNo").equalTo(regNo)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//Do what you want to try
}else{
//Create New Node in Database
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is what might be going wrong with the code. You are trying to check if the regno exist with addValueEventListener on user databaseReference.
From Android Documentation addValueEventListener does this
Add a listener for changes in the data at this location. Each time time the data changes, your listener will be called with an immutable snapshot of the data.
Therefore, when the dataSnapshot does not exists it creates a new node and eventually addValueEventListener fires again and your toast prints Reg no. exist.
What you can do is
databaseReference
.child(regNo)
.addListenerForSingleValueEvent(new ValueEventListenerAdapter() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// Document exists
} else {
// Do something
}
}
});
Related
I'm a new android developer and trying to make image to text app. I watched some tutorials and pretty sure that i don't make any mistakes. I'm using ML Kit for this project and got error when i tried to convert the image to text.
My main activity
package com.gorkemtand.textrecognition;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.Toast;
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.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.google.mlkit.vision.text.latin.TextRecognizerOptions;
import java.io.IOException;
import java.security.Permission;
public class MainActivity extends AppCompatActivity {
private MaterialButton inputImageBtn;
private MaterialButton recognizeTextBtn;
private ShapeableImageView imageIv;
private EditText recognizedTextEt;
private static final String TAG = "MAIN_TAG";
private Uri imageUri = null;
//to handle the result of Camere/Gallery permissions
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 101;
//arrays of permission required to pick image from Camera,gallery
private String[] cameraPermissions;
private String[] storagePermissions;
private ProgressDialog progressDialog;
private TextRecognizer textRecognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputImageBtn = findViewById(R.id.inputImageBtn);
recognizeTextBtn = findViewById(R.id.recognizeBtn);
imageIv = findViewById(R.id.imageIv);
recognizedTextEt = findViewById(R.id.recognizedTextEd);
cameraPermissions = new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please Wait");
progressDialog.setCanceledOnTouchOutside(false);
textRecognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);
inputImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showInputImageDialog();
}
});
recognizeTextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(imageUri == null){
Toast.makeText(MainActivity.this,"Pick image first...",Toast.LENGTH_SHORT).show();
}
else {
recognizeTextFromImage();
}
}
});
}
private void recognizeTextFromImage() {
Log.d(TAG, "recognizeTextFromImage: ");
progressDialog.setMessage("Preparing image...");
progressDialog.show();
try {
InputImage inputImage = InputImage.fromFilePath(this,imageUri);
progressDialog.setMessage("Recognizing text...");
Task<Text> textTaskResult = textRecognizer.process(inputImage).addOnSuccessListener(new OnSuccessListener<Text>() {
#Override
public void onSuccess(Text text) {
progressDialog.dismiss();
String recognizedText = text.getText();
Log.d(TAG, "onSuccess: recognizedText: "+recognizedText);
recognizedTextEt.setText(recognizedText);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Log.e(TAG, "onFailure: ",e);
Toast.makeText(MainActivity.this,"Failed recognizing text due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
progressDialog.dismiss();
Log.e(TAG, "recognizeTextFromImage: ",e);
Toast.makeText(MainActivity.this,"Failed preparing image due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
private void showInputImageDialog() {
PopupMenu popupMenu = new PopupMenu(this, inputImageBtn);
popupMenu.getMenu().add(Menu.NONE,1,1,"CAMERA");
popupMenu.getMenu().add(Menu.NONE,2,2,"GALLERY");
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if(id == 1){
Log.d(TAG, "onMenuItemClick: Camera Clicked...");
if(checkCameraPermissions()){
pickImageCamera();
}
else{
requestCameraPermissions();
}
}
else if(id == 2){
Log.d(TAG, "onMenuItemClick: Gallery Clicked...");
if(checkStoragePermision()){
pickImageGallery();
}
else{
requestStoragePermission();
}
}
return false;
}
});
}
private void pickImageGallery(){
Log.d(TAG, "pickImageGallery: ");
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
galleryActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> galleryActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
//image picked
Intent data = result.getData();
imageUri = data.getData();
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
//set to imageview
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled...",Toast.LENGTH_SHORT).show();
}
}
}
);
private void pickImageCamera(){
Log.d(TAG, "pickImageCamera: ");
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Sample Title");
values.put(MediaStore.Images.Media.DESCRIPTION, "Sample Description");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
cameraActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> cameraActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
);
private boolean checkStoragePermision(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission(){
ActivityCompat.requestPermissions(this,storagePermissions,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermissions(){
boolean cameraResult = ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean storafeResult = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return cameraResult && storafeResult;
}
private void requestCameraPermissions(){
ActivityCompat.requestPermissions(this,cameraPermissions, CAMERA_REQUEST_CODE);
}
//handle permission results
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && storageAccepted){
pickImageCamera();
}
else {
Toast.makeText(this, "Camera && Storage permissions are required", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(this,"Cancelled",Toast.LENGTH_SHORT).show();
}
}
break;
case STORAGE_REQUEST_CODE:{
if(grantResults.length>0){
boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (storageAccepted) {
pickImageGallery();
}
else {
Toast.makeText(this, "Storage permission is required", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
}
Also i implemented these two
implementation 'com.google.android.gms:play-services-mlkit-text-recognition:18.0.2'
implementation 'com.google.android.gms:play-services-mlkit-text-recognition-common:18.0.0'
And give the permissions to manifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the error i got:
Error
I searched the google and cnat find a solution. If u can help me i will be very happy.
I searched google and can't find anything works.
I solved by implementing com.google.mlkit:text-recognition:16.0.0-beta6
Are you testing on device without play store services? For example on an emulator? In order to use com.google.android.gms:play-services-mlkit-text-recognition:18.0.2 it has to be on a device with play store services.
I am making a project for which the login should be done only when the user data is already in the Firebase Realtime Database, no new users are to be registered, I only have to work with pre-existing users. My current code generates and verifies OTP regardless of whether the user mobile number is already present or not. So how do I modify to serve my purpose?
Here is my code:
package com.lalbhaibrokers.lalbhaibrokerspvtltd;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskExecutors;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.concurrent.TimeUnit;
public class LoginActivity extends AppCompatActivity {
//Variables
TextInputEditText mobileNumber, otp;
TextView forgotPassword, errorMessage, sendOtp, verifyOtpAndLogin;
Context context = this;
String verificationCode;
boolean isVerified;
FirebaseDatabase database;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Hooks
mobileNumber = (TextInputEditText) findViewById(R.id.mobile_no_editText);
otp = (TextInputEditText) findViewById(R.id.otp_editText);
errorMessage = (TextView) findViewById(R.id.error_message_textView);
sendOtp = (TextView) findViewById(R.id.send_otp_btn);
verifyOtpAndLogin = (TextView) findViewById(R.id.verify_otp_and_login);
verifyOtpAndLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String userCode = otp.getText().toString();
if (!userCode.isEmpty()) {
verifyCode(userCode); //verifying the code Entered by user
}
}
});
}
//method for start the OTP process
public void sendOtp(View view){
if(mobileNumber.getText().toString().equals("")){
errorMessage.setText("Please Enter phone number");
errorMessage.setVisibility(View.VISIBLE);
}else if(mobileNumber.getText().toString().length() != 10){
errorMessage.setText("PhoneNumber is Invalid"); //we can only accept phoneNumbers with 10 digits
errorMessage.setVisibility(View.VISIBLE);
}else{
String phoneNum= "+91"+mobileNumber.getText().toString(); //we have to add country code in order to receive OTP
//method that will send the OTP to given number
PhoneAuthProvider.getInstance().verifyPhoneNumber( //sending message
phoneNum, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
TaskExecutors.MAIN_THREAD, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
Toast.makeText(context, "OTP send to"+phoneNum, Toast.LENGTH_SHORT).show();
verifyOtpAndLogin.setVisibility(View.VISIBLE);
}
}
//method that verify the OTP received or not
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCode = s; //verification code that should be received by phoneNumber
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode(); //verification code that actually received by phoneNumber
if (code != null) {
verifyCode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(context, "Verification Failed: OTP not received", Toast.LENGTH_SHORT).show();
}
};
//verifying the OTP
public void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCode, code); //comparing both verification code
signin(credential);
}
//signing in the User to update in database
private void signin(PhoneAuthCredential credential) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(context, "Verification Complete", Toast.LENGTH_SHORT).show();
isVerified=true;
Intent intent = new Intent(context, UserDashboard.class);
startActivity(intent);
finish();
} else {
Toast.makeText(context, "Verification Faild: OTP wrong", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Set up a method that verifies if the UID of the verified user already exists on your database
if (task.isSuccessful()) {
//verify UID here
Toast.makeText(context, "Verification Complete", Toast.LENGTH_SHORT).show();
isVerified=true;
Intent intent = new Intent(context, UserDashboard.class);
startActivity(intent);
finish();
} else {
Toast.makeText(context, "Verification Faild: OTP wrong", Toast.LENGTH_SHORT).show();
}
}
});
This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
How to get URL from Firebase Storage getDownloadURL
(13 answers)
Closed 2 years ago.
I make a chatting app with android studio. I want to create settings activity. I successfully load profile image to firebase storage. But when I retrieve profile image from storage it seems end of the onactivityresult. But when I go back to main activity the profile image is disappearing I want when I enter to settings activity profile image is retrieves. I try to do with picasso & glide but not working.
enter code here
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
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.ValueEventListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Toolbar mToolbar;
private CircleImageView set_profile_image;
private EditText set_user_name , set_profile_status;
private Button update_settings_button;
private String CurrentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
define();
RetrieveUserInfo();
}
private void define() {
set_profile_image = (CircleImageView) findViewById(R.id.set_profile_image);
set_user_name = (EditText) findViewById(R.id.set_user_name);
set_profile_status = (EditText) findViewById(R.id.set_profile_status);
update_settings_button = (Button) findViewById(R.id.update_settings_button);
mAuth = FirebaseAuth.getInstance();
CurrentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
loadingBar = new ProgressDialog(this);
}
public void set_profile_image_click(View view){
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent , GalleryPick);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null){
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1 , 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK){
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Your Profile Image is Updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
final Uri resultUri = result.getUri();
StorageReference FilePath = UserProfileImagesRef.child(CurrentUserID + ".jpg");
FilePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull final Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Profile Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getUploadSessionUri().toString();
RootRef.child("Users").child(CurrentUserID).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Image Uploaded Database Successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message , Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
Glide.with(SettingsActivity.this).load(new File(resultUri.getPath())).into(set_profile_image);
}
}
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(CurrentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image")))){
String RetrieveUserName = dataSnapshot.child("name").getValue().toString();
String RetrieveProfileStatus = dataSnapshot.child("status").getValue().toString();
String RetrieveProfileImage = dataSnapshot.child("image").getValue().toString();
set_user_name.setText(RetrieveUserName);
set_profile_status.setText(RetrieveProfileStatus);
//Picasso.get().load(RetrieveProfileImage).into(set_profile_image);
Glide.with(SettingsActivity.this).load(new File(RetrieveProfileImage.)).into(set_profile_image);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
String RetrieveUserName = dataSnapshot.child("name").getValue().toString();
String RetrieveProfileStatus = dataSnapshot.child("status").getValue().toString();
set_user_name.setText(RetrieveUserName);
set_profile_status.setText(RetrieveProfileStatus);
}
else{
//set_user_name.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Please update your profile Settings", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void update_settings_button_click(View view){
UpdateSettings();
}
private void UpdateSettings() {
String setUserName = set_user_name.getText().toString();
String setProfileStatus = set_profile_status.getText().toString();
if (TextUtils.isEmpty(setUserName)){
Toast.makeText(this, "Please write your User Name", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setProfileStatus)){
Toast.makeText(this, "Please write your Status", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String , String> ProfileMap = new HashMap<>();
ProfileMap.put("uid" , CurrentUserID);
ProfileMap.put("name" , setUserName);
ProfileMap.put("status" , setProfileStatus);
RootRef.child("Users").child(CurrentUserID).setValue(ProfileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
}else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message , Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SettingsActivity.this , MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
I have two activities SetupActivity , DashboardActivity. I'm Using Firebase Authentication and checking user existence. The flow of application for a new user is
open App->MainActivity->RegisterFragment->SetupActivity->DashboardActivity. This is my SetupActivity.Java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.kloadingspin.KLoadingSpin;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.FirebaseAuth;
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.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 com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import br.com.simplepass.loadingbutton.customViews.CircularProgressButton;
import de.hdodenhof.circleimageview.CircleImageView;
public class SetupActivity extends AppCompatActivity implements LocationListener, View.OnClickListener {
private static final int REQUEST_LOCATION = 1 ;
private TextInputLayout TIPFullname, TIPCurrentLocation, TIPMobile, TIPBloodGroup, TIPLastDonated;
private TextInputEditText FullName, CurrentLocation, Mobile, BloodGroup, LastDonated;
private AutoCompleteTextView PermanentLocation;
private CircularProgressButton SaveInformationButton;
private CircleImageView ProfileImage;
private SimpleDateFormat dateFormatter;
private LocationManager locationManager;
private LocationListener locationListener;
private DatePickerDialog datePickerDialog;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
private StorageReference UserProfileImageRef;
private ValidationHelper validation;
KLoadingSpin a;
String currentUserID;
final static int Gallery_Pick = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
String[] cities = getResources().getStringArray(R.array.cities);
// Toast.makeText(this, "First select profile image and then enter details", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
a = findViewById(R.id.KLoadingSpin);
TIPFullname = findViewById(R.id.tip_fullname);
TIPCurrentLocation = findViewById(R.id.tip_curr_location);
TIPBloodGroup = findViewById(R.id.tip_blood_group);
TIPLastDonated = findViewById(R.id.tip_last_donated);
TIPMobile = findViewById(R.id.tip_mobile);
FullName = findViewById(R.id.reg_fullname);
CurrentLocation = findViewById(R.id.reg_curr_location);
Mobile = findViewById(R.id.reg_mobile);
BloodGroup = findViewById(R.id.reg_blood_group);
PermanentLocation = findViewById(R.id.reg_per_location);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.dropdown_menu_popup_item,cities);
PermanentLocation.setAdapter(adapter);
PermanentLocation.setThreshold(2);
LastDonated = findViewById(R.id.reg_last_donated);
LastDonated.setInputType(InputType.TYPE_NULL);
SaveInformationButton = findViewById(R.id.btn_save);
ProfileImage = findViewById(R.id.setup_profile_image);
validation = new ValidationHelper(this);
TIPCurrentLocation.setEndIconOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
getLocation();
}
});
SetDateTimeField();
SaveInformationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkValidation();
SaveAccountSetupInformation();
}
});
ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("profileimage")) {
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(SetupActivity.this).load(image).placeholder(R.drawable.default_profile).into(ProfileImage);
} else {
Toast.makeText(SetupActivity.this, "Please select profile image first.", Toast.LENGTH_LONG).show();
tipDisabled();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SetDateTimeField() {
LastDonated.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
LastDonated.setText(dateFormatter.format(newDate.getTime().toString()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public void onClick(View view) {
if(view == LastDonated) {
datePickerDialog.show();
}
}
private void checkValidation() {
if (!validation.isEditTextFilled(BloodGroup, TIPBloodGroup, "Enter Blood Group")) {
return;
}
if (!validation.isEditTextBloodGroup(BloodGroup, TIPBloodGroup, "Enter Correct BloodGroup!!")) {
return;
}
}
private void getLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION},
75
);
}
isLocationEnabled();
Location loc=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
String longitude = "Longitude: " +loc.getLongitude();
String latitude = "Latitude: " +loc.getLatitude();
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = " "+cityName;
CurrentLocation.setText(s);
}
private boolean isLocationEnabled(){
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
a.setVisibility(View.VISIBLE);
a.startAnimation();
a.setIsVisible(true);
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Toast.makeText(SetupActivity.this, "Please Wait", Toast.LENGTH_SHORT).show();
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UsersRef.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SetupActivity.this, "Please Wait", Toast.LENGTH_LONG).show();
Intent selfIntent = new Intent(SetupActivity.this, SetupActivity.class);
startActivity(selfIntent);
tipEnabled();
Toast.makeText(SetupActivity.this, "Your Profile image looks great!!!...", Toast.LENGTH_SHORT).show();
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
} else {
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
tipDisabled();
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
}
}
});
}
});
}
}
});
} else {
Toast.makeText(SetupActivity.this, "Error: Image not selected or not cropped", Toast.LENGTH_SHORT).show();
tipDisabled();
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
}
}
}
private void SaveAccountSetupInformation() {
String fullname = FullName.getText().toString();
String currentlocation = CurrentLocation.getText().toString();
String mobile = Mobile.getText().toString();
String permanentlocation = PermanentLocation.getText().toString();
String bloodgroup = BloodGroup.getText().toString();
String lastdonated = LastDonated.getText().toString();
if (TextUtils.isEmpty(currentlocation)) {
Toast.makeText(this, "Please click button and get your current city...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(mobile)) {
Toast.makeText(this, "Please write your mobile no...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(permanentlocation)) {
Toast.makeText(this, "Please enter your permanent city...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(fullname)) {
Toast.makeText(this, "Please enter your full name...", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(bloodgroup)) {
Toast.makeText(this, "Please enter your bloodgroup...", Toast.LENGTH_SHORT).show();
}
else {
a.setVisibility(View.VISIBLE);
a.startAnimation();
a.setIsVisible(true);
SaveInformationButton.startAnimation();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
HashMap userMap = new HashMap();
userMap.put("bloodgroup", bloodgroup);
userMap.put("fullname", fullname);
userMap.put("mobile", mobile);
userMap.put("currentlocation", currentlocation);
userMap.put("permanentlocation", permanentlocation);
userMap.put("timesdonated","0");
userMap.put("lastdonatedon",lastdonated);
UsersRef.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(SetupActivity.this, "your Account is created Successfully.", Toast.LENGTH_LONG).show();
} else {
a.stopAnimation();
a.setVisibility(View.GONE);
a.setIsVisible(false);
SaveInformationButton.revertAnimation();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Error Occured: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void tipDisabled()
{
TIPCurrentLocation.setEnabled(false);
TIPMobile.setEnabled(false);
TIPBloodGroup.setEnabled(false);
TIPFullname.setEnabled(false);
TIPLastDonated.setEnabled(false);
PermanentLocation.setEnabled(false);
}
private void tipEnabled()
{
TIPCurrentLocation.setEnabled(true);
TIPMobile.setEnabled(true);
TIPBloodGroup.setEnabled(true);
TIPFullname.setEnabled(true);
TIPLastDonated.setEnabled(true);
PermanentLocation.setEnabled(true);
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SetupActivity.this, DashboardActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
public void onLocationChanged(Location loc) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this,"Enable Location and Internet to get Location",Toast.LENGTH_LONG);
}
}
` Here i want the user to select the profile picture first and then have to fill text in edittexts. So,i need to disable all the edittexts and after the profile image is set i have to enable them. for this purpose i have written tipdisabled() and tipEnabled() methods. But i donno where to use them correctly. Please Clarify this.
You can merge your code like this:
private void tipEnabled(Boolean isEnabled)
{
TIPCurrentLocation.setEnabled(isEnabled);
TIPMobile.setEnabled(isEnabled);
TIPBloodGroup.setEnabled(isEnabled);
TIPFullname.setEnabled(isEnabled);
TIPLastDonated.setEnabled(isEnabled);
PermanentLocation.setEnabled(isEnabled);
}
To achieve your flow, put tipEnabled(false) inside your choose image click Listener and tipEnabled(true) in the onResult, which i think in your case is onActivityResult().
You should seggerate you code as right now your activity looks like a data dump which is handling too many responsibilities at the moment. Try creating Presenter classes, Controller classes or ViewModel classes to delegate all this functioning to them. You Activity should only act as a container and should not be doing validations or any logical processing but rather doing delegation.
In the register page, when a user clicks on the "ImageUserPhoto", he can pick an image from the gallery. My code works fine when he picks the photo and fills up all given fields. But if he doesn't pick any photo, the app crashes. How can I give a warning if he doesn't choose any photo in the same section where I check all the fields?
Thanks in advance!!
package com.ayon.austmart.activities;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
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.ProgressBar;
import android.widget.Toast;
import com.ayon.austmart.R;
import com.google.android.gms.tasks.OnCompleteListener;
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.auth.UserProfileChangeRequest;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import de.hdodenhof.circleimageview.CircleImageView;
public class RegisterActivity extends AppCompatActivity {
CircleImageView ImgUserPhoto;
static int PReqCode = 1;
static int REQUESCODE = 1;
Uri pickedImgUri;
private EditText userEmail, userPassword, userPassword2, userName;
private ProgressBar loadingProgress;
private Button regBtn;
private Intent homeIntent;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
userEmail = findViewById(R.id.Email);
userPassword = findViewById(R.id.Password);
userPassword2 = findViewById(R.id.ConfirmPassword);
userName = findViewById(R.id.Name);
loadingProgress = findViewById(R.id.progressBarRegister);
regBtn = findViewById(R.id.buttonRegister);
loadingProgress.setVisibility(View.INVISIBLE);
mAuth = FirebaseAuth.getInstance();
ImgUserPhoto = findViewById(R.id.avatar);
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
regBtn.setVisibility(View.INVISIBLE);
loadingProgress.setVisibility(View.VISIBLE);
final String email = userEmail.getText().toString();
final String password = userPassword.getText().toString();
final String password2 = userPassword2.getText().toString();
final String name =userName.getText().toString();
if(email.isEmpty() || name.isEmpty() || password.isEmpty() || password2.isEmpty() || !password.equals(password2))
{
//something goes wrong... display an error message
showMessage("Please verify full fields!!");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else
{
//Everything is ok..
createUserAccount(email,name,password);
}
}
});
ImgUserPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= 22)
{
checkAndRequestForPermission();
}
else
{
openGallery();
}
}
});
}
private void createUserAccount(String email, final String name, String password) {
//this method create user account with valid email and pass
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
//user account is created successfully
showMessage("Account Created!");
//now update the pro pic and username
updateUserInfo(name,pickedImgUri,mAuth.getCurrentUser());
}
else
{
showMessage("Account creation failed"+task.getException().getMessage());
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
}
});
}
private void updateUserInfo(final String name, Uri pickedImgUri, final FirebaseUser currentUser){
StorageReference mStorage = FirebaseStorage.getInstance().getReference().child("user_photos");
final StorageReference imageFilePath = mStorage.child(pickedImgUri.getLastPathSegment());
imageFilePath.putFile(pickedImgUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image uploaded successfully
//getting image url
imageFilePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// uri contains user image url
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(uri)
.build();
currentUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
//user info updated successfully
showMessage("Register Complete!");
updateUI();
}
}
});
}
});
}
});
}
private void updateUI() {
homeIntent = new Intent(getApplicationContext(), Home.class);
startActivity(homeIntent);
finish();
}
//message show
private void showMessage(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
private void openGallery() {
//Open gallery intent and wait for user to pick an image
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,REQUESCODE);
}
public void checkAndRequestForPermission()
{
if(ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(RegisterActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE))
{
Toast.makeText(RegisterActivity.this,"Please accept for required permission",Toast.LENGTH_SHORT ).show();
}
else
{
ActivityCompat.requestPermissions(RegisterActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PReqCode);
}
}
else
openGallery();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == REQUESCODE && data !=null)
{
//user has successfully picked an image...
//saving its reference to a Uri variable
pickedImgUri = data.getData();
ImgUserPhoto.setImageURI(pickedImgUri);
}
}
}
your pickedImgUri is null if the user does not select the image from gallery.
So when you call createUserAccount() when register button is clicked and user has not selected the image pickedImgUri is not updated as per your code.
Hence updateUserInfo() will fail calling an exception which causes the crash.
please add a null checker like
if(pickedImgUri!=null){
//then update the user account
}
If you are interested in forcing the user to select the profile photo then simply use above checker and alert user to please select a photo first but i'd advice against that. Not everyone likes to upload a photo. use any generic avatar png file instead when user does not want to update/remove the avatar.
Happy coding
Thanks a lot!! I have added a few lines and it worked!!! Thank you very much!!
if(email.isEmpty() || name.isEmpty() || password.isEmpty() || password2.isEmpty() || !password.equals(password2))
{
//something goes wrong... display an error message
showMessage("Please verify full fields!!");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else
{
if(pickedImgUri == null)
{
showMessage("Please select an image");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else {
createUserAccount(email, name, password);
//Everything is ok..
}
}
}
});