Task is not yet completed while using firebase - java

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

I think the way you try to upload the song in the database (in Realtime Database I suppose) is wrong. In the method uploadDetailsToDatabase, write:
Declare the reference, in the begining of the class:
DatabaseReference songsDatabase;
Initialize the reference, in onCreate() method, with the path of the song table inside the database:
songsDatabase = FirebaseDatabase.getInstance().getReference("songs");
Add the song object in the realtime database:
Songs songObj = new Songs(songName, songUrl);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
songsDatabase.child(songName).setValue(songObj).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(MainActivity.this,"Song Uploaded",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
In that way, you create a data(table) in the Realtime Databse, with the name of the song, as the name of this table (songName). Inside this table, you have 2 fields: The song name, and the url of the song.
You may find usefull this answer:
how to resolve java.lang.IllegalStateException: Task is not yet complete Error when uploading image to Firebase storage?

You should avoid using while loop inside a callback listener, instead you can check on the other listener method onComplete() if the upload has been successful or not.

Related

My app is gets back to previous page without updating data to database. (Using Android studio + Firebase)

My app is gets back to previous page without updating data to database. (Using Android studio + Firebase)
This is the java code for the activity
package com.example.hospital_management_system;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
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.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.HashMap;
import java.util.UUID;
import de.hdodenhof.circleimageview.CircleImageView;
public class DoctorRegistrationActivity extends AppCompatActivity {
private TextView backToLogin;
private TextInputEditText dregistrationFullName, dregistrationIdNumber,
dregistrationPhoneNumber, doctorRegMailId, doctorRegPassword;
private CircleImageView dprofileImage;
private Spinner availabilitySpinner,departmentSpinner,specializationSpinner;
private Button regButton;
public Uri resultUri;
private FirebaseAuth mAuth;
private FirebaseStorage Storage;
private StorageReference storageReference;
private DatabaseReference userDatabaseRef;
private ProgressDialog loader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_registration);
backToLogin = findViewById(R.id.backToLogin);
backToLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(DoctorRegistrationActivity.this,
LoginActivity.class);
startActivity(intent);
}
});
dregistrationFullName = findViewById(R.id.dregistrationFullName);
dregistrationPhoneNumber = findViewById(R.id.dregistrationPhoneNumber);
dregistrationIdNumber = findViewById(R.id.dregistrationIdNumber);
doctorRegMailId = findViewById(R.id.doctorRegMailId);
doctorRegPassword = findViewById(R.id.doctorRegPassword);
regButton = findViewById(R.id.regButton);
dprofileImage = findViewById(R.id.dprofileImage);
departmentSpinner = (Spinner)findViewById(R.id.departmentSpinner);
specializationSpinner =(Spinner)findViewById(R.id.specializationSpinner);
availabilitySpinner =(Spinner)findViewById(R.id.availabilitySpinner);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
dprofileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
choosePicture();
}
});
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("yoyoyoyoyoyoyo", "reg just clicked ");
final String email = doctorRegMailId.getText().toString().trim();
final String password = doctorRegPassword.getText().toString().trim();
final String fullName = dregistrationFullName.getText().toString().trim();
final String idNumber = dregistrationIdNumber.getText().toString().trim();
final String phoneNumber =
dregistrationPhoneNumber.getText().toString().trim();
Log.d("yoyoyoyoyoyoyo", "reached to spinner ");
final String department =
departmentSpinner.getSelectedItem().toString().trim();
final String specialization =
specializationSpinner.getSelectedItem().toString().trim();
final String availability =
availabilitySpinner.getSelectedItem().toString().trim();
if (TextUtils.isEmpty(email)) {
doctorRegMailId.setError("Email is Required!");
return;
}
if (TextUtils.isEmpty(password)) {
doctorRegPassword.setError("Password is Required!");
return;
}
if (TextUtils.isEmpty(fullName)) {
dregistrationFullName.setError("Name is Required!");
return;
}
if (TextUtils.isEmpty(idNumber)) {
dregistrationIdNumber.setError("IdNumber is Required!");
return;
}
if (TextUtils.isEmpty(phoneNumber)) {
dregistrationPhoneNumber.setError("PhoneNumber is Required!");
return;
}
if(resultUri==null){
Toast.makeText(DoctorRegistrationActivity.this, "profile is required",
Toast.LENGTH_SHORT).show();
}
else{
Log.d("yoyoyoyoyoyoyo", "else ");
loader.setMessage("Registration in progress...");
loader.setCanceledOnTouchOutside(false);
loader.show();
Log.d("yoyoyoyoyoyoyo", "reached to mauth ");
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new
OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Log.d("yoyoyoyoyoyoyo", "task is successful ");
String currentUserId = mAuth.getCurrentUser().getUid();
userDatabaseRef =
FirebaseDatabase.getInstance().getReference().child("users").child(currentUserId);
// userDatabaseRef.setValue("name",fullName);
// userDatabaseRef.setValue("email",email);
// userDatabaseRef.setValue("idnumber",idNumber);
// userDatabaseRef.setValue("phonenumber",phoneNumber);
// userDatabaseRef.setValue("department",department);
//
userDatabaseRef.setValue("specialization",specialization);
// userDatabaseRef.setValue("availability",availability);
HashMap doctorInfo = new HashMap();
Log.d("yoyoyoyoyoyoyo", "after hasmap");
doctorInfo.put("name",fullName);
doctorInfo.put("email",email);
doctorInfo.put("idnumber",idNumber);
doctorInfo.put("phonenumber",phoneNumber);
Log.d("yoyoyoyoyoyoyo", "after phone number ");
doctorInfo.put("department",department);
doctorInfo.put("specialization",specialization);
Log.d("yoyoyoyoyoyoyo", "after specialization ");
doctorInfo.put("availability",availability);
doctorInfo.put("type","doctor");
Log.d("yoyoyoyoyoyoyo", "after doctor ");
userDatabaseRef.updateChildren(doctorInfo).addOnCompleteListener(new
OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
Log.d("yoyoyoyoyoyoyo", "before details set
successfully ");
if(task.isSuccessful()){
Toast.makeText(DoctorRegistrationActivity.this,
"Details set successfully", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(DoctorRegistrationActivity.this,task.getException().toString() ,
Toast.LENGTH_SHORT).show();
}
finish();
loader.dismiss();
}
});
if(resultUri!=null){
uploadImage();
}
Intent intent = new Intent(DoctorRegistrationActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
loader.dismiss();
}
else{
Log.d("yoyoyoyoyoyoyo", "else ");
String error = task.getException().toString();
Toast.makeText(DoctorRegistrationActivity.this, "Error
Occurred: "+error, Toast.LENGTH_SHORT).show();}
}
});
}
}
});
}
private void choosePicture() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startForResult.launch(intent);
}
ActivityResultLauncher<Intent> startForResult = registerForActivityResult(new
ActivityResultContracts.StartActivityForResult(), new
ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result!=null&&result.getResultCode()==RESULT_OK){
if(result.getData()!=null ){
Intent data = result.getData();
resultUri = data.getData();
dprofileImage.setImageURI(resultUri);
}
}
}
});
private void uploadImage(){
final String randomKey = UUID.randomUUID().toString();
// Create a reference to "mountains.jpg"
StorageReference mountainsRef = storageReference.child("image/"+randomKey);
mountainsRef.putFile(resultUri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(DoctorRegistrationActivity.this, "Failed to Upload Image",
Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(DoctorRegistrationActivity.this, "Successfully Uploaded
Image", Toast.LENGTH_SHORT).show();
}
});
}
}
This is the log at that time,
I had already tried to debug but couldn't get any solution.........................................................................................
D/yoyoyoyoyoyoyo: task is successful
D/yoyoyoyoyoyoyo: after hasmap
D/yoyoyoyoyoyoyo: after phone number
D/yoyoyoyoyoyoyo: after specialization
D/yoyoyoyoyoyoyo: after doctor
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hospital_management_system, PID: 12296
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.storage.StorageReference com.google.firebase.storage.StorageReference.child(java.lang.String)' on a null object reference
at com.example.hospital_management_system.DoctorRegistrationActivity.uploadImage(DoctorRegistrationActivity.java:231)
at com.example.hospital_management_system.DoctorRegistrationActivity.access$1200(DoctorRegistrationActivity.java:42)
at com.example.hospital_management_system.DoctorRegistrationActivity$3$1.onComplete(DoctorRegistrationActivity.java:184)
at com.google.android.gms.tasks.zzi.run(com.google.android.gms:play-services-tasks##18.0.1:1)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8061)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
I/Process: Sending signal. PID: 12296 SIG: 9
Disconnected from the target VM, address: 'localhost:54389', transport: 'socket'
You should initialize your storage reference before you call its child, so inside your uploadImage(), add 2 lines at the begining:
final String randomKey = UUID.randomUUID().toString();
// Create a reference to "mountains.jpg"
FirebaseStorage storage = FirebaseStorage.getInstance(); // add this
storageReference = storage.getReference(); // and this
StorageReference mountainsRef = storageReference.child("image/"+randomKey);

main screen opens two times when I login using firebase phone authentication

Login.java
package com.example.simpleaccounting;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
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.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.zxing.pdf417.encoder.PDF417;
import java.util.concurrent.TimeUnit;
public class Login extends AppCompatActivity {
private EditText countryCodeEdit, phoneNumberEdit;
private Button mSendOTPBtn;
ProgressDialog progressDialog;
TextView processText;
private FirebaseAuth auth;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBacks;
private Boolean authFlag = false;
//permission constants
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 101;
//image pick constants
private static final int IMAGE_PICK_CAMERA_CODE = 102;
private static final int IMAGE_PICK_GALLERY_CODE = 103;
//arrays of permissions
private String[] cameraPermissions; //camera and storage
private String[] storagePermissions; // only storage
//variables (will contain data to save)
private Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSendOTPBtn = findViewById(R.id.send_codebtn);
processText = findViewById(R.id.text_process);
countryCodeEdit = findViewById(R.id.input_country_code);
phoneNumberEdit = findViewById(R.id.input_phone);
//init permission arrays
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestCameraPermission();
//set by default text for country code
countryCodeEdit.setText("91");
auth = FirebaseAuth.getInstance();
mSendOTPBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//initialize progress dialog
progressDialog = new ProgressDialog(Login.this);
//show progress dialog
progressDialog.show();
//set Content View
progressDialog.setContentView(R.layout.progress_dialog);
//set transparent background
progressDialog.getWindow().setBackgroundDrawableResource(
android.R.color.transparent
);
String country_code = countryCodeEdit.getText().toString();
String phone = phoneNumberEdit.getText().toString();
String phoneNumber = "+" + country_code + "" + phone;
if (!country_code.isEmpty() || !phone.isEmpty()) {
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(Login.this)
.setCallbacks(mCallBacks)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
} else {
processText.setText("Please Enter Country Code and Phone Number");
processText.setTextColor(Color.RED);
processText.setVisibility(View.VISIBLE);
}
}
});
mCallBacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
signIn(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
processText.setText(e.getMessage());
processText.setTextColor(Color.RED);
processText.setVisibility(View.VISIBLE);
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
processText.setText("OTP has been Sent");
processText.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent otpIntent = new Intent(Login.this, otp.class);
otpIntent.putExtra("auth", s);
startActivity(otpIntent);
}
}, 10000);
}
};
}
private void requestCameraPermission() {
//request the camera permission
ActivityCompat.requestPermissions(this, cameraPermissions, CAMERA_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//result of permssion allowed/denied
switch (requestCode) {
case CAMERA_REQUEST_CODE: {
if (grantResults.length > 0) {
//if allowed returns true otherwise false
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
Toast.makeText(this, cameraAccepted + "", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
#Override
public void onBackPressed() {
//dismiss progress dialog
progressDialog.dismiss();
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
sendToMain();
}
}
private void sendToMain() {
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
finish();
}
private void signIn(PhoneAuthCredential credential) {
auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
sendToMain();
} else {
processText.setText(task.getException().getMessage());
processText.setTextColor(Color.RED);
processText.setVisibility(View.VISIBLE);
}
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.cancel();
}
}
}
This is my login activity.
When i write the otp manually , then i don't have this issue, main activity opens only one time but when it auto reads the otp and directly sends me to main activity from login (skipping otp screen) then main activity opens two times.
OTP.java
package com.example.simpleaccounting;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
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.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
public class otp extends AppCompatActivity {
private Button mVerifyCodeBtn;
private EditText otpEdit;
private String OTP;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp);
mVerifyCodeBtn = findViewById(R.id.verifycode_btn);
otpEdit = findViewById(R.id.verify_code_edit);
firebaseAuth = FirebaseAuth.getInstance();
OTP = getIntent().getStringExtra("auth");
mVerifyCodeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String verification_code = otpEdit.getText().toString();
if(!verification_code.isEmpty()){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(OTP,verification_code);
signIn(credential);
}else{
Toast.makeText(otp.this,"Please Enter OTP",Toast.LENGTH_SHORT).show();
}
}
});
}
private void signIn(PhoneAuthCredential credential){
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
sendToMain();
}else{
Toast.makeText(otp.this,"Verification Failed",Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = firebaseAuth.getCurrentUser();
if(currentUser!=null){
sendToMain();
}
}
private void sendToMain(){
startActivity(new Intent(otp.this, MainActivity.class));
finish();
}
}
And this is my otp screen activity code.
after login my main activity opens but within 5 seconds my main activity opens again. Can anyone help me out with this issue.
Thanks in advance.

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

Breaking my neck with ProgressDialog and dismiss method issues

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

constructor xxx in class xxx cannot be applied to given types;

I'm building an android project with the help of an YouTube video and when I try to build it, it gives the following error message.
error: constructor User in class User cannot be applied to given types;
required: String,String,String,String,Uri
found: String,String
reason: actual and formal argument lists differ in length
I have done the exactly same thing on the video and now I don't understand why it gives me such error.
Here are the lines having errors. The lines between asterisk have underlined with red in the code.
Common.loggedUser = **new User(firebaseUser.getUid(), firebaseUser.getEmail())**;
user_information.child(Common.loggedUser.**getUid**())
.setValue(Common.loggedUser);
Paper.book().write(Common.USER_UID_SAVE_KEY, Common.loggedUser.**getUid**());
tokens.child(firebaseUser.getUid())
.setValue(InstanceIdResult.**getToken**());
Here is my full code
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.IdpResponse;
import com.firebase.ui.auth.data.model.User;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
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.ValueEventListener;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.mynewrealtimelocationtracker.Utils.Common;
import java.util.Arrays;
import java.util.List;
import io.paperdb.Paper;
public class MainActivity extends AppCompatActivity {
DatabaseReference user_information;
private static final int MY_REQUEST_CODE = 4477; //any number you want
List<AuthUI.IdpConfig> providers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Paper.init(this);
//Init firebase
user_information = FirebaseDatabase.getInstance().getReference(Common.USER_INFORMATION);
//Init provider
providers = Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build()
);
//Request permission location
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
showSignInOptions();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(MainActivity.this,"You must accept permissionto use app",Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
}).check();
}
private void showSignInOptions() {
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.build(),MY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == MY_REQUEST_CODE){
IdpResponse response = IdpResponse.fromResultIntent(data);
if (resultCode == RESULT_OK){
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
//Check if user exist on database
user_information.orderByKey()
.equalTo(firebaseUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) //If user is not exist
{
if (!dataSnapshot.child(firebaseUser.getUid()).exists()) //If key uid is not exist
{
Common.loggedUser = new User(firebaseUser.getUid(), firebaseUser.getEmail()); //--> Error
//Add to database
user_information.child(Common.loggedUser.getUid()) //->Error
.setValue(Common.loggedUser);
}
}
else // If user is available
{
Common.loggedUser = dataSnapshot.child(firebaseUser.getUid()).getValue(User.class);
}
// Save UID to storage to update location from background
Paper.book().write(Common.USER_UID_SAVE_KEY, Common.loggedUser.getUid()); //->Error
updateToken(firebaseUser);
setupUI();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
private void setupUI() {
//Navigate Home
startActivity(new Intent(MainActivity.this, HomeActivity.class));
}
private void updateToken(final FirebaseUser firebaseUser) {
final DatabaseReference tokens = FirebaseDatabase.getInstance()
.getReference(Common.TOKENS);
//Get Token
FirebaseInstanceId.getInstance().getInstanceId()
.addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
tokens.child(firebaseUser.getUid())
.setValue(InstanceIdResult.getToken()); //->Error
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Here is my User class
package com.mynewrealtimelocationtracker.Model;
import java.util.HashMap;
public class User {
private String uid, email;
private HashMap<String, User> acceptList; //List user friend
public User() {
}
public User(String uid, String email) {
this.uid = uid;
this.email = email;
acceptList = new HashMap<>();
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public HashMap<String, User> getAcceptList() {
return acceptList;
}
public void setAcceptList(HashMap<String, User> acceptList) {
this.acceptList = acceptList;
}
}
You imported User from com.firebase.ui.auth.data.model, but your class is in com.mynewrealtimelocationtracker.Model. Change the import.
private HashMap acceptList;
Make Constructor With is variable
public User(String uid, String email,HashMap<String,User> acceptList) {
this.uid = uid;
this.email = email;
this.acceptList = acceptList;
}
Then Create Object

Categories

Resources