Unable to obtain user profile image from Firebase Storage - firebase

I'm currently working on a settings page for my app and have been trying to obtain the user profile image from the firebase storage. I am able to upload the picture from the storage.
However, the app does not produce the image onto the activity itself. Is there something wrong with my code?
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/main_chat_toolbar"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</androidx.appcompat.widget.Toolbar>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_image"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="85dp"
app:civ_border_color="#color/colorPrimary"
android:src="#drawable/pikachu"
app:civ_border_width="2dp" />
<EditText
android:id="#+id/setting_username"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#id/profile_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:drawableLeft="#drawable/ic_action_name"
android:hint="Username"
android:inputType="textMultiLine" />
<EditText
android:id="#+id/set_profile_status"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/setting_username"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:drawableLeft="#drawable/ic_user_status"
android:hint="Hey, I'm available now!"
android:inputType="textMultiLine" />
<Button
android:id="#+id/setting_updatebtn"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#id/set_profile_status"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="#drawable/btn_rect"
android:text="Update Settings" />
</RelativeLayout>
Java
package com.shiminu1521462c.fyp_2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
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.io.File;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingActivity extends AppCompatActivity {
private EditText etUsername, etUserStatus;
private Button changeSettings;
private CircleImageView userProfileImage;
private Toolbar mToolbar;
private String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImageRef;
private ProgressDialog LoadingBar;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mToolbar = (Toolbar) findViewById(R.id.main_chat_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Settings");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
etUsername.setVisibility(View.INVISIBLE);
changeSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.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, GalleryPick);
}
});
}
private void InitializeFields() {
changeSettings = (Button) findViewById(R.id.setting_updatebtn);
etUsername = (EditText) findViewById(R.id.setting_username);
etUserStatus = (EditText) findViewById(R.id.set_profile_status);
userProfileImage = (CircleImageView) findViewById(R.id.profile_image);
LoadingBar = new ProgressDialog(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null) {
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
LoadingBar.setTitle("Set Profile Image");
LoadingBar.setMessage("Please wait while your profile image is uploading...");
LoadingBar.setCanceledOnTouchOutside(false);
LoadingBar.show();
final Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Toast.makeText(SettingActivity.this, "Profile Image Uploaded Successfully!", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(SettingActivity.this, "Image saved in Database successfully!", Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}else{
String message = task.getException().toString();
Toast.makeText(SettingActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
} else {
String message = task.getException().toString();
Toast.makeText(SettingActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
}
}
}
private void UpdateSettings() {
String setUsername = etUsername.getText().toString();
String setStatus = etUserStatus.getText().toString();
if (TextUtils.isEmpty(setUsername)) {
Toast.makeText(this, "Please enter your username..", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus)){
Toast.makeText(this, "Please set a status..", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUsername);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserID).updateChildren(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
sendUserToDashboardActivity();
Toast.makeText(SettingActivity.this, "Profile updated successfully!", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().toString();
Toast.makeText(SettingActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists())
&& (dataSnapshot.hasChild("name")
&& (dataSnapshot.hasChild("image")))) {
String retrieveUsername = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
etUsername.setText(retrieveUsername);
etUserStatus.setText(retrieveStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
} else if ((dataSnapshot.exists())
&& (dataSnapshot.hasChild("name"))) {
String retrieveUsername = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
etUsername.setText(retrieveUsername);
etUserStatus.setText(retrieveStatus);
} else {
etUsername.setVisibility(View.VISIBLE);
Toast.makeText(SettingActivity.this, "Please set and update profile information..", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendUserToDashboardActivity() {
Intent mainIntent = new Intent(SettingActivity.this, DashboardActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent myIntent = new Intent(getApplicationContext(), DashboardActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
}
Thank you.

Why not load the image using the resultUri?
Uri resultUri = result.getUri();
Glide.with(this).load(new File(resultUri.getPath())).into(imageView);
Do that after image upload is successful.

have you added the internet permission in the manifest file?
<uses-permission android:name="android.permission.INTERNET" />

I finally managed to solve my issue! This is the altered code, hopefully it helps others who need it! :)
final Uri resultUri = result.getUri();
final StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
RootRef.child("Users").child(currentUserID).child("image").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SettingActivity.this, "Profile image stored to firebase database successfully.", Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
} else {
String message = task.getException().getMessage();
Toast.makeText(SettingActivity.this, "Error Occurred..." + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
}
});
}

Related

'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference androidx

could you help me, before my code worked well, after the splash I would have my form and I would start the session without any problem, but now I don't know what it was that I got this error ... I already tried several solutions from other forums and no I get to fix it.
it literally tells me what the uid is but I don't know how to make it not null
package com.example.medicare;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import com.example.medicare.modelo.Cita;
import com.google.android.gms.tasks.OnSuccessListener;
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.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.text.DateFormat;
import java.util.Calendar;
import cn.pedant.SweetAlert.SweetAlertDialog;
import de.hdodenhof.circleimageview.CircleImageView;
public class MenuActivity extends AppCompatActivity {
TextView nombreC, nss;
CircleImageView imagenPerfil;
SharedPreferences sp;
DatabaseReference dbdReferencia;
FirebaseUser usuario;
String uid;
NotificationCompat.Builder builder;
String pacienteNombreC, pacienteNss, fechaHoy;
int numeroCitas;
static int token = 0;
String[] numeros = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
public static void setToken(int number)
{
token = number;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
numeroCitas = 0;
sp = getSharedPreferences("Iniciar Sesion", MODE_PRIVATE);
usuario = FirebaseAuth.getInstance().getCurrentUser();
nombreC = findViewById(R.id.nombreCompleto);
nss = findViewById(R.id.nss);
imagenPerfil = findViewById(R.id.imagen_perfil);
uid = usuario.getUid();
Calendar c = Calendar.getInstance();
fechaHoy = DateFormat.getDateInstance(DateFormat.SHORT).format(c.getTime());
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Citas");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Cita cita = data.getValue(Cita.class);
if (cita.getEmailPaciente().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail()) &&
cita.getestado().equals("Aceptado") &&
cita.getfecha().equals(fechaHoy)
)
numeroCitas++;
}
if (numeroCitas == 1) {
builder = new NotificationCompat.Builder(com.example.medicare.MenuActivity.this)
.setSmallIcon(R.drawable.ic_heart_beats)
.setContentTitle("Cita diaria")
.setContentText("Usted tiene una cita el dia de hoy")
.setAutoCancel(true)
.setColor(Color.parseColor("#33AEB6"))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH);
}
if (numeroCitas > 1) {
builder = new NotificationCompat.Builder(com.example.medicare.MenuActivity.this)
.setSmallIcon(R.drawable.ic_heart_beats)
.setContentTitle("Citas diarias")
.setContentText("Usted tiene " + numeros[numeroCitas - 1] + " citas el dia de hoy")
.setAutoCancel(true)
.setColor(Color.parseColor("#33AEB6"))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH);
}
if (numeroCitas == 0) {
builder = new NotificationCompat.Builder(com.example.medicare.MenuActivity.this)
.setSmallIcon(R.drawable.ic_heart_beats)
.setContentTitle("Citas diarias")
.setContentText("Usted no tiene citas el dia de hoy")
.setAutoCancel(true)
.setColor(Color.parseColor("#33AEB6"))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH);
}
if(token == 0) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, AsignarCitaActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(com.example.medicare.MenuActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE
);
notificationManager.notify(0, builder.build());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
dbdReferencia = FirebaseDatabase.getInstance().getReference("Pacientes");
dbdReferencia.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//pacienteNombreC = dataSnapshot.child(uid).child("apellidos").getValue(String.class) + " " + dataSnapshot.child(uid).child("nombreC").getValue(String.class);
pacienteNombreC = dataSnapshot.child(uid).child("nombreC").getValue(String.class);
pacienteNss = dataSnapshot.child(uid).child("nss").getValue(String.class);
nombreC.setText(pacienteNombreC);
nss.setText(pacienteNss);
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference profileRef = storageReference.child("imagen_perfil").child(FirebaseAuth.getInstance().getCurrentUser().getEmail() + ".jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(imagenPerfil);
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void buscarDoctor(View view) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, BuscarDoctorEspecialidadActivity.class);
startActivity(intent);
}
public void Citas(View view) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, AsignarCitaActivity.class);
startActivity(intent);
}
public void perfilInfo(View view) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, PerfilPacienteInfo.class);
startActivity(intent);
}
public void abrirExpedienteMedico(View view) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, ExpedienteMedico.class);
startActivity(intent);
}
public void cerrarSesion(View view) {
sp.edit().putBoolean("Sesion cerrada", false).apply();
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(com.example.medicare.MenuActivity.this, MainActivity.class));
}
#Override
public void onBackPressed() {
SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
dialog.setConfirmText("Si");
dialog.setCancelText("No");
dialog.setContentText("Estas seguro que deseas salir de edicare ?");
dialog.setTitleText("Cerrar Aplicacion");
dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
finishAffinity();
System.exit(0);
}
});
dialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
}
});
dialog.show();
}
public void myDoctors(View view) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, MisDoctoresActivity.class);
startActivity(intent);
}
}

Image Uploading to firebase successfully but not showing in phone

I am trying to build a messenger type app. And for this, I have uploaded an image from my phone to firebase. And the image is successfully stored in firebase storage. And I am trying to show the image on my phone. And I use Picasso to retrieve the image from firebase. But my picture isn't showing. But when I add placeholder I can see the default image that is set by a placeholder. How can I solve this problem? My code is given below:
package com.example.whatsapp2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
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.Task;
import com.google.firebase.FirebaseApp;
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.io.IOException;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Button UpdateAccountSetting;
private EditText userName, userStatus;
private CircleImageView userProfileImage;
private String currentUserId;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
private Toolbar SettingsToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
FirebaseApp.initializeApp(this);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.INVISIBLE);
UpdateAccountSetting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.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,GalleryPick);
}
});
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")) && (dataSnapshot.hasChild("image"))){
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
//Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profile_image).resize(100,100).centerCrop().into(userProfileImage);
}
else if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
}
else {
userName.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),"Please set & update your profile information...",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if (TextUtils.isEmpty(setUserName)) {
Toast.makeText(this,"Please write your user name first....",Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus)) {
Toast.makeText(this,"Please write your status....",Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("uid", currentUserId);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserId).updateChildren(profileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(getApplicationContext(),"Profile Updated Successfully...",Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error : "+message,Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void InitializeFields() {
UpdateAccountSetting = findViewById(R.id.update_settings_button);
userName = findViewById(R.id.set_user_name);
userStatus =findViewById(R.id.set_profile_status);
userProfileImage = findViewById(R.id.set_profile_image);
loadingBar = new ProgressDialog(this);
SettingsToolbar = findViewById(R.id.settings_toolbar);
setSupportActionBar(SettingsToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setTitle("Account Settings");
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GalleryPick && resultCode == RESULT_OK && data != null){
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
//userProfileImage.setImageURI(ImageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Please wait, your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImagesRef.child(currentUserId+".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Profile Image uploaded Successfully...",Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserId).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Image save in Database Successfully...",Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else{
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else{
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
}
You can resolve this issue by simply adding 1 line of code:
//in this block
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null ) {
Uri ImageUri = data.getData();
userProfileImage.setImageURI(ImageUri); //add this line

Android: RecyclerView: No adapter attached; skipping layout. I am having trouble retrieving data from firebase and displaying it.

I really don't know where I am going wrong. According to the documentation I am doing everything right. I am doubtful if it's happening just because I am using TabbedActivity and dealing with fragments, but still I don't know how it's wrong.
Please look into the code and help me out. I have been struggling a lot to achieve this task of retrieving and displaying data from FIREBASE.
And being a beginner in this, it's quite hard for me to figure it out.
MainActivity.Java
package com.example.souravkumar.sqaurewallpapers;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
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;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
int count=0;
public FloatingActionButton mAddImage;
private StorageReference mStorage;
public DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
String stringUri;
Long date;
private static final int GALLERY_INTENT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mStorage = FirebaseStorage.getInstance().getReference();
mAddImage = (FloatingActionButton) findViewById(R.id.addImage);
mAddImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
Uri uri = data.getData();
StorageReference filePath = mStorage.child("Wallpapers").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_LONG).show();
Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Adding image to the database
stringUri= downloadUrl.toString();
date = System.currentTimeMillis();
addImageToDatabase (stringUri, date);
}
});
}
}
private void addImageToDatabase(String downloadUrl, Long date){
image_details id= new image_details(downloadUrl, date);
String key = mDatabase.push().getKey();
mDatabase.child(key).child("URL").setValue(id.getUrl());
mDatabase.child(key).child("Date").setValue(id.getDate());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
GridView gridView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
View rootView = inflater.inflate(R.layout.fragment_popular, container, false);
return rootView;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
View rootView = inflater.inflate(R.layout.fragment_recent, container, false);
return rootView;
} else
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "POPULAR";
case 1:
return "RECENT";
case 2:
return "PROFILES";
}
return null;
}
}
}
Popular.Java
package com.example.souravkumar.sqaurewallpapers;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
/**
* Created by Sourav Kumar on 11/3/2017.
*/
public class popular extends FragmentActivity {
private RecyclerView recyclerView;
private DatabaseReference myRef;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myRef = FirebaseDatabase.getInstance().getReference();
FirebaseRecyclerAdapter<image_details,BlogViewHolder> recyclerAdapter=new FirebaseRecyclerAdapter<image_details,BlogViewHolder>(
image_details.class,
R.layout.individual_row,
BlogViewHolder.class,
myRef
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, image_details model, int position) {
viewHolder.setUrl(model.getUrl());
viewHolder.setDate(model.getDate());
}
};
recyclerView.setAdapter(recyclerAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
TextView textView;
ImageView imageView;
public BlogViewHolder(View itemView) {
super(itemView);
mView=itemView;
textView = (TextView)itemView.findViewById(R.id.date);
imageView = (ImageView)itemView.findViewById(R.id.imageView);
}
public void setDate(Long date) {
textView.setText(date.toString());
}
public void setUrl(String url) {
Picasso.with(mView.getContext())
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView);
}
}
}
image_details.Java
package com.example.souravkumar.sqaurewallpapers;
/**
* Created by Sourav Kumar on 10/29/2017.
*/
public class image_details {
String url;
Long date;
image_details(){}
public image_details(String url, Long date){
this.url = url;
this.date = date;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
}
fragment_popular.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.souravkumar.sqaurewallpapers.popular">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerView">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
individual_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="150dp"
android:layout_height="280dp"
android:id="#+id/imageView"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date"
android:id="#+id/date"/>
</LinearLayout>
</android.support.v7.widget.CardView>

Custom Simplecursoradapter doesn't populate Listview

SimpleCustomAdapter worked and populated my ListView, but then I wanted to implement a delete ImageButton within the ListView. To achieve that I had to make a custom adapter. Now it doesn't show data in ListView.
This is my MainActivity.java where I put the MyListAdapter class too (at the bottom). I am a beginner so I am aware that code might be all over the place. MainAcitivty has call for adapter, a setonclicklistener for listview which also sends id of item in sharedpreferences so I can catch it in deleteNotes within adapter. Also, delete button works perfectly fine and I can delete notes, but the only problem is that Title and Date dont show in ListView, whereas before they did. Thanks
package com.example.android.notepad2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.Image;
import android.preference.PreferenceManager;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import static com.example.android.notepad2.R.id.parent;
import static com.example.android.notepad2.R.layout.listtemplate;
public class MainActivity extends AppCompatActivity {
NDb mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new NDb(this);
ListView listview;
// listview
listview = (ListView) findViewById(R.id.listview);
String[] array = new String[] {mydb.name, mydb.date};
int[] display = new int[] {R.id.title, R.id.date};
Cursor c = mydb.fetchAll();
MyListAdapter adapter = new MyListAdapter(this, listtemplate, c, array, display, 0);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", (int)l);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("ajdi", (int)l);
editor.apply();
Intent intent = new Intent(MainActivity.this, NoteDisplay.class);
intent.putExtras(dataBundle);
MainActivity.this.startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_note:
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(MainActivity.this,NoteDisplay.class);
intent.putExtras(dataBundle);
MainActivity.this.startActivity(intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public class MyListAdapter extends SimpleCursorAdapter{
private LayoutInflater mInflater;
private Context context;
private int layout;
public MyListAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags){
super(context, layout, c, from, to, flags);
this.context = context;
this.layout = layout;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup par){
ViewHolder holder;
if(convertView==null){
mInflater = LayoutInflater.from(getBaseContext());
convertView = mInflater.inflate(R.layout.listtemplate, null);
holder = new ViewHolder();
holder.btn = (ImageButton) convertView.findViewById(R.id.delete_note);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
int l = sp.getInt("ajdi", 0);
if (l != 0) {
mydb.deleteNotes(l);
Toast.makeText(MainActivity.this, "Deleted", Toast.LENGTH_SHORT).show();
finish();
startActivity(getIntent());
}
}
});
convertView.setTag(holder);
}else{
holder= (ViewHolder) convertView.getTag();
}
return convertView;
}
}
public class ViewHolder{
ImageButton btn;
TextView title;
TextView date;
}
}
This is my Database java file.
package com.example.android.notepad2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by DelicAnte on 04.10.2017..
*/
public class NDb extends SQLiteOpenHelper {
public static final String dbname = "mydb";
public static final String mynotes = "mynotes";
public static final String _id = "_id";
public static final String name = "name";
public static final String content = "content";
public static final String date = "date";
SQLiteDatabase db;
public NDb(Context context){
super(context,dbname,null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table mynotes"
+"(_id integer primary key, name text, content text, date text)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS" + mynotes);
onCreate(db);
}
public boolean insertNotes(String name, String content, String date){
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("content", content);
contentValues.put("date", date);
db.insert(mynotes, null, contentValues);
return true;
}
public Cursor fetchAll(){
db = this.getReadableDatabase();
Cursor mCursor = db.query(mynotes, new String[] {"_id", "name", "content", "date"}, null, null, null, null, null);
if(mCursor!=null){
mCursor.moveToFirst();
}
return mCursor;
}
public Integer deleteNotes(Integer id){
db = this.getWritableDatabase();
return db.delete(mynotes, "_id=?", new String[] {Integer.toString(id)});
}
public Cursor getData(int id){
db = this.getReadableDatabase();
Cursor c = db.rawQuery("select * from " + mynotes +" where _id=" + id + "", null);
return c;
}
}
This is my listtemplate.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2"
>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/title"
android:textSize="22sp"
android:layout_weight="1"
android:paddingBottom="15dp"
/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/date"
android:textSize="14sp"
android:layout_weight="0.5"
/>
<ImageButton
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:src="#drawable/delete_note"
android:layout_weight="0.5"
android:focusable="false"
android:id="#+id/delete_note"
/>
<!-- android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"-->
</LinearLayout>
</LinearLayout>
If anyone might be interested. I solved this by adding adapter.bindView in mainactivity.java. In that method you set text for title, content and finally a button setonclicklistener.

how to authenticate and save data in firebase at same time using android studio

i have wrriten a code and getting error in
06-30 23:55:00.702 2499-2499/com.example.parthtiwari.trace E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.parthtiwari.trace, PID: 2499
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null
my code is
import android.app.ProgressDialog;
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.TextView;
import android.widget.Toast;
import com.google.firebase.auth.AuthResult;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private FirebaseAuth fb;
private DatabaseReference databaseReference;
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextName, mobile_number,vehicle_number,editTextAddress;
private Button buttonSignup;
private TextView textViewSignin;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fb = FirebaseAuth.getInstance();
if(fb.getCurrentUser() != null){
finish();
startActivity(new Intent(getApplicationContext(),welcome.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
editTextAddress = (EditText) findViewById(R.id.Address);
editTextName = (EditText) findViewById(R.id.name);
mobile_number = (EditText) findViewById(R.id.mobile);
vehicle_number = (EditText) findViewById(R.id.vehicle);
editTextEmail = (EditText) findViewById(R.id.Email);
editTextPassword = (EditText) findViewById(R.id.Password);
buttonSignup = (Button) findViewById(R.id.Signup);
textViewSignin = (TextView) findViewById(R.id.Signin);
progressDialog = new ProgressDialog(this);
FirebaseUser user = fb.getCurrentUser();
buttonSignup.setOnClickListener(this);
textViewSignin.setOnClickListener(this);
}
private void registerUser() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter email",
Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password",
Toast.LENGTH_LONG).show();
return;
}
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
fb.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Successfully registered", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Registration Error", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
saveUserInformation();
}
private void saveUserInformation() {
String name = editTextName.getText().toString().trim();
String mob = mobile_number.getText().toString().trim();
String vehicle = vehicle_number.getText().toString().trim();
String add = editTextAddress.getText().toString().trim();
//creating a userinformation object
userinfo userInformation = new userinfo(name, mob, vehicle, add);
//getting the current logged in user
FirebaseUser user = fb.getCurrentUser();
databaseReference.child(user.getUid()).setValue(userInformation);
//displaying a success toast
Toast.makeText(this, "Information Saved...", Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View view) {
if(view == buttonSignup){
registerUser();
}
if(view == textViewSignin){
startActivity(new Intent(this, login.class));
}
}
}
Try moving saveUserInformation() into your onCompletionListener.
Looks like saveUserInformation() is called before registration is completed.
fb.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
saveUserInformation(authResult);
Toast.makeText(MainActivity.this, "Successfully
registered",Toast.LENGTH_LONG).show();
progressDialog.dismiss(); }).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Registration Error",
Toast.LENGTH_LONG).show();
progressDialog.dismiss();
});
and change
saveUserInformation(AuthResult authResult)
authResult.getUid();

Resources