Breaking my neck with ProgressDialog and dismiss method issues - java

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

Related

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

Task is not yet completed while using firebase

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

Firebase User == null all the time

My app uses firebase and it needs to send a verification email to the user after registration before they can login. In my code, the app fails to send the verification email and I found out that the user is always null (while debugging) in line 86/88 of my code. any help would be greaty appreciated.
I've tried retracing my steps back but I couldn't get where i nicked an artery
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
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.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import static android.text.TextUtils.isEmpty;
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuthSetUp();
//widgets
TextView mSignUp = (TextView) findViewById(R.id.sign_up_txt);
TextView forgotPassword = (TextView) findViewById(R.id.forgot_password_txt);
Button mSignIn = (Button) findViewById(R.id.sign_in_btn);
final EditText mEmailSignIn = (EditText) findViewById(R.id.sign_in_email);
final EditText mPasswordSignIn = (EditText) findViewById(R.id.sign_in_password);
mSignUp.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
}));
//sign in process
mSignIn.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isEmpty(mEmailSignIn.getText().toString()) && !isEmpty(mPasswordSignIn.getText().toString())) {
//showProgressBar();
FirebaseAuth.getInstance().signInWithEmailAndPassword(mEmailSignIn.getText().toString(), mPasswordSignIn.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//hideProgressBar();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, " Authentication Failed!!!", Toast.LENGTH_LONG).show();
//hideProgressBar();
}
});
} else {
Toast.makeText(LoginActivity.this, "Please, Fill All Fields", Toast.LENGTH_LONG).show();
}
}
}));
}
//Setting up Firebase
private void firebaseAuthSetUp() {
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
Log.d("TAG", "CurrentUser: " + user);
if (user != null) {
if(user.isEmailVerified()){
Log.d("TAG", "onAuthStateChanged: signed in: " + user.getEmail());
Toast.makeText(LoginActivity.this, "signed in " + user.getUid(), Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginActivity.this, "Please Check Your Email Inbox for Verification Link " + user.getUid(), Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
}
} else {
Toast.makeText(LoginActivity.this, "failed to sign in", Toast.LENGTH_LONG).show();
}
}
};
}
#Override
protected void onStart() {
super.onStart();
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if (mAuthListener != null) {
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
}
}
/*public void showProgressBar(){
mProgressBar.setVisibility(View.VISIBLE);
}
public void hideProgressBar(){
if (mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.INVISIBLE);
}
}*/
}```
Thanks a lot #Praveen and #Alex... figured it out, I made a mistake of signing out the user in the else statement [of the if(user.isEmailVerified()) block in the firebaseAuthSetup() method]. probably wouldn't have gotten it if I didn't retrace from the onComplete()

Facebook Login loaduserprofile

When I log in through facebook, I am supposed to get some data from Facebook such as my email, name and profile picture. However, now I can't get the data anymore after I added these codes
#Override
public void onSuccess(LoginResult loginResult) {
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Toast.makeText(getApplicationContext(), "Login Success with Facebook", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
I am supposed to get these Facebook datas in this activity
package com.example.musix.Musix;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.musix.MainActivity;
import com.example.musix.R;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.google.firebase.auth.FirebaseAuth;
import org.json.JSONException;
import org.json.JSONObject;
public class ViewProfile extends AppCompatActivity {
private ImageView circleImageView;
private TextView txtName,txtEmail;
private ImageButton Home;
private ImageButton Playlist;
private FirebaseAuth firebaseAuth;
private Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_profile);
circleImageView = (ImageView) findViewById(R.id.profile_icon);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
Home = (ImageButton)findViewById(R.id.home);
Playlist = (ImageButton)findViewById(R.id.playlisticon);
firebaseAuth = FirebaseAuth.getInstance();
logout = (Button)findViewById(R.id.btnLogout);
//go to LoginScreen page
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
startActivity(new Intent(ViewProfile.this, LoginScreen.class));
}
});
//go to Playlist page
Playlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ViewProfile.this, Playlist.class));
}
});
//go to MainActivity page
Home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ViewProfile.this, MainActivity.class));
}
});
checkLoginStatus();
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null){
txtName.setText("");
txtEmail.setText("");
circleImageView.setImageResource(0);
}
else{
loaduserProfile(currentAccessToken);
}
}
};
//get Facebook profile data
private void loaduserProfile(AccessToken newAccessToken){
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+id+ "/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(ViewProfile.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name, last_name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
//display Facebook profile data if already logged in
private void checkLoginStatus(){
if(AccessToken.getCurrentAccessToken()!= null){
loaduserProfile(AccessToken.getCurrentAccessToken());
}
}
}
My facebook login page
package com.example.musix.Musix;
import android.app.ProgressDialog;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.musix.MainActivity;
import com.example.musix.R;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphRequestAsyncTask;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
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 org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
public class LoginScreen extends AppCompatActivity {
private EditText Username;
private EditText Password;
private Button Login;
private LoginButton FacebookLogin;
private ImageView circleImageView;
private TextView txtName,txtEmail;
private TextView userRegistration;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private TextView forgotPassword;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
Username = (EditText) findViewById(R.id.etName);
Password = (EditText) findViewById(R.id.etPassword);
Login = (Button) findViewById(R.id.btnLogin);
FacebookLogin = (LoginButton) findViewById(R.id.facebookLogin);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
circleImageView = (ImageView) findViewById(R.id.profile_icon);
userRegistration = (TextView)findViewById(R.id.tvRegister);
forgotPassword = (TextView)findViewById(R.id.tvForgotPassword);
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
finish();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((Username.length() > 0) && (Password.length() > 0)) ||(AccessToken.getCurrentAccessToken()!= null)){
validate(Username.getText().toString(), Password.getText().toString());
}
else if((Username.length() == 0) && (Password.length() > 0)){
Username.setError("Enter Username");
}
else if((Password.length() == 0) && (Username.length() > 0)){
Password.setError("Enter Password");
}
else{
Username.setError("Enter Username");
Password.setError("Enter Password");
}
}
});
userRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginScreen.this, SignUp.class));
}
});
callbackManager = CallbackManager.Factory.create();
FacebookLogin.setReadPermissions(Arrays.asList("email", "public_profile"));
checkLoginStatus();
FacebookLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Toast.makeText(getApplicationContext(), "Login Success with Facebook", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_SHORT).show();
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginScreen.this, ForgotPassword.class));
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null){
txtName.setText("");
txtEmail.setText("");
circleImageView.setImageResource(0);
}
else{
loaduserProfile(currentAccessToken);
}
}
};
//get Facebook profile data
private void loaduserProfile(AccessToken newAccessToken){
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+id+ "/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(LoginScreen.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name, last_name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
//display Facebook profile data if already logged in
private void checkLoginStatus(){
if(AccessToken.getCurrentAccessToken()!= null){
loaduserProfile(AccessToken.getCurrentAccessToken());
}
}
private void validate(String userUsername, String userPassword){
//show login progress
progressDialog.setMessage("Loading . . .");
progressDialog.show();
//Login admin account
if((userUsername.equals("Admin")) && (userPassword.equals("12345"))){
Intent intent = new Intent(LoginScreen.this, MainActivity.class);
startActivity(intent);
finish();
}
//Login using firebase-registered accounts
else{
firebaseAuth.signInWithEmailAndPassword(userUsername,userPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isComplete()){
progressDialog.dismiss();
Toast.makeText(LoginScreen.this, "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
else{
progressDialog.dismiss();
Toast.makeText(LoginScreen.this, "The username or password you entered is incorrect.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Here you are logging yourself out the moment you are succesfully logged in. Remove
LoginManager.getInstance().logOut();

Categories

Resources