Firebase not uploading files to Storage Bucket - java

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

Related

App crashes whenever I log out, authentication with firebase

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

Firebase chat app not displaying messages like whatsapp does

I am trying to come up with a chat app using Firebase Recycler adapter. The problem is that the sender's and receiver's chats are not displayed as expected. All the chats are displayed on the right. Despite the text being "Morning", the text is displayed as "Hello".
Below is my code
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import ultramodern.activity.besha.Adapter.MessageAdapter;
import ultramodern.activity.besha.Model.Chat;
import ultramodern.activity.besha.Model.Users;
public class Complete_new_Group extends AppCompatActivity implements View.OnClickListener{
Button fab,paybtn, depobtn, borrowbtn, borrowicon, depoicon, payicon;
CircleImageView sendtextbutton;
EditText text_send;
RecyclerView chatrecyclerView;
MessageAdapter messageAdapter;
public static final int MESSAGE_RIGHT=0;
public static final int MESSAGE_LEFT=1;
//private String user_id;
#Override
protected void onCreate(Bundle savedInstanceState) { ;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete_new__group);
Toast.makeText(this, "This area is still under development", Toast.LENGTH_LONG).show();
fab = findViewById(R.id.fab_complete_group);
paybtn = findViewById(R.id.button6);
depobtn = findViewById(R.id.button5);
borrowbtn = findViewById(R.id.button3);
borrowicon = findViewById(R.id.button8);
depoicon = findViewById(R.id.button9);
payicon = findViewById(R.id.button10);
sendtextbutton = findViewById(R.id.sendtextButton);
text_send = findViewById(R.id.text_send);
chatrecyclerView = findViewById(R.id.chatrecycler);
chatrecyclerView.setLayoutManager(new LinearLayoutManager(this));
fab.setOnClickListener(this);
paybtn.setOnClickListener(this);
depobtn.setOnClickListener(this);
borrowbtn.setOnClickListener(this);
borrowicon.setOnClickListener(this);
depoicon.setOnClickListener(this);
payicon.setOnClickListener(this);
sendtextbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = text_send.getText().toString();
if (!message.equals("")){
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String userId = getIntent().getStringExtra("userId");
sendmessage(message,userId,firebaseUser.getUid());
}
else {
Toast.makeText(Complete_new_Group.this, "You can't send an empty message", Toast.LENGTH_SHORT).show();
}
text_send.setText("");
}
});
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final String user_id;
Intent intent = getIntent();
user_id = intent.getStringExtra("userId");
assert user_id != null;
// Log.d("TRACK",user_id);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Users users = snapshot.getValue(Users.class);
readMessage(firebaseUser.getUid(),user_id,users.getImageURL());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onClick(View view) {
if (view==fab){
paybtn.setVisibility(View.VISIBLE);
depobtn.setVisibility(View.VISIBLE);
borrowbtn.setVisibility(View.VISIBLE);
borrowicon.setVisibility(View.VISIBLE);
depoicon.setVisibility(View.VISIBLE);
payicon.setVisibility(View.VISIBLE);
}
if (view==paybtn){
Intent intent = new Intent(getApplicationContext(),Group_pay.class);
startActivity(intent);
}
if (view==payicon){
Intent intent = new Intent(getApplicationContext(),Group_pay_icon_activity.class);
startActivity(intent);
}
if (view==depobtn){
Intent intent = new Intent(getApplicationContext(),Group_deposit_button_activity.class);
startActivity(intent);
}
if (view==depoicon){
Intent intent = new Intent(getApplicationContext(),Group_depo_icon_activity.class);
startActivity(intent);
}
if (view==borrowbtn){
Intent intent = new Intent(getApplicationContext(),Group_deposit_button_activity.class);
startActivity(intent);
}
if (view==borrowicon){
Intent intent = new Intent(getApplicationContext(),Group_borrow_icon_activity.class);
startActivity(intent);
}
if (view==sendtextbutton){
}
}
private void sendmessage(String message,String sender, String reciever){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
HashMap<String,Object> hashMap = new HashMap<>();
hashMap.put("sender",sender);
hashMap.put("reciever",reciever);
hashMap.put("message",message);
reference.child("Chats").push().setValue(hashMap);
}
private void readMessage(final String myId, final String userId, String imageURL){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Chats");
FirebaseRecyclerOptions<Chat> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Chat>().setQuery(databaseReference, new SnapshotParser<Chat>() {
#NonNull
#Override
public Chat parseSnapshot(#NonNull DataSnapshot snapshot) {
String message = String.valueOf(snapshot.child("message").getValue());
String sender = String.valueOf(snapshot.child("sender").getValue());
String receiver = String.valueOf(snapshot.child("reciever").getValue());
return new Chat(message,sender,receiver);
}
}).build();
final FirebaseRecyclerAdapter<Chat,ViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Chat,ViewHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull final ViewHolder viewHolder, int i, #NonNull Chat chat) {
if (chat.getReceiver().equals(userId) && chat.getSender().equals(myId) || chat.getReceiver()
.equals(myId) && chat.getSender().equals(userId)){
viewHolder.showMessage.setText(chat.getMessage());
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MESSAGE_RIGHT){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item_right,parent,false);
return new ViewHolder(view);
}
else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item_left,parent,false);
return new ViewHolder(view);
}
}
#Override
public int getItemViewType(int position) {
Chat chat = getItem(position);
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (chat.getSender().equals(firebaseUser.getUid())){
return MESSAGE_LEFT;
}
else {
return MESSAGE_RIGHT;
}
//return super.getItemViewType(position);
}
};
chatrecyclerView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView showMessage;
public ImageView profilepic;
public ViewHolder(#NonNull View itemView) {
super(itemView);
showMessage=itemView.findViewById(R.id.showMessage);
profilepic=itemView.findViewById(R.id.profilepic);
}
public void setText(String paramString){
this.showMessage.setText(paramString);
}
}
}
This is the output on both the sender and the receiver
I need some assistance

Upload Image to Firebase - Java

i try to upload an image, unfortunately when i try to click button continue to upload it, the apk always crash, here's the log
It says childName cannot be null or empty
the java
package com.example.firstapplication;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
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.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 com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class Register_two extends AppCompatActivity {
LinearLayout btn_back;
Button btn_continue, btn_upload_photo;
ImageView prof_pic;
EditText bio, nama_lengkap;
Uri photo_location;
Integer photo_max = 1;
DatabaseReference reference;
StorageReference storage;
String USERNAME_KEY = "usernamekey";
String username_key = "";
String username_key_new = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_two);
getUsernameLocal();
btn_continue = findViewById(R.id.btn_continue);
btn_back = findViewById(R.id.btn_back);
btn_upload_photo = findViewById(R.id.btn_upload_photo);
prof_pic = findViewById(R.id.prof_pic);
btn_upload_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
findPhoto();
}
});
btn_continue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//ubah state menjadi loading...
btn_continue.setEnabled(false);
btn_continue.setText("Loading...");
//menyimpan ke Firebase
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(username_key_new);
storage = FirebaseStorage.getInstance().getReference().child("Photousers").child(username_key_new);
//validasi untuk file (apakah ada?)
if (photo_location != null){
final StorageReference storageReference1 =
storage.child(System.currentTimeMillis() + "." +
getFileExtention(photo_location));
storageReference1.putFile(photo_location)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageReference1.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String uri_photo = uri.toString();
reference.getRef().child("url_photo_profile").setValue(uri_photo);
reference.getRef().child("nama_lengkap").setValue(nama_lengkap.getText().toString());
reference.getRef().child("bio").setValue(bio.getText().toString());
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
//pindah activity
Intent btncontinue = new Intent(Register_two.this,SuccessRegister.class);
startActivity(btncontinue);
}
});
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
//pindah activity
// Intent btncontinue = new Intent(Register_two.this,SuccessRegister.class);
// startActivity(btncontinue);
}
});
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goback = new Intent(Register_two.this,Register_one.class);
startActivity(goback);
}
});
}
String getFileExtention(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
public void findPhoto(){
Intent pic = new Intent();
pic.setType("image/*");
pic.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(pic, photo_max);
}
#Override
public void onActivityResult (int requestCode, int resultCode, #Nullable Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == photo_max && resultCode == RESULT_OK && data != null && data.getData() != null)
{
photo_location = data.getData();
Picasso.with(this).load(photo_location).centerCrop().fit().into(prof_pic);
}
}
public void getUsernameLocal(){
SharedPreferences sharedPreferences = getSharedPreferences(USERNAME_KEY, MODE_PRIVATE);
username_key_new = sharedPreferences.getString(username_key,"");
}
}
the error said, i'm passing null into a childin the line 81
storage = FirebaseStorage.getInstance().getReference().child("Photousers").child(username_key_new);
but i dont know what is wrong
Have you ever try this?
And I suggest to make a return string instead making a void method
//Please check what is the identifier of the string in sharedpreferences
//if usernamekey is the identifier then getString("usernamekey","");
public String getUsernameLocal(){
SharedPreferences sharedPreferences = getSharedPreferences(USERNAME_KEY, MODE_PRIVATE);
String userKey= sharedPreferences.getString(USERNAME_KEY,"");
return userKey;
}
And your reference
storage = FirebaseStorage.getInstance().getReference().child("Photousers").child(getUsernameLocal());

Activity opening itself [closed]

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.

Getting "java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()" in Firebase

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

Categories