Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am creating a chat app. users can change their info. after making a new account, they have to create their profile. the profile activity restarts itself again and again. can I fix it or It is an Android problem
I have tried everything at here!
settingsActivity.java:
package com.satyamedh.chitchatmessenger;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Button Updatebutton;
private EditText Username, Status;
private CircleImageView profileImage;
private String currentUID;
private DatabaseReference rootref;
private StorageReference ProfileImagesRef;
private String downloadUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
final CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
Uri resultUri = result.getUri();
final StorageReference ref = ProfileImagesRef.child(currentUID + ".jpg");
ref.putFile(resultUri)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri)
{
Toast.makeText(SettingsActivity.this, uri.toString(), Toast.LENGTH_SHORT).show();
downloadUrl = uri.toString();
rootref.child("Users").child(currentUID).child("image")
.setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile Image Uploaded Successfully...", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SettingsActivity.this, "Some error has occurred, please try again later...", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
});
}
}
}
private void getUserInfo()
{
rootref.child("Users").child(currentUID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String oldImage;
if(dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("status"))) {
String oldUsername = dataSnapshot.child("name").getValue().toString();
String oldStatus = dataSnapshot.child("status").getValue().toString();
Username.setText(oldUsername);
Status.setText(oldStatus);
}
if (dataSnapshot.hasChild("image"))
{
oldImage = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(oldImage).placeholder(R.drawable.profile_image).into(profileImage);
}
Toast.makeText(SettingsActivity.this, "Please update your profile", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void updateSettings()
{
String setUserName = Username.getText().toString();
String setStatus = Status.getText().toString();
if (TextUtils.isEmpty(setUserName))
{
Toast.makeText(this, "Please enter Username to continue", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus))
{
Toast.makeText(this, "Please enter Status to continue", Toast.LENGTH_SHORT).show();
}
else
{
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUID);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
rootref.child("Users").child(currentUID).setValue(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile updated successfully", Toast.LENGTH_SHORT).show();
askUserToUseApp();
}
else
{
String messegess = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error : " + messegess, Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
currentUID = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
rootref = FirebaseDatabase.getInstance().getReference();
ProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile images");
initializeFields();
Updatebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateSettings();
}
});
getUserInfo();
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(SettingsActivity.this);
}
});
updateUserStatus("online");
}
private void initializeFields()
{
Updatebutton = findViewById(R.id.update_settings);
Username = findViewById(R.id.set_user_name);
Status = findViewById(R.id.set_status);
profileImage = findViewById(R.id.set_profile_image);
}
private void askUserToUseApp() {
Intent loginIntent = new Intent(SettingsActivity.this, MainActivity.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
#Override
protected void onStop()
{
super.onStop();
updateUserStatus("offline");
}
#Override
protected void onDestroy()
{
super.onDestroy();
updateUserStatus("offline");
}
private void updateUserStatus(String state)
{
Calendar calForDate = Calendar.getInstance();
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM, yyyy");
String currentDate = simpleDateFormat.format(calForDate.getTime());
Calendar calForTime = Calendar.getInstance();
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("hh:mm:ss a");
String currentTime = simpleTimeFormat.format(calForTime.getTime());
HashMap<String, Object> onlineState = new HashMap<>();
onlineState.put("time", currentTime);
onlineState.put("date", currentDate);
onlineState.put("state", state);
rootref.child("Users").child(currentUID).child("userState")
.updateChildren(onlineState);
}
}
there are no errors. but I can stop it by uninstalling it using ADB
Edit: it works fine after I edit it manually edit in firebase and then open that activity from the main activity.
Edit2:
registerActivity.java
package com.satyamedh.chitchatmessenger;
import android.app.ProgressDialog;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
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.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
public class ResigsterActivity extends AppCompatActivity {
private Button registerButton;
private EditText userEmail, userPassword;
private TextView loginactivityLink;
private FirebaseAuth mAuth;
private DatabaseReference rootref;
private ProgressDialog loading_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resigster);
FirebaseApp.initializeApp(this);
mAuth = FirebaseAuth.getInstance();
rootref = FirebaseDatabase.getInstance().getReference();
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.register_banner_ad);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
initializeFields();
loginactivityLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
askUserToLogin();
}
});
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createAccount();
}
});
}
private void createAccount()
{
final String email = userEmail.getText().toString();
final String password = userPassword.getText().toString();
if (TextUtils.isEmpty(email))
{
Toast.makeText(this, "Please enter Email...", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "Please enter Password...", Toast.LENGTH_SHORT).show();
}
else
{
loading_bar.setTitle("Creating new account");
loading_bar.setMessage("Please wait...");
loading_bar.setCanceledOnTouchOutside(true);
loading_bar.show();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
final String currentUserID = mAuth.getCurrentUser().getUid();
rootref.child("Users").child(currentUserID).setValue("");
final String[] deviceToken = new String[1];
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
deviceToken[0] = instanceIdResult.getToken();
// Do whatever you want with your token now
// i.e. store it on SharedPreferences or DB
// or directly send it to server
rootref.child("Users").child(currentUserID).child("device_token").setValue(deviceToken[0]).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(ResigsterActivity.this, "Account created successfully...", Toast.LENGTH_SHORT).show();
loading_bar.dismiss();
mAuth.signInWithEmailAndPassword(email, password);
askUserToMain();
}
}
});
rootref.child("Users").child(currentUserID).child("image").setValue("https://firebasestorage.googleapis.com/v0/b/chit-chat-web-chat.appspot.com/o/profile_image.png?alt=media&token=12bc53c2-c27d-420f-9d5f-f84c22a6449c");
rootref.child("Users").child(currentUserID).child("name").setValue("Enter your name here");
rootref.child("Users").child(currentUserID).child("status").setValue("Enter your status here");
}
});
}
else
{
String messegess = task.getException().toString();
Toast.makeText(ResigsterActivity.this, "Error : " + messegess, Toast.LENGTH_SHORT).show();
loading_bar.dismiss();
}
}
});
}
}
private void initializeFields()
{
registerButton = (Button) findViewById(R.id.register_button);
userEmail = (EditText) findViewById(R.id.register_email);
userPassword = (EditText) findViewById(R.id.register_password);
loginactivityLink = (TextView) findViewById(R.id.register_sign_in);
loading_bar = new ProgressDialog(this);
}
private void askUserToLogin() {
Intent loginIntent = new Intent(ResigsterActivity.this, LoginActivity.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void askUserToMain() {
Intent mainIntent = new Intent(ResigsterActivity.this, ProfileActivity.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
private void askUserToUseApp() {
Intent loginIntent = new Intent(ResigsterActivity.this, LoginActivity.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
}
Might be not related answer but whenever you are using any firebase or firestore
event try to pass "this("activity context")" as the first parameter it will manage the
activity life cycle and will remove you listener when your app will be in background.
Related
i'm creating a sing in up and whenever i log in then log out i crash, I get this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at net.app.MainActivity.onCreate(MainActivity.java:89)
with the line 89 being:
StorageReference profileRef = storageReference.child("users/"+fAuth.getCurrentUser().getUid()+"/profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profileImage);
}
});
and the mainactivity code is:
package net.smallacademy.authenticatorapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
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.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import javax.annotation.Nullable;
public class MainActivity extends AppCompatActivity {
private static final int GALLERY_INTENT_CODE = 1023 ;
TextView fullName,email,phone,verifyMsg;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
String userId;
Button resendCode;
Button resetPassLocal,changeProfileImage;
FirebaseUser user;
ImageView profileImage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize variable for navigation
BottomNavigationView bottomNavigationView=findViewById(R.id.bottom_navigation);
//set home to be selected
bottomNavigationView.setSelectedItemId(R.id.profile);
//preform itemselectedlistener
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.home:
startActivity(new Intent(getApplicationContext(),home.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
return true;
case R.id.exercice:
startActivity(new Intent(getApplicationContext(),hi.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
phone = findViewById(R.id.profilePhone);
fullName = findViewById(R.id.profileName);
email = findViewById(R.id.profileEmail);
resetPassLocal = findViewById(R.id.resetPasswordLocal);
profileImage = findViewById(R.id.profileImage);
changeProfileImage = findViewById(R.id.changeProfile);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storageReference = FirebaseStorage.getInstance().getReference();
StorageReference profileRef = storageReference.child("users/"+fAuth.getCurrentUser().getUid()+"/profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profileImage);
}
});
resendCode = findViewById(R.id.resendCode);
verifyMsg = findViewById(R.id.verifyMsg);
userId = fAuth.getCurrentUser().getUid();
user = fAuth.getCurrentUser();
if(!user.isEmailVerified()){
verifyMsg.setVisibility(View.VISIBLE);
resendCode.setVisibility(View.VISIBLE);
resendCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(v.getContext(), "Verification Email Has been Sent.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("tag", "onFailure: Email not sent " + e.getMessage());
}
});
}
});
}
DocumentReference documentReference = fStore.collection("users").document(userId);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if(documentSnapshot.exists()){
phone.setText(documentSnapshot.getString("phone"));
fullName.setText(documentSnapshot.getString("fName"));
email.setText(documentSnapshot.getString("email"));
}else {
Log.d("tag", "onEvent: Document do not exists");
}
}
});
resetPassLocal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetPassword = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter New Password > 8 Characters long.");
passwordResetDialog.setView(resetPassword);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String newPassword = resetPassword.getText().toString();
user.updatePassword(newPassword).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "Password Reset Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Password Reset Failed.", Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close
}
});
passwordResetDialog.create().show();
}
});
changeProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// open gallery
Intent i = new Intent(v.getContext(),EditProfile.class);
i.putExtra("fullName",fullName.getText().toString());
i.putExtra("email",email.getText().toString());
i.putExtra("phone",phone.getText().toString());
startActivity(i);
//
}
});
}
//this is the logout function
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(getApplicationContext(),Login.class));
Toast.makeText(this,"Logging Out",Toast.LENGTH_SHORT).show();
finish();
}
}
I don't get why it's happening,it was working fine before
Before using fAuth.getCurrentUser().getUid() check if there is a user currently signed in
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
if(user!=null){
StorageReference profileRef= storageReference.child("users/"+user.getUid()+"/profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>(){
#Override
public void onSuccess(Uri uri){
Picasso.get().load(uri).into(profileImage);
}
});
}
That should solve the problem, but still you will have to handle a user not signed in
I want my firebase database to initialize with the user profile pic image URL I try to add this but i thing profileImageUrl variable not initialize with ImageUri variable? pls help to get this thing done...
i just want 5th variable profile image link initialize with image url string that is come from URI variable but it's not initialize
this is my project logcat
2020-05-31 11:23:23.475 23993-23993/com.ramzan.snnstocks D/WindowClient: Add to mViews: DecorView#3fca5d8[UserRegistration], this = android.view.WindowManagerGlobal#878094
2020-05-31 11:23:23.479 23993-23993/com.ramzan.snnstocks D/ViewRootImpl[UserRegistration]: hardware acceleration is enabled, this = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}
2020-05-31 11:23:23.482 23993-23993/com.ramzan.snnstocks V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}, this = DecorView#3fca5d8[UserRegistration]
2020-05-31 11:23:23.688 23993-24035/com.ramzan.snnstocks D/OpenGLRenderer: CanvasContext() 0x90c11000 initialize window=0x90a6f700, title=com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration
2020-05-31 11:23:26.588 23993-23993/com.ramzan.snnstocks V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}, this = DecorView#3fca5d8[UserRegistration]
2020-05-31 11:23:32.551 23993-23993/com.ramzan.snnstocks I/UserRegistration: OnActivityResult: RESULT OK
2020-05-31 11:23:32.566 23993-23993/com.ramzan.snnstocks V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{2607f29 com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration,ident = 2}, this = DecorView#3fca5d8[UserRegistration]
2020-05-31 11:23:32.596 23993-24035/com.ramzan.snnstocks D/OpenGLRenderer: CanvasContext() 0x90c11000 initialize window=0x90a6f700, title=com.ramzan.snnstocks/com.ramzan.snnstocks.UserRegistration
2020-05-31 11:24:12.578 23993-23993/com.ramzan.snnstocks D/WindowClient: Remove from mViews: DecorView#3fca5d8[UserRegistration], this = android.view.WindowManagerGlobal#878094
2020-05-31 11:24:16.941 23993-23993/com.ramzan.snnstocks D/UserRegistration: onSuccess : https://firebasestorage.googleapis.com/v0/b/snn-stocks-c12fc.appspot.com/o/Profile_Image%2F9352682709.jpeg?alt=media&token=801f8e9d-cf5f-4d0a-890a-57823d50973a
here is my UserRegistration Activity...
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
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.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.ramzan.snnstocks.Model.Users;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import de.hdodenhof.circleimageview.CircleImageView;
public class UserRegistration extends AppCompatActivity {
private Spinner spinner;
private CircleImageView mImageView;
private static final int PICK_IMAGE = 101;
private EditText et_name, et_mobile, et_pass;
private Button btn_user;
private static String name, mobile, pass, spinner_port_place,profile_image_url;
private ProgressDialog loadingBar;
private DatabaseReference mDatabase;
private Bitmap bitmap;
private static final String TAG = "UserRegistration";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_registration);
mImageView = findViewById(R.id.profile_image);
loadingBar = new ProgressDialog(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spinner = findViewById(R.id.spinner_port_place);
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(UserRegistration.this,
android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Port_Name));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(myAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinner_port_place = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// initializing UI components
et_name = findViewById(R.id.textInputEditTextLayout_name);
et_mobile = findViewById(R.id.textInputEditTextLayout_mobile);
et_pass = findViewById(R.id.textInputEditTextLayout_pass);
btn_user = findViewById(R.id.btn_user_registration);
//onClick listner to Button
btn_user.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = et_name.getText().toString();
mobile = et_mobile.getText().toString();
pass = et_pass.getText().toString();
if (name.isEmpty()) {
et_name.setError("Full Name Required");
et_name.requestFocus();
} else if (mobile.isEmpty()) {
et_mobile.setError("Mobile Number is Required");
et_mobile.requestFocus();
} else if (pass.isEmpty()) {
et_pass.setError("Choose Your Password");
et_pass.requestFocus();
} else {
uploadData();
}
}
});
//OnClick Listner on Image View
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager())
!= null) {
startActivityForResult(intent, PICK_IMAGE);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
switch (resultCode) {
case RESULT_OK:
Log.i(TAG, "OnActivityResult: RESULT OK");
bitmap = (Bitmap) data.getExtras().get("data");
mImageView.setImageBitmap(bitmap);
break;
case RESULT_CANCELED:
Log.i(TAG, "OnActivityResult: RESULT CANCELLED");
break;
default:
break;
}
}
}
// upload data from here...
private void uploadData() {
loadingBar.setTitle("Registering Retailer....");
loadingBar.setMessage("Please Wait While We Are Creating Retailer Database");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
handleUpload(bitmap);
//Initialize Firebase Database;
mDatabase = FirebaseDatabase.getInstance().getReference();
createUserDatabase(name, mobile, pass, spinner_port_place, profile_image_url);
}
// profile image upload
private void handleUpload(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final StorageReference reference = FirebaseStorage.getInstance().getReference().child("Profile_Image").child(mobile + ".jpeg");
reference.putBytes(baos.toByteArray())
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(UserRegistration.this, "Upload Successfull...", Toast.LENGTH_SHORT).show();
getDownloadUrl(reference);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "onFailure : ", e.getCause());
}
});
}
private void getDownloadUrl(StorageReference reference) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
profile_image_url = uri.toString();
Log.d(TAG, "onSuccess : " + uri);
initializeUrl(uri);
}
});
}
private void initializeUrl(Uri uri) {
profile_image_url = uri.toString();
}
private void createUserDatabase(final String name, final String mobile, final String pass, final String spinner_port_place, final String profile_image_url) {
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!(dataSnapshot.child("Users").child(mobile).exists() && !(dataSnapshot.child("Admin").child(mobile).exists()))) {
Users new_user = new Users(name, mobile, pass, spinner_port_place, profile_image_url);
mDatabase.child("Users").child(mobile).setValue(new_user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
loadingBar.dismiss();
Toast.makeText(UserRegistration.this, "Your Account Has Been Created Successfully !", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(UserRegistration.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
loadingBar.dismiss();
String msg;
msg = e.toString();
Toast.makeText(UserRegistration.this, "Error : " + msg, Toast.LENGTH_LONG).show();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
You can try this:
private void uploadData() {
loadingBar.setTitle("Registering Retailer....");
loadingBar.setMessage("Please Wait While We Are Creating Retailer Database");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
handleUpload(bitmap);
}
private void initializeUrl(Uri uri) {
profile_image_url = uri.toString();
//Initialize Firebase Database;
mDatabase = FirebaseDatabase.getInstance().getReference();
createUserDatabase(name, mobile, pass, spinner_port_place, profile_image_url);
}
And use addListenerForSingleValueEvent instead of addValueEventListener. More useful.
Upload the profile picture first, then save the user to the database.
This is not the case with your code. You save the user to the database and pass to the other screen until the profile picture is uploaded.
I'm trying to create a login and register system in Android Studio using Firebase. Registration works pretty well, user is created in Firebase successfully. But whenever I try to login it gives me this error "The password is invalid or the user does not have a password" even though the password I entered is the same I registered with. I think the problem might be with my code because user can login perfectly when I create account for given user on Firebase Console directly. What might cause this problem?
I provided my login and my register activity code:
Login activity
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity
{
private EditText emailLoginEditText, passwordLoginEditText;
private Button loginBtn;
private TextView signupLink, forgetPassword;
private ProgressDialog progressDialog;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailLoginEditText = findViewById(R.id.email_login);
passwordLoginEditText = findViewById(R.id.password_login);
loginBtn = findViewById(R.id.btn_login);
signupLink = findViewById(R.id.signup_reg);
forgetPassword = findViewById(R.id.forget_password);
progressDialog = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
startActivity(new Intent(MainActivity.this, RegistrationActivity.class));
}
});
forgetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
startActivity(new Intent(MainActivity.this, ResetActivity.class));
}
});
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
loginDetails();
}
});
}
private void loginDetails()
{
String email = emailLoginEditText.getText().toString().trim();
String password = passwordLoginEditText.getText().toString();
if(TextUtils.isEmpty(email))
{
emailLoginEditText.setError("Email can't be empty...");
return;
}
if(TextUtils.isEmpty(password))
{
passwordLoginEditText.setError("Password can't be empty...");
return;
}
else
{
progressDialog.setTitle("Login");
progressDialog.setMessage("Please wait while we are connecting you");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
else
{
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
And this is RegistrationActivity:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class RegistrationActivity extends AppCompatActivity
{
private EditText mEmailEditText, mPasswordEditText;
private Button mRegisterBtn;
private TextView SigninLink;
private ProgressDialog progressDialog;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
mEmailEditText = findViewById(R.id.email_reg);
mPasswordEditText = findViewById(R.id.password_reg);
mRegisterBtn = findViewById(R.id.btn_reg);
SigninLink = findViewById(R.id.signin_here);
progressDialog = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
SigninLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}
});
registration();
}
private void registration()
{
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String email = mEmailEditText.getText().toString().trim();
String password = mEmailEditText.getText().toString();
if(TextUtils.isEmpty(email))
{
mEmailEditText.setError("Email can't be empty...");
return;
}
if(TextUtils.isEmpty(password))
{
mPasswordEditText.setError("Password can't be empty...");
return;
}
progressDialog.setTitle("Creating Account");
progressDialog.setMessage("Please wait while we are creating your account");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
progressDialog.dismiss();
startActivity(new Intent(RegistrationActivity.this, HomeActivity.class));
}
else
{
Toast.makeText(RegistrationActivity.this, "Registration failed...", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
});
}
}
I am creating a chat app in which Users can create groups. when a users creates a group, he/she can choose a group profile image. but if i choose the image, it wont upload. what to do?
I have inspected the code, there is no error anywhere
CreateGroupActivity.java:
package com.satyamedh.chitchatmessenger;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import de.hdodenhof.circleimageview.CircleImageView;
public class CreateGroupActivity extends AppCompatActivity
{
private CircleImageView circleImageView;
private EditText editText;
private Button buttonconf, buttoncanc;
private Uri resultUri;
private final static int chosenProfileImage = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_group);
initializeFields();
buttoncanc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(CreateGroupActivity.this, MainActivity.class);
startActivity(profileIntent);
}
});
buttonconf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(editText.getText())){
Toast.makeText(CreateGroupActivity.this, "Please enter text..", Toast.LENGTH_SHORT).show();
}
else
{
DatabaseReference rootref = FirebaseDatabase.getInstance().getReference();
Intent settingsIntent = new Intent(CreateGroupActivity.this, chooseUserActivity.class);
String key = rootref.push().getKey();
settingsIntent.putExtra("groupKey", key);
settingsIntent.putExtra("groupImage", resultUri);
settingsIntent.putExtra("groupName", editText.getText().toString());
startActivity(settingsIntent);
}
}
});
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, chosenProfileImage);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == chosenProfileImage && resultCode == RESULT_OK && data != null)
{
Uri imageUri = data.getData();
CropImage
.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
final CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK) {
resultUri = result.getUri();
circleImageView.setImageURI(resultUri);
}
}
}
private void initializeFields()
{
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.my_adView_createGroup);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
circleImageView = findViewById(R.id.create_group_image);
editText = findViewById(R.id.create_group_name);
buttonconf = findViewById(R.id.confirm_button);
buttoncanc = findViewById(R.id.cancel_button);
}
}
chooseUserActivity.java:
package com.satyamedh.chitchatmessenger;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* A simple {#link Fragment} subclass.
*/
public class chooseUserActivity extends AppCompatActivity {
private RecyclerView myRecyclerList;
private DatabaseReference ContactsRef, UsersRef;
private String currentUID;
private DatabaseReference groupsRef;
private Button confirmButton;
private String downloadUrl ;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_choose_user);
super.onCreate(savedInstanceState);
initializeFields();
}
private void initializeFields()
{
myRecyclerList = findViewById(R.id.users_choser_group);
myRecyclerList.setLayoutManager(new LinearLayoutManager(chooseUserActivity.this));
FirebaseAuth mAuth = FirebaseAuth.getInstance();
currentUID = mAuth.getCurrentUser().getUid();
ContactsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
confirmButton = findViewById(R.id.confirm_group);
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.choose_user_adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
Toolbar toolbar = findViewById(R.id.users_chosers_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Choose users to be in " + getIntent().getExtras().get("groupName").toString());
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ContactsRef, Contacts.class)
.build()
;
FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>
adapter = new
FirebaseRecyclerAdapter <Contacts, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, final int position, #NonNull Contacts model)
{
final String string = getRef(position).getKey();
final String[] image = {"default_image"};
UsersRef
.child(string)
.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
if (dataSnapshot.hasChild("image"))
{
image[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(image[0]).placeholder(R.drawable.profile_image).into(holder.profileImageView);
}
final String name = dataSnapshot.child("name").getValue().toString();
holder.Username.setText(name);
holder.Userstatus.setText("Last seen: \n");
if(dataSnapshot.child("userState").hasChild("state"))
{
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
if(Objects.equals(state, "online"))
{
holder.Userstatus.setText(getString(R.string.Online));
}
else
{
holder.Userstatus.setText(getString(R.string.last_seen) + time + " " + date);
}
}
else
{
holder.Userstatus.setText("Offline");
}
final HashMap<String, Object> hashMap = new HashMap<>();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (!hashMap.containsKey(getRef(position).getKey())) {
holder.itemView.setPadding(15, 15, 15, 15);
holder.IsUserInGroup.setVisibility(View.VISIBLE);
if (hashMap.isEmpty()) {
hashMap.put(currentUID, "admin");
}
hashMap.put(getRef(position).getKey(), "non-admin");
}
else {
holder.itemView.setPadding(0, 0, 0, 0);
if (hashMap.size() == 1)
{
hashMap.remove(currentUID, "admin");
}
holder.IsUserInGroup.setVisibility(View.INVISIBLE);
hashMap.remove(getRef(position).getKey(), "non-admin");
}
groupsRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(getIntent().getExtras().get("groupKey").toString());
}
});
confirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
final StorageReference ProfileImagesRef;
ProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Groups profile images");
final StorageReference ref = ProfileImagesRef.child(getIntent().getExtras().get("groupKey").toString() + ".jpg");
ref.putFile((Uri) getIntent().getExtras().get("groupImage"))
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri)
{
Toast.makeText(chooseUserActivity.this, uri.toString(), Toast.LENGTH_SHORT).show();
downloadUrl = uri.toString();
}
});
}
});
groupsRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(getIntent().getExtras().get("groupKey").toString());
groupsRef.child("Users").updateChildren(hashMap);
groupsRef.child("Messages").setValue("");
groupsRef.child("Group info").child("group name").setValue(getIntent().getExtras().get("groupName").toString());
groupsRef.child("Group info").child("group image").setValue(downloadUrl);
Toast.makeText(chooseUserActivity.this, "Group created successfully", Toast.LENGTH_SHORT).show();
Intent settingsIntent = new Intent(chooseUserActivity.this, MainActivity.class);
settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(settingsIntent);
finish();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
myRecyclerList.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder
{
CircleImageView profileImageView;
TextView Username, Userstatus;
CheckBox IsUserInGroup;
ChatsViewHolder(#NonNull View itemView)
{
super(itemView);
profileImageView = itemView.findViewById(R.id.users_profile_image);
Username = itemView.findViewById(R.id.users_name);
Userstatus = itemView.findViewById(R.id.users_status);
IsUserInGroup = itemView.findViewById(R.id.IsUserInGroup);
}
}
}
Can anyone help me please?
I fixed it by moving the code in the on success listener itself
Image of DB in firebase console
I don't really know what's wrong here, I am able to add data on the other activity. I am getting error "java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()" and don't know how to fix. There are 3 other classes created only one other is adding data to firebase realtime database storage.
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.akshay.katiroll.R;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Profile extends AppCompatActivity {
EditText fName, lName, PhNo, BDay, Zip;
Button svBtn;
DatabaseReference mDataReference;
String keyUser;
String fNameStr, lNameStr, PhNoStr, BDayStr, ZipStr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
keyUser = getIntent().getStringExtra("USER_KEY");
mDataReference = FirebaseDatabase.getInstance().getReference().child("Users").child(keyUser);//error in this line
fName = (EditText) findViewById(R.id.fName);
lName = (EditText) findViewById(R.id.lName);
PhNo = (EditText) findViewById(R.id.phno);
BDay = (EditText) findViewById(R.id.bday);
Zip = (EditText) findViewById(R.id.zip);
svBtn = (Button) findViewById(R.id.svBtn);
svBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fNameStr = fName.getText().toString();
lNameStr = lName.getText().toString();
PhNoStr = PhNo.getText().toString();
BDayStr = BDay.getText().toString();
ZipStr = Zip.getText().toString();
if(!TextUtils.isEmpty(fNameStr) && !TextUtils.isEmpty(lNameStr) && !TextUtils.isEmpty(PhNoStr)) {
DatabaseReference mDataRef = mDataReference.child("Users").push();
mDataRef.child("firstName").setValue(""+fNameStr);
mDataRef.child("lastName").setValue(""+lNameStr);
mDataRef.child("phoneNumber").setValue(""+PhNoStr);
mDataRef.child("isVerified").setValue("verified");
if(!TextUtils.isEmpty(BDayStr)){
mDataRef.child("birthday").setValue(""+BDayStr);
}else{
mDataRef.child("birthday").setValue("null");
}
if(!TextUtils.isEmpty(ZipStr)){
mDataRef.child("zipcode").setValue("ZipStr");
}else{
mDataRef.child("zipcode").setValue("null");
}
Toast.makeText(Profile.this, "User profile added", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile.this, welcome.class));
}else{
Toast.makeText(Profile.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
}
}
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.akshay.katiroll.R;
import com.example.akshay.katiroll.SecondScreen.welcome;
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.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Iterator;
public class katiRoll extends AppCompatActivity {
EditText userEdit;
EditText passEdit;
String sUser, sPass;
Button sign;
Button reg;
Boolean signInVLogIn;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference mDatabaseRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kati_roll);
float Re = 255;
float Gr = 148;
float Bl = 0;
userEdit = (EditText)findViewById(R.id.user);
passEdit = (EditText)findViewById(R.id.pass);
sign = (Button) findViewById(R.id.sign);
reg = (Button) findViewById(R.id.reg);
userEdit.setTextColor(Color.rgb(Re,Gr,Bl));
passEdit.setTextColor(Color.rgb(Re,Gr,Bl));
sign.setTextColor(Color.rgb(Re,Gr,Bl));
reg.setTextColor(Color.rgb(Re,Gr,Bl));
mAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Users");
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(!TextUtils.isEmpty(sUser) && !TextUtils.isEmpty(sPass)){
signInVLogIn = true;
}else{
signInVLogIn = false;
}
if(user != null && signInVLogIn) {
}else{
//Toast.makeText(katiRoll.this, "Log In Failed", Toast.LENGTH_LONG).show();
}
}
};
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sUser = userEdit.getText().toString().trim();
sPass = passEdit.getText().toString().trim();
if(!TextUtils.isEmpty(sUser) && !TextUtils.isEmpty(sPass))
{
mAuth.signInWithEmailAndPassword(sUser, sPass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkUserValidation(dataSnapshot, sUser);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}else{
Toast.makeText(katiRoll.this, "User Login Doesn't Exist" , Toast.LENGTH_LONG).show();
}
}
});
}
}
});
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(katiRoll.this, signUp.class));
}
});
}
private void checkUserValidation(DataSnapshot dataSnapshot, String emailForVer) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext())
{
DataSnapshot dataUser = (DataSnapshot)iterator.next();
if (dataUser.child("emailUser").getValue().toString().equals(emailForVer)){
if(dataUser.child("isVerified").getValue().toString().equals("unverified"))
{
Intent in = new Intent(katiRoll.this, Profile.class);
in.putExtra("USER KEY", dataUser.child("userKey").getValue().toString());
startActivity(in);
Log.d("USERKEY",dataUser.child("userKey").getValue().toString());
}
else{
startActivity(new Intent(katiRoll.this, welcome.class));
}
}
}
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if(mAuthListener !=null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.akshay.katiroll.SecondScreen.welcome;
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.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.akshay.katiroll.R;
import com.google.firebase.database.ValueEventListener;
import java.util.Iterator;
public class signUp extends AppCompatActivity {
EditText nUser, nPass;
Button registerBtn, backToMain;
ImageButton passVis;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference mDatabaseRef, mUserCheckData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
nUser = (EditText) findViewById(R.id.nUser);
nPass = (EditText) findViewById(R.id.nPass);
registerBtn = (Button) findViewById(R.id.registerBtn);
backToMain = (Button) findViewById(R.id.backToMain);
passVis = (ImageButton)findViewById(R.id.passVis);
passVis.setImageResource(R.drawable.open);
passVis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Drawable drawable = passVis.getDrawable();
if(drawable.getConstantState().equals(getResources().getDrawable(R.drawable.open,null).getConstantState())){
passVis.setImageResource(R.drawable.closed);
nPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
}else{
passVis.setImageResource(R.drawable.open);
nPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD);
}
}
});
float Re = 255;
float Gr = 148;
float Bl = 0;
nUser.setTextColor(Color.rgb(Re, Gr, Bl));
nPass.setTextColor(Color.rgb(Re, Gr, Bl));
registerBtn.setTextColor(Color.rgb(Re, Gr, Bl));
backToMain.setTextColor(Color.rgb(Re, Gr, Bl));
mAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
mUserCheckData = FirebaseDatabase.getInstance().getReference().child("User");
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
final String emailForVer = user.getEmail();
mUserCheckData.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkForValidation(dataSnapshot, emailForVer);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Log.d("TAG", "onAuthStateChanged:signed_out");
}
}
};
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String nUserString, nPassString;
nUserString = (nUser.getText().toString().trim());
nPassString = (nPass.getText().toString().trim());
if(nPassString.length()>=6){
if (!TextUtils.isEmpty(nUserString) && !TextUtils.isEmpty(nPassString)) {
mAuth.createUserWithEmailAndPassword(nUserString, nPassString).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
DatabaseReference mChildDatabase = mDatabaseRef.child("Users").push();
String key_user = mChildDatabase.getKey();
mChildDatabase.child("isVerified").setValue("unverified");
mChildDatabase.child("userKey").setValue(key_user);
mChildDatabase.child("EmailUser").setValue(nUserString);
mChildDatabase.child("PasswordUser").setValue(nPassString);
Toast.makeText(signUp.this, "User Account Created, Check Email For Confirmation", Toast.LENGTH_LONG).show();
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
user.sendEmailVerification();
}
startActivity(new Intent(signUp.this, Profile.class));
} else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
backToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(signUp.this, katiRoll.class));
}
});
}
private void checkForValidation(DataSnapshot dataSnapshot, String emailForVer) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext())
{
DataSnapshot dataUser = (DataSnapshot)iterator.next();
if (dataUser.child("emailUser").getValue().toString().equals(emailForVer)){
if(dataUser.child("isVerified").getValue().toString().equals("unverified"))
{
Intent in = new Intent(signUp.this, Profile.class);
in.putExtra("USER KEY", dataUser.child("userKey").getValue().toString());
startActivity(in);
Log.d("USERKEY",dataUser.child("userKey").getValue().toString());
}
else{
startActivity(new Intent(signUp.this, welcome.class));
}
}
}
}
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if(mAuthListener !=null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
package com.example.akshay.katiroll.SecondScreen;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.akshay.katiroll.FirstScreen.katiRoll;
import com.example.akshay.katiroll.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class welcome extends AppCompatActivity {
Button logOutBtn;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
float Re = 255;
float Gr = 148;
float Bl = 0;
logOutBtn = (Button)findViewById(R.id.logOutBtn);
logOutBtn.setTextColor(Color.rgb(Re,Gr,Bl));
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user !=null) {
}else{
}
}
};
logOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAuth.signOut();
finish();
startActivity(new Intent(welcome.this, katiRoll.class));
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(mAuthListener);
}
}
The problem that is telling to you is that you are doing wrong the reference, you are trying to get something inside Firebase Database that is not there
This line is telling you that the child("Users").child(KeyUser); does not exist in your current DB structure
To fix this you should see your databse structure and then redo your reference.
if you post a photo of your Firebase DB i will be glad to refactor your code to your needs.
also here you are getting wrong your USER_KEY
keyUser = getIntent().getStringExtra("USER_KEY");
To fix this a short way would be doing this
keyUser = getIntent().getExtras().getString("USER_KEY");
you are geting an intent from where? if you are trying to get a putExtra from another Activity, you are doing it wrong, post where you are seting the extra ("USER_KEY");
Intent.getStringExtra() and Intent.getExtras() returns null if there are no extras, so you need to check for that before trying to call getString()
one quick example to check for extras first would be this
String keyUser;
Bundle extras = getIntent().getExtras();
if(extras == null) {
Log.e("keyUser is null","");
} else {
keyUser= extras.getString("USER_KEY");
}
happy coding