This is my RegistrationActivity.java where I want user to choose image while registering time. Everything works fine except image updation! When I register a new user and when I click in image, it opens my image gallery, I choose any image, and it back to register activity but it won't update. Also I'm unable to register because that image is not uploading successfully and I sat (if
imagepath == null), so that's why toast error is coming that fill all the details.
NOTE:
1. I tried multiple images, same issue, also I resize some images and tried.
2.There is no error in logcat.
3.Default image is showing perfectly when we first time try to register that time I sat android logo which is default.
4.I can't register without selecting any image because imagepath == null and I exactly want that user should not register if he/she not upload the image.
5.I sat imageview size :
android:layout_width="150dp"
android:layout_height="150dp"
in my activity_registration.xml file. Is there cause any problem?
package com.jimmytrivedi.loginapp;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
public class RegistrationActivity extends AppCompatActivity {
private EditText userName, userEmail, userPassword, userAge;
private Button SignUp;
private TextView userLogin;
private FirebaseAuth firebaseAuth;
private ImageView profile;
private FirebaseStorage firebaseStorage;
private static int PICK_IMAGE = 123;
String name, email, password, age;
Uri imagePath;
private StorageReference storageReference;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE && requestCode == RESULT_OK && data.getData() != null) {
imagePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath);
profile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setUpUIViews();
firebaseAuth = FirebaseAuth.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
SignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
//upload data to the database
String user_email = userEmail.getText().toString().trim();
String user_password = userPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(user_email, user_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
sendEmailVerification();
} else {
Toast.makeText(RegistrationActivity.this, "Registration failed!", Toast.LENGTH_SHORT)
.show();
}
}
});
}
}
});
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}
});
}
private void setUpUIViews() {
userName = findViewById(R.id.userName);
userEmail = findViewById(R.id.userEmail);
userPassword = findViewById(R.id.userPassword);
SignUp = findViewById(R.id.userRegister);
userLogin = findViewById(R.id.userLogin);
userAge = findViewById(R.id.userAge);
profile = findViewById(R.id.profile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE);
}
});
}
private boolean validate() {
Boolean result = false;
name = userName.getText().toString();
email = userEmail.getText().toString();
password = userPassword.getText().toString();
age = userAge.getText().toString();
if (name.isEmpty() || password.isEmpty() || email.isEmpty() || age.isEmpty()
|| imagePath == null) {
Toast.makeText(this, "Please enter all the details", Toast.LENGTH_SHORT)
.show();
} else {
result = true;
}
return result;
}
private void sendEmailVerification() {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
sendUserData();
Toast.makeText(RegistrationActivity.this, "Successfully registered, Verification email has been sent",
Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
finish();
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
} else {
Toast.makeText(RegistrationActivity.this, "Verification email hasn't been sent",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void sendUserData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myReference = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.
child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
UploadTask uploadTask = imageReference.putFile(imagePath);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Upload failed", Toast.LENGTH_SHORT)
.show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(RegistrationActivity.this, "Upload successful", Toast.LENGTH_SHORT)
.show();
}
});
UserProfile userProfile = new UserProfile(age, email, name);
myReference.setValue(userProfile);
}
}
Replace your sendUserData with this
private void sendUserData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myReference = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.
child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
imageReference.putFile(imagePath).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Upload failed", Toast.LENGTH_SHORT)
.show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(RegistrationActivity.this, "Upload successful", Toast.LENGTH_SHORT)
.show();
}
});
UserProfile userProfile = new UserProfile(age, email, name);
myReference.setValue(userProfile);
}
Related
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;
}
I'm trying to make a profile activity where user's data will be shown and also user can edit their data also. Everything works fine. There is no error showing in the code but when i'm trying to upload an image using camera or gallery. It's not uploading in the firebase storage. Also no "Toast" message shows. I'm fully stucked in this problem. How to solve this problem? The following code is given below:
package com.example.muthomap;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
public class Profile extends AppCompatActivity {
//views
ImageView profilephoto;
private TextView pname,pemail,pphone;
private FloatingActionButton medit;
//Instance of FirebaseAuth
private FirebaseAuth mAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
//progress Dialog
ProgressDialog progressDialog;
//permissions constants
private static final int CAMERA_REQUEST_CODE=100;
private static final int STORAGE_REQUEST_CODE=200;
private static final int IMAGE_PICK_GALLERY_REQUEST_CODE=300;
private static final int IMAGE_PICK_CAMERA_REQUEST_CODE=400;
//arrays of permissions to be requested
String cameraPermissions[];
String storagePermissions[];
//uri of picked image
Uri image_uri;
//to check either profile or cover photo
String profileOrCoverPhoto;
//storage
StorageReference storageReference;
//path where imagees of profile and cover will be stored
String storagePath = "Users_Profile_Cover_Imgs/";
public Profile(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
profilephoto= findViewById(R.id.profile_photo);
pname= findViewById(R.id.profile_name);
pemail= findViewById(R.id.profile_email);
pphone= findViewById(R.id.profile_mobile);
medit= findViewById(R.id.edit);
//Initialize the FirebaseAuth instance
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference= firebaseDatabase.getReference("user").child("customers");
storageReference = FirebaseStorage.getInstance().getReference().child(storagePath);
//intitalize arrays of permissions
cameraPermissions= new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions= new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
progressDialog= new ProgressDialog(this);
progressDialog.setMessage("Updating User.....");
/*We need to get current signed in users email,name,phone etc. And we retrive user
detail using email.*/
/* by using OrderByChild query we will show the detail from a node whose
key named email has value equal to currently signed in email.
It will search all nodes, where the key matches it will get it's detail.
*/
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//check until getting required data
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//get data
String name = "" + ds.child("name").getValue();
String email = "" + ds.child("email").getValue();
String phone = "" + ds.child("phone").getValue();
String image = "" + ds.child("image").getValue();
//set data
pname.setText(name);
pemail.setText(email);
pphone.setText(phone);
try {
Picasso.get().load(image).resize(50, 50)
.centerCrop().into(profilephoto);
} catch (Exception e) {
//if there is any exceptions while getting image then set defaults
Picasso.get().load(R.drawable.ic_default_face).into(profilephoto);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//handleing floating Button
medit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShowEditProfileDialog();
}
});
}
private boolean checkStoragePermission(){
/*check if storage permission is enebled or not
return true if enebled
return false if not
*/
boolean result = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void requestStoragePermission(){
//request runtime storage permission
requestPermissions(storagePermissions,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission(){
/*check if storage permission is enebled or not
return true if enebled
return false if not
*/
boolean result = ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission(){
//request runtime camera permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(cameraPermissions,CAMERA_REQUEST_CODE);
}
}
private void ShowEditProfileDialog() {
/*show dialog of options
*1. Upload Photo
*2. Edit Name
*3. Edit phone
*/
//options ro show in Dialog
String options[ ] = {"Upload Photo","Edit Name","Edit phone"};
//alert Dialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
//title
builder.setTitle("Choose Actions");
//set items
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
if (which == 0){
//Edit Profile picture clicked
progressDialog.setMessage("Updating Profile Picture");
profileOrCoverPhoto = "image";
showImagePicDialog();
}
else if (which == 1){
//Edit Name clicked
progressDialog.setMessage("Updating Name");
showNamePhoneUpdateDialog("name");
}
else if (which == 2){
//Edit Phone clicked
progressDialog.setMessage("Updating Phone Number");
showNamePhoneUpdateDialog("phone");
}
}
});
builder.create().show();
}
private void showNamePhoneUpdateDialog(final String key) {
//custom dialog
AlertDialog.Builder builder= new AlertDialog.Builder(Profile.this);
builder.setTitle("Update "+ key);
//set layout of dialog
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10,10,10,10);
//add edit text
final EditText editText = new EditText(Profile.this);
editText.setHint("Enter "+key);
linearLayout.addView(editText);
builder.setView(linearLayout);
//add button to update
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//input text
String val = editText.getText().toString().trim();
//validate if user has entered somethig or not
if ((!TextUtils.isEmpty(val))){
progressDialog.show();
HashMap<String, Object> results = new HashMap<>();
results.put(key, val);
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this, ""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(Profile.this, "Please Enter ", Toast.LENGTH_SHORT).show();
}
}
});
//add button to cancel
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
//create and show dialog
builder.create().show();
}
private void showImagePicDialog() {
//options containing options Camera and Gallery
String options[ ] = {"Camera","Gallery"};
//alert Dialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
//title
builder.setTitle("Pick Image From");
//set items
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
if (which == 0){
//Camera Clicked
if (!checkCameraPermission()){
requestCameraPermission();
}
else {
pickFromCamera();
}
}
else if (which == 1){
//Gallery Picked
if (!checkStoragePermission()){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestStoragePermission();
}
}
else{
pickFromGallery();
}
}
}
});
builder.create().show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
/*This method called when user press Allow or Deny from permission request dialog
here we will handle permissions cases (allowed or denied)
*/
switch (requestCode){
case CAMERA_REQUEST_CODE:{
//picking from camera, first check if camera and storage permission allowed or not
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted= grantResults[1]==PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted){
//permission enebled
pickFromCamera();
}
else {
Toast.makeText(this, "Please eneble Camera and Storage permission",Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE:{
//picking from storage, first check if storage permission allowed or not
if (grantResults.length >0 ){
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted){
//permission enebled
pickFromGallery();
}
else {
Toast.makeText(this, "Please eneble Storage permission",Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//This method will be called after picking image from Camera or Gallery
if (resultCode == RESULT_OK){
if (resultCode == IMAGE_PICK_GALLERY_REQUEST_CODE){
//image is picked from gallery , get uri of image
image_uri = data.getData();
uploadProfilePhoto(image_uri);
}
if (resultCode == IMAGE_PICK_CAMERA_REQUEST_CODE){
//image is picked from Camera, get uri
uploadProfilePhoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfilePhoto(Uri uri) {
//show progress
progressDialog.show();
/*The parameter "image_uri" contains the uri of image picked either from camera or gallery
*Will use UID of the currently signed in user as name of the image so ther will be only one image
* profile and one image for cover for each user */
//path and name of image to be stored in firebase storage
String filePathAndName = storagePath+ ""+ profileOrCoverPhoto +"_"+ user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathAndName);
storageReference2nd.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask=taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();
//check if uploading is successfull
if (uriTask.isSuccessful()){
//image uploaded
//add url in user's database
HashMap<String,Object> results = new HashMap<>();
results.put(profileOrCoverPhoto, downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//url in database of user is added successfully
//dismiss progress bar
progressDialog.dismiss();
Toast.makeText(Profile.this, "Image Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Error Updating Image", Toast.LENGTH_SHORT).show();
}
});
}
else {
//error
progressDialog.dismiss();
Toast.makeText(Profile.this, "Some Error Occurd", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
//Intent of picking image from device camera
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
//put image uri
image_uri=Profile.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
//intent to open camera
Intent cameraIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_REQUEST_CODE);
}
private void pickFromGallery() {
//pick from gallery
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_REQUEST_CODE);
}
}
Logcat: Logcat log
https://i.stack.imgur.com/2NqTU.jpg
I want to record the account data to firebase realltime-database when I logged in with Google Account/facebook account in app but I couldn't expect my goal because whiIe I'm starting to log in application and the storing processing, the application is force closed.
This was code I've tried
LoginActivity.java
package id.co.dolansemarang.loginfirebaseds;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DatabaseReference;
import id.co.dolansemarang.loginfirebaseds.model.User;
import id.co.dolansemarang.loginfirebaseds.model.UsersProvider;
public class LoginActivity extends BaseActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "Login User";
private static final int RC_SIGN_IN = 1234;
CallbackManager callbackManager;
GoogleSignInClient googleSignInClient;
GoogleApiClient mGoogleApiClient;
LoginButton loginButton;
Button btnLogin;
LinearLayout btnGoogleSignIn, btnFacebookSignIn;
EditText edtEmailLogin, edtPasswordLogin;
TextView tvResetPass, tvRegisterLink;
FirebaseAuth firebaseAuthLogin;
FirebaseAuth.AuthStateListener authStateListener;
// DatabaseReference userRefLogin;
FirebaseUser curUser;
DatabaseReference providerLoginRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnLogin = findViewById(R.id.btn_login);
edtEmailLogin = findViewById(R.id.edt_email_login);
edtPasswordLogin = findViewById(R.id.edt_password_login);
tvResetPass = findViewById(R.id.tv_reset_pass);
tvRegisterLink = findViewById(R.id.tv_register_link);
btnGoogleSignIn = findViewById(R.id.btn_sign_in_with_google);
btnFacebookSignIn = findViewById(R.id.btn_sign_in_with_facebook);
loginButton = findViewById(R.id.login_button);
firebaseAuthLogin = FirebaseAuth.getInstance();
// authStateListener = new FirebaseAuth.AuthStateListener() {
// #Override
// public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
// if (curUser != null) {
// Log.d(TAG, "onAuthStateChanged: Sign In");
// } else {
// Log.d(TAG, "onAuthStateChanged:signed_out");
// }
// }
// };
//Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(LoginActivity.this)
.enableAutoManage(LoginActivity.this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
googleSignInClient = GoogleSignIn.getClient(this, gso);
//facebook Sign In
callbackManager = CallbackManager.Factory.create();
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook: onSuccess Login" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook: onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook: onError", error);
}
});
btnFacebookSignIn.setOnClickListener(this);
btnLogin.setOnClickListener(this);
tvResetPass.setOnClickListener(this);
btnGoogleSignIn.setOnClickListener(this);
tvRegisterLink.setOnClickListener(this);
}
private void handleFacebookAccessToken(AccessToken accessToken) {
Log.d(TAG, "handleFacebookAccessToken : " + accessToken);
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
firebaseAuthLogin.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "your account has been success to register");
FirebaseUser user = firebaseAuthLogin.getCurrentUser();
// updateUI(user);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
Toast.makeText(LoginActivity.this, "Welcome " + user.getEmail() + "", Toast.LENGTH_LONG).show();
finish();
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
// updateUI(null);
}
hideProgressDialog();
}
});
}
#Override
protected void onStart() {
super.onStart();
// cek apakah pengguna sudah pernah masuk sehingga ada update UI disini
if(authStateListener!= null){
FirebaseUser currentUser = firebaseAuthLogin.getCurrentUser();
updateUI(currentUser);
authStateListener.onAuthStateChanged(firebaseAuthLogin);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
// GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
// handleSignInResult(result);
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
loginWithGoogle(account);
} catch (ApiException e) {
Log.w(TAG, "Google Sign I Failed", e);
updateUI(curUser);
}
}
}
private void loginWithGoogle(GoogleSignInAccount account) {
showProgressDialog();
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
firebaseAuthLogin.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String nama =FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
String providerID =FirebaseAuth.getInstance().getCurrentUser().getProviderId();
UsersProvider users = new UsersProvider (uid,nama,email,providerID);
providerLoginRef.child("UsersProviders").child(uid).setValue(users).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
updateUI(curUser);
}
});
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
}
hideProgressDialog();
}
});
}
private void loginUserWithEmail(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
firebaseAuthLogin.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "your account has been success to register");
FirebaseUser user = firebaseAuthLogin.getCurrentUser();
if (user.isEmailVerified()) {
updateUI(user);
} else {
Toast.makeText(LoginActivity.this, "Silakan cek inbox untuk verifikasi", Toast.LENGTH_LONG).show();
}
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
// updateUI(null);
}
hideProgressDialog();
}
});
}
private void updateUI(FirebaseUser user) {
hideProgressDialog();
if (user != null) {
user.getDisplayName();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
Toast.makeText(this, "Welcome " + user.getEmail() + "", Toast.LENGTH_LONG).show();
finish();
}
}
private boolean validateForm() {
boolean valid = true;
String email = edtEmailLogin.getText().toString();
String password = edtPasswordLogin.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Harap isi email kembali", Toast.LENGTH_LONG).show();
valid = false;
} else {
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Harap isi password kembali", Toast.LENGTH_LONG).show();
valid = false;
} else {
if (password.length() <= 6) {
Toast.makeText(getApplicationContext(), "password contained minimum 6 character", Toast.LENGTH_LONG).show();
valid = false;
}
}
}
return valid;
}
#Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.btn_login) {
loginUserWithEmail(edtEmailLogin.getText().toString(), edtPasswordLogin.getText().toString());
} else if (i == R.id.tv_reset_pass) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
finish();
} else if (i == R.id.btn_sign_in_with_google) {
signInGoogle();
} else if (i == R.id.tv_register_link) {
gotoRegister();
} else if (i == R.id.btn_sign_in_with_facebook) {
loginButton.performClick();
}
}
private void gotoRegister() {
startActivity(new Intent(this, RegisterActivity.class));
finish();
}
private void signInGoogle() {
Intent signIntent = googleSignInClient.getSignInIntent();
startActivityForResult(signIntent, RC_SIGN_IN);
}
#Override
protected void onStop() {
super.onStop();
if (authStateListener != null) {
firebaseAuthLogin.removeAuthStateListener(authStateListener);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
I expect I can store but there is opposite because the logcat show the error like this
2019-05-04 20:55:13.471 16495-16495/id.co.dolansemarang.loginfirebaseds E/AndroidRuntime: FATAL EXCEPTION: main
Process: id.co.dolansemarang.loginfirebaseds, PID: 16495
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
at id.co.dolansemarang.loginfirebaseds.LoginActivity$3.onComplete(LoginActivity.java:203)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
I would like you to help me, please. Thanks before
To solve this, please change the following line of code:
DatabaseReference providerLoginRef;
to
DatabaseReference providerLoginRef = FirebaseDatabase.getInstance().getReference();
So you got that error because your providerLoginRef object was never initialized.
I've logined google account on the application but when I logout of the system, the application force closed. In another, couldn't show google account chooser when I started to login the application again
This was the code I've tried and the problem is null object reference on methode GoogleSignIn Client and I couldn't find method revokeaccess cause it was unavailable.
Login Activity.java
package id.co.dolansemarang.loginfirebaseds;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
public class LoginActivity extends BaseActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "Login User";
private static final int RC_SIGN_IN = 1234;
GoogleSignInClient googleSignInClient;
GoogleApiClient mGoogleApiClient;
Button btnLogin;
LinearLayout btnGoogleSignIn;
EditText edtEmailLogin, edtPasswordLogin;
TextView tvResetPass;
FirebaseAuth firebaseAuthLogin;
// DatabaseReference userRefLogin;
FirebaseUser curUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnLogin = findViewById(R.id.btn_login);
edtEmailLogin = findViewById(R.id.edt_email_login);
edtPasswordLogin = findViewById(R.id.edt_password_login);
tvResetPass = findViewById(R.id.tv_reset_pass);
btnGoogleSignIn = findViewById(R.id.btn_sign_in_with_google);
//Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(LoginActivity.this)
.enableAutoManage(LoginActivity.this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
googleSignInClient = GoogleSignIn.getClient(this, gso);
firebaseAuthLogin = FirebaseAuth.getInstance();
btnLogin.setOnClickListener(this);
tvResetPass.setOnClickListener(this);
btnGoogleSignIn.setOnClickListener(this);
updateUI(curUser);
}
#Override
protected void onStart() {
super.onStart();
// cek apakah pengguna sudah pernah masuk sehingga ada update UI disini
FirebaseUser currentUser = firebaseAuthLogin.getCurrentUser();
updateUI(currentUser);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RC_SIGN_IN){
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try{
GoogleSignInAccount account = task.getResult(ApiException.class);
loginWithGoogle(account);
}
catch (ApiException e){
Log.w(TAG, "Google Sign I Failed", e);
updateUI(curUser);
}
}
}
private void loginWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "FirebaseAuthWithGoogle" +account.getId());
showProgressDialog();
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
firebaseAuthLogin.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "your account has been success to register");
FirebaseUser user = firebaseAuthLogin.getCurrentUser();
updateUI(user);
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
// updateUI(null);
}
hideProgressDialog();
}
});
}
private void loginUserWithFirebase(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
firebaseAuthLogin.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "your account has been success to register");
FirebaseUser user = firebaseAuthLogin.getCurrentUser();
updateUI(user);
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
// updateUI(null);
}
hideProgressDialog();
}
});
}
private void updateUI(FirebaseUser user) {
hideProgressDialog();
if (user != null && user.isEmailVerified()) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
Toast.makeText(this, "Welcome " + user.getEmail() + "", Toast.LENGTH_LONG).show();
finish();
} else if (user != null && !user.isEmailVerified()) {
Toast.makeText(getApplicationContext(), "Please verify your Email, first", Toast.LENGTH_SHORT).show();
} else {
Log.d(TAG, "Selamat datang");
}
}
private boolean validateForm() {
boolean valid = true;
String email = edtEmailLogin.getText().toString();
String password = edtPasswordLogin.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Harap isi email kembali", Toast.LENGTH_LONG).show();
valid = false;
} else {
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Harap isi password kembali", Toast.LENGTH_LONG).show();
valid = false;
} else {
if (password.length() <= 6) {
Toast.makeText(getApplicationContext(), "password contained minimum 6 character", Toast.LENGTH_LONG).show();
valid = false;
}
}
}
return valid;
}
#Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.btn_login) {
loginUserWithFirebase(edtEmailLogin.getText().toString(), edtPasswordLogin.getText().toString());
} else if (i == R.id.tv_reset_pass) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
finish();
} else if(i == R.id.btn_sign_in_with_google){
signInGoogle();
}
}
private void signInGoogle() {
Intent signIntent = googleSignInClient.getSignInIntent();
startActivityForResult(signIntent, RC_SIGN_IN);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Main Activity.java
package id.co.dolansemarang.loginfirebaseds;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
FirebaseAuth firebaseAuthMain;
FirebaseUser user;
Button btnKeluar;
GoogleSignInClient googleSignInClient;
GoogleApiClient googleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnKeluar = findViewById(R.id.btn_sign_out);
firebaseAuthMain = FirebaseAuth.getInstance();
btnKeluar.setOnClickListener(this);
user = firebaseAuthMain.getCurrentUser();
}
#Override
public void onClick(View v) {
int i = v.getId();
if(i == R.id.btn_sign_out){
// firebaseAuthMain.signOut();
// googleSignInClient.signOut().addOnCompleteListener(this, new OnCompleteListener<Void>() {
// #Override
// public void onComplete(#NonNull Task<Void> task) {
// updateUI(null);
// }
// });
// updateUI(user);
signOutApp();
signOutGoogle();
}
}
private void signOutGoogle() {
googleSignInClient.signOut().addOnCompleteListener(this,
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
updateUI(null);
}
});
}
private void signOutApp() {
firebaseAuthMain.signOut();
updateUI(user);
}
private void updateUI(FirebaseUser user) {
if(user != null){
startActivity(new Intent(MainActivity.this, LoginActivity.class));
Toast.makeText(this,"Thanks for visiting",Toast.LENGTH_LONG).show();
finish();
}
}
}
I expected when I login with either email or google account and then Logout without conflict. So, How should I do?
Following the document here google-signin
Just only FirebaseAuth.getInstance().signOut(); to logout
So you might have to call signOutApp() function only.
For my app to register a user all it fills needs to be filled. However when I select an image when clicking on the image view; it doesn't come up, and after filling the other detail I can't create a new user due to the the imageview not being filled. I don't have no errors in my logcat.It only stopped creating a new user after implementing the Image part in the code.
package com.example.appdemo;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
public class RegistrationActivity extends AppCompatActivity {
private EditText userName, userPassword, userEmail,userAge;
private Button regButton;
private TextView userLogin;
private ImageView userProfilePic;
private FirebaseAuth firebaseAuth;
String email, name, age, password;
private FirebaseStorage firebaseStorage;
private static int PICK_IMAGE = 123;
Uri imagePath;
private StorageReference storageReference;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == PICK_IMAGE && requestCode == RESULT_OK && data.getData() != null){
imagePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imagePath);
userProfilePic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setupUIViewas();
firebaseAuth = FirebaseAuth.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
userProfilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");// for document //application/* audio/* mp3/*
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "select image"),PICK_IMAGE);
}
});
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(validate()){
//upload data to database
String user_email = userEmail.getText().toString().trim();
String user_password = userPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(user_email,user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//have to put the verification code here.
sendUserData();
// signs out user after registration and send you to login
firebaseAuth.signOut();
Toast.makeText(RegistrationActivity.this,"Registration successful",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(RegistrationActivity.this,MainActivity.class));
}else{ Toast.makeText(RegistrationActivity.this,"Registration failed please try again",Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegistrationActivity.this,MainActivity.class));
}
});
}
private void setupUIViewas(){
userName = (EditText) findViewById(R.id.etUserName);
userPassword = (EditText) findViewById(R.id.etUserPassword);
userEmail = (EditText) findViewById(R.id.etUserEmail);
regButton = (Button) findViewById(R.id.btnRegister);
userLogin = (TextView) findViewById(R.id.tvUserLogin);
userAge = (EditText) findViewById(R.id.etAge);
userProfilePic = (ImageView) findViewById(R.id.ivProfile);
}
private Boolean validate(){
Boolean result = false;
name = userName.getText().toString();
password = userPassword.getText().toString();
email = userEmail.getText().toString();
age = userAge.getText().toString();
if(name.isEmpty()|| password.isEmpty()||email.isEmpty() || age.isEmpty() || imagePath == null){
Toast.makeText(this, "Please fill in all the details", Toast.LENGTH_SHORT).show();
}else {
result = true;
}
return result;
}
private void sendUserData(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myref = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic");//User Id/Images/profile_pic.jpg
UploadTask uploadTask = imageReference.putFile(imagePath);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this,"File upload failed!",Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(RegistrationActivity.this,"File upload successful!",Toast.LENGTH_SHORT).show();
}
});
UserProfile userProfile = new UserProfile(age,email,name);
myref.setValue(userProfile);
}
}
Check the condition you wrote in onActivityResult :)
The second requestCode should be resultCode.
Change:
(requestCode == PICK_IMAGE && requestCode == RESULT_OK &&
data.getData() != null)
To:
(requestCode == PICK_IMAGE && resultCode == RESULT_OK &&
data.getData() != null)