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.
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 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());
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.
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
While using android studio and firebase, my app (in the background or foreground) crashes on an API 26 device when notification is clicked. Whereas when I use an API 23 device, the app crashes when the app is closed and notification is clicked but can still process the notification when app is in the background/foreground. I don't understand the problem and any help is appreciated.
NOTIFICATION SERVICE
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.RemoteMessage;
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
String from_user_id = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(FirebaseMessagingService.this, "default")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notification_title)
.setContentText(notification_message);
Intent resultIntent = new Intent(click_action);
resultIntent.putExtra("user_id", from_user_id);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
FirebaseMessagingService.this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
USERS ACTIVITY
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class UsersActivity extends AppCompatActivity {
private Toolbar mToolbar;
private RecyclerView mUsersList;
private DatabaseReference mUsersDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
mToolbar=(Toolbar)findViewById(R.id.users_appBar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("All Users");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mUsersDatabase= FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mUsersList=(RecyclerView)findViewById(R.id.users_list);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
startListening();
}
public void startListening(){
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Users")
.limitToLast(50);
FirebaseRecyclerOptions<Users> options =
new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(query, Users.class)
.build();
FirebaseRecyclerAdapter<Users, UserViewHolder> adapter = new FirebaseRecyclerAdapter<Users, UserViewHolder>(options) {
#Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.users_single_layout, parent, false);
return new UserViewHolder(view);
}
#Override
protected void onBindViewHolder(UserViewHolder holder, int position, Users model) {
// Bind the Chat object to the ChatHolder
holder.setName(model.name);
holder.setStatus(model.status);
holder.setUserImage(model.getThumb_image());
final String user_id= getRef(position).getKey();
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(UsersActivity.this, ProfileActivity.class);
if (user_id != null) {
profileIntent.putExtra("user_id", user_id);
startActivity(profileIntent);
}
}
});
}
};
mUsersList.setAdapter(adapter);
adapter.startListening();
}
public static class UserViewHolder extends RecyclerView.ViewHolder {
View mView;
public UserViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setStatus(String status){
TextView userStatusView= (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(status);
}
public void setUserImage(String thumb_image){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.get().load(thumb_image).placeholder(R.drawable.accountpicture).into(userImageView);
}
}
}
PROFILE ACTIVITY
import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
public class ProfileActivity extends AppCompatActivity {
private ImageView mProfileImage;
private TextView mProfileName, mProfileStatus, mProfileFriendsCount;
private Button mProfileSendReqBtn;
private DatabaseReference mUserDatabase;
private Button declineRequest;
private FirebaseUser mCurrent_user;
private ProgressDialog mProgressDialog;
private DatabaseReference mFriendRequestDatabase;
private DatabaseReference mFriendDatabase;
private String mCurrent_state;
private DatabaseReference mNotificationDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final String user_id = getIntent().getStringExtra("user_id");
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
mFriendRequestDatabase = FirebaseDatabase.getInstance().getReference().child("Friend_req");
mCurrent_user= FirebaseAuth.getInstance().getCurrentUser();
mFriendDatabase= FirebaseDatabase.getInstance().getReference().child("Friends");
mNotificationDatabase= FirebaseDatabase.getInstance().getReference().child("notifications");
mProfileImage = (ImageView) findViewById(R.id.profile_image);
mProfileName = (TextView) findViewById(R.id.profile_profileName);
mProfileStatus = (TextView) findViewById(R.id.profile_status);
mProfileFriendsCount = (TextView) findViewById(R.id.profile_totalFriends);
mProfileSendReqBtn = (Button) findViewById(R.id.profile_send_req_btn);
declineRequest= (Button)findViewById(R.id.profile_decline_btn);
mCurrent_state = "not_friends";
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("Loading User Data");
mProgressDialog.setMessage("Please wait...");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
declineRequest.setVisibility(View.INVISIBLE);
if(mCurrent_user.getUid().equals(user_id)){
mProfileSendReqBtn.setVisibility(View.INVISIBLE);
}
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String diplay_name = dataSnapshot.child("name").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
final String image = dataSnapshot.child("image").getValue().toString();
mProfileName.setText(diplay_name);
mProfileStatus.setText(status);
Picasso.get().load(image).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.accountpicture).into(mProfileImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(image).placeholder(R.drawable.accountpicture).into(mProfileImage);
}
});
mFriendRequestDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
String req_type= dataSnapshot.child(user_id).child("request_type").getValue().toString();
if(req_type.equals("received")){
mCurrent_state= "req_received";
mProfileSendReqBtn.setText("Accept Friend Request");
declineRequest.setVisibility(View.VISIBLE);
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
else if(req_type.equals("sent")){
mCurrent_state="req_sent";
mProfileSendReqBtn.setText("Cancel Friend Request");
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
else if(req_type.equals("req_sent")){
mCurrent_state= "not_friends";
mProfileSendReqBtn.setText("Send Friend Request");
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
mProgressDialog.dismiss();
}
else{
mFriendDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
mCurrent_state= "friends";
mProfileSendReqBtn.setText("Unfriend User");
mProfileSendReqBtn.setEnabled(true);
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
mProgressDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
mProgressDialog.dismiss();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mProfileSendReqBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProfileSendReqBtn.setEnabled(false);
if (user_id.equals(mCurrent_user.getUid())) {
Toast.makeText(ProfileActivity.this, "Cannot send friend request to yourself!", Toast.LENGTH_LONG).show();
declineRequest.setVisibility(View.INVISIBLE);
} else {
if (mCurrent_state.equals("not_friends")) {
mFriendRequestDatabase.child(mCurrent_user.getUid()).child(user_id).child("request_type").setValue("sent").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mFriendRequestDatabase.child(user_id).child(mCurrent_user.getUid()).child("request_type").setValue("received").addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
HashMap<String, String> notificationData= new HashMap<>();
notificationData.put("from", mCurrent_user.getUid());
notificationData.put("type", "request");
mNotificationDatabase.child(user_id).push().setValue(notificationData).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mCurrent_state = "req_sent";
mProfileSendReqBtn.setText("Cancel Friend Request");
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
});
}
});
} else {
Toast.makeText(ProfileActivity.this, "Error", Toast.LENGTH_LONG).show();
}
mProfileSendReqBtn.setEnabled(true);
}
});
}
if (mCurrent_state.equals("req_sent")) {
mProfileSendReqBtn.setEnabled(true);
mFriendRequestDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendRequestDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mCurrent_state = "req_sent";
mProfileSendReqBtn.setText("Send Friend Request");
mCurrent_state = "not_friends";
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
});
}
});
}
if (mCurrent_state.equals("req_received")) {
declineRequest.setVisibility(View.INVISIBLE);
mProfileSendReqBtn.setEnabled(true);
final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
mFriendDatabase.child(mCurrent_user.getUid()).child(user_id).setValue(currentDate).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendDatabase.child(user_id).child(mCurrent_user.getUid()).setValue(currentDate).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendRequestDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendRequestDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mCurrent_state = "friends";
mProfileSendReqBtn.setText("Unfriend User");
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
});
}
});
}
});
}
});
}
}
}
});
declineRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
declineRequest.setVisibility(View.INVISIBLE);
mFriendRequestDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendRequestDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mCurrent_state= "not_friends";
mProfileSendReqBtn.setText("Send Friend Request");
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
});
}
});
}
});
}
}
INDEX.JS FILE
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
/*
* 'OnWrite' works as 'addValueEventListener' for android. It will fire the function
* everytime there is some item added, removed or changed from the provided 'database.ref'
* 'sendNotification' is the name of the function, which can be changed according to
* your requirement
*/
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
/*
* You can store values as variables from the 'database.ref'
* Just like here, I've done for 'user_id' and 'notification'
*/
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification from : ', user_id);
/*
* Stops proceeding to the rest of the function if the entry is deleted from database.
* If you want to work with what should happen when an entry is deleted, you can replace the
* line from "return console.log.... "
*/
if(!change.after.val()){
return console.log('A Notification has been deleted from the database : ', notification_id);
}
/*
* 'fromUser' query retreives the ID of the user who sent the notification
*/
const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
console.log('You have new notification from : ', from_user_id);
/*
* The we run two queries at a time using Firebase 'Promise'.
* One to get the name of the user who sent the notification
* another one to get the devicetoken to the device we want to send notification to
*/
const userQuery = admin.database().ref(`Users/${from_user_id}/name`).once('value');
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
return Promise.all([userQuery, deviceToken]).then(result => {
const userName = result[0].val();
const token_id = result[1].val();
/*
* We are creating a 'payload' to create a notification to be sent.
*/
const payload = {
notification: {
title : "New Friend Request",
body: `${userName} has sent you a request`,
icon: "default",
click_action : "com.example.****.chattingapp_TARGET_NOTIFICATION"
},
data : {
from_user_id : from_user_id
}
};
/*
* Then using admin.messaging() we are sending the payload notification to the token_id of
* the device we retreived.
*/
return admin.messaging().sendToDevice(token_id, payload).then(response => {
return console.log('This was the notification Feature');
});
});
});
});
ERROR I GET
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.****.chattingapp, PID: *****
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.****.chattingapp/com.example.****.chattingapp.ProfileActivity}: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.example.****.chattingapp.ProfileActivity.onCreate(ProfileActivity.java:53)
DATABASE VALUES
You removed most of the important rows of the Error.
However you have to look at it very well and even decode it. It was saying that: there is a problem on "ProfileActivity.onCreate()" method when it calls a "Firebase.....child()" method. There are few rows where you call a "child()" method using a Variable (and not a fixed String), so one of them (please check the Error Log and find the line of that "child()" warning) is the real problem.
So I figured out I needed
final String user_id;
String data = getIntent().getStringExtra("user_id");
if (data == null) {
user_id = getIntent().getStringExtra("from_user_id");
} else {
user_id = getIntent().getStringExtra("user_id");
}
I wasn't check what string I was getting from my intents, hence the null exceptions.