NullPointerException with Firebase Authentication [closed] - android

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm doing a blog app, but when I run it, I have this code of crash:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fgvelectro.f/com.fgvelectro.f.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
I've searched on the net for days, without success. I've saw other threads that talked about that problem, but nothing solved. Here it is my MainActivity:
import com.firebase.ui.database.FirebaseRecyclerAdapter;
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.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
private RecyclerView mBlogList;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseUsers;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() == null){
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseUsers.keepSynced(true);
mDatabase.keepSynced(true);
mBlogList = (RecyclerView) findViewById(R.id.blog_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
checkUserExist();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.blog_row,
BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
private void checkUserExist() {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(user_id)){
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setupIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public static class BlogViewHolder extends RecyclerView.ViewHolder{
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setImage(Context ctx, String image){
ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
Picasso.with(ctx).load(image).into(post_image);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_add){
startActivity(new Intent(MainActivity.this, PostActivity.class));
}
if (item.getItemId() == R.id.action_logout){
logout();
}
return super.onOptionsItemSelected(item);
}
private void logout() {
mAuth.signOut();
}
}
I know that is hard (and timewasting) to solve this problem, but if you can help me, thanks, thanks, thanks.
faby
Now my code looks like this:
private void checkUserExist() {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(user_id)){
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setupIntent);
}
if (FirebaseAuth.getInstance().getCurrentUser() == null) {Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
else{
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
}
what should I do? Is it ok?
[new edit]
Hi thanks but nothing worked. Firebase support is helping me now, I'll get you know if something will work

In your app build.gradle, add this to your dependencies
compile 'com.google.firebase:firebase-auth:11.0.4'
and in java file;
import com.google.firebase.auth.FirebaseAuth;
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
//Go to login
}
else{
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
}

Related

Error after logout and try to login again on Firebase DB

My app is working normally but he crash if i logout and try to login again. After the crash if i try to open the app again he open normally.
This is the error:
com.google.firebase.database.DatabaseException: Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance.
This is my classe:
DatabaseReference databaseReference;
RecyclerView recyclerView;
ArrayList<Tasks> tasksArrayList;
UsersRecyclerAdapter adapter;
GoogleSignInOptions gso;
GoogleSignInClient gsc;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Objects.requireNonNull(getSupportActionBar());
CheckLogin();
FirebaseDatabase.getInstance().setPersistenceEnabled(true); // work offline
databaseReference = FirebaseDatabase.getInstance().getReference();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
tasksArrayList = new ArrayList<>();
ReadData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.add) {
ViewDialogAdd viewDialogAdd = new ViewDialogAdd();
viewDialogAdd.showDialog(MainActivity.this);
}else if (id == R.id.logout) {
gsc.signOut().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
finish();
}
});
}
return super.onOptionsItemSelected(item);
}
private void CheckLogin(){
//Check if user is logged in
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
gsc = GoogleSignIn.getClient(this, gso);
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (account != null){
userID = account.getId();
} else {
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}
private void ReadData() {
if (userID != null) {
databaseReference.child("DB").child(userID).child("TASKS").orderByChild("id").addValueEventListener(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
tasksArrayList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Tasks users = dataSnapshot.getValue(Tasks.class);
tasksArrayList.add(users);
}
adapter = new UsersRecyclerAdapter(MainActivity.this, tasksArrayList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
public class ViewDialogAdd {
public void showDialog(Context context) {
/*Body*/
}
}
I tried to change this line of code:
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
I put it in different places in my code but the error is the same.
I also tried to remove the CheckLogin(); but the error persist the same way
Yesterday i make a few researches about my error and found nothing. Today i made i few more searches and this here helped me fix the problem.
Solution

Is there a way to reference a variable outside onCreate method?

I can't seem to reference a variable outside the onCreate method. Is there a way to overcome this? I'm a student and still learning. If anyone can help, that would be great. Thank you. I would like to reference the "url" variable to the "onItemClick" method, it says "Cannot resolve symbol".
Here is my code :
public class CominSoonActivity extends AppCompatActivity implements RecyclerViewClickItemInterface {
DatabaseReference reference;
RecyclerView recyclerView;
ArrayList<Event> list;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comin_soon);
recyclerView = findViewById(R.id.myRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<Event>();
adapter = new MyAdapter(CominSoonActivity.this, list, this);
recyclerView.setAdapter(adapter);
reference = FirebaseDatabase.getInstance().getReference().child("EventDisplay");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Event e = dataSnapshot1.getValue(Event.class);
String url = (String) dataSnapshot1.child("website").getValue();
list.add(e);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(CominSoonActivity.this, "Opps.... Something went wrong", Toast.LENGTH_SHORT).show();
}
});
//add back button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
#Override
public void onItemClick(int position) {
//Uri uri = Uri.parse("http://fareezdanial19.wixsite.com/merlimaulibrary");
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
//taking the user back to the previous activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
Intent homeActivity = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(homeActivity);
finish();
}
return super.onOptionsItemSelected(item);
}
}
You can do it like this,
public class CominSoonActivity extends AppCompatActivity implements RecyclerViewClickItemInterface {
DatabaseReference reference;
RecyclerView recyclerView;
ArrayList<Event> list;
MyAdapter adapter;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comin_soon);
recyclerView = findViewById(R.id.myRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<Event>();
adapter = new MyAdapter(CominSoonActivity.this, list, this);
recyclerView.setAdapter(adapter);
reference = FirebaseDatabase.getInstance().getReference().child("EventDisplay");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Event e = dataSnapshot1.getValue(Event.class);
url = (String) dataSnapshot1.child("website").getValue();
list.add(e);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(CominSoonActivity.this, "Opps.... Something went wrong", Toast.LENGTH_SHORT).show();
}
});
//add back button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
#Override
public void onItemClick(int position) {
//Uri uri = Uri.parse("http://fareezdanial19.wixsite.com/merlimaulibrary");
if(!url.isEmpty()){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
//taking the user back to the previous activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
Intent homeActivity = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(homeActivity);
finish();
}
return super.onOptionsItemSelected(item);
}
}

Android app crashes while scrolling down

I am developing a blogging app for android and I am using firebase for the backend. The app is working fine but the when I scroll down to the last post, the app crashes. I have working on finding the solution from a quite a long but couldn't possibly find any.
Here is the activity which is facing the problem
public class UserActivity extends AppCompatActivity {
private RecyclerView mStatusView;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseUsers;
private DatabaseReference mDatabaseLike;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
String userID = "";
private Boolean exit = false;
private Boolean mProcessLike = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
Intent loginIntent = new Intent(UserActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("Status");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseUsers.keepSynced(true);
mDatabaseLike.keepSynced(true);
mDatabase.keepSynced(true);
mStatusView = findViewById(R.id.status_list);
mStatusView.setHasFixedSize(true);
mStatusView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
checkUserExists();
mFirebaseAuth.addAuthStateListener(mAuthListener);
// Creating a Firebase recycle Adapter
FirebaseRecyclerAdapter<Status, StatusViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Status, StatusViewHolder>(
Status.class,
R.layout.status_row,
StatusViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(StatusViewHolder viewHolder, Status model, int position) {
final String postKey = getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDescription((model.getDescription()));
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.mNumberOfLikesTextView.setVisibility(View.GONE);
viewHolder.setLikeButton(postKey);
viewHolder.mLikeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLike = true;
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(postKey).hasChild(mFirebaseAuth.getCurrentUser().getUid())) {
mDatabaseLike.child(postKey).child(mFirebaseAuth.getCurrentUser().getUid()).removeValue();
mProcessLike = false;
Toast.makeText(UserActivity.this, "Like removed", Toast.LENGTH_SHORT).show();
} else {
mDatabaseLike.child(postKey).child(mFirebaseAuth.getCurrentUser().getUid()).setValue("RandomValue");
mProcessLike = false;
Toast.makeText(UserActivity.this, "Liked", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mStatusView.setAdapter(firebaseRecyclerAdapter);
}
private void checkUserExists() {
try {
userID = mFirebaseAuth.getCurrentUser().getUid();
} catch (NullPointerException e) {
e.printStackTrace();
}
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(userID)) {
Intent registerIntent = new Intent(UserActivity.this,
RegisterActivity.class);
registerIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(registerIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// Setting up Recycler View
public static class StatusViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageButton mLikeButton;
TextView mNumberOfLikesTextView;
DatabaseReference mDataBaseLike;
FirebaseAuth mAuth;
public StatusViewHolder(View itemView) {
super(itemView);
mView = itemView;
mLikeButton = itemView.findViewById(R.id.like_button);
mNumberOfLikesTextView = itemView.findViewById(R.id.number_of_likes_text_view);
mDataBaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mAuth = FirebaseAuth.getInstance();
mDataBaseLike.keepSynced(true);
}
public void setLikeButton(final String postKey) {
mDataBaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())) {
mLikeButton.setImageResource(R.drawable.ic_thumb_up_blue_24dp);
} else {
mLikeButton.setImageResource(R.drawable.ic_thumb_up_black_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// Setting the title
public void setTitle(String title) {
TextView statusTitle = mView.findViewById(R.id.status_title_textView);
statusTitle.setText(title);
}
public void setDescription(String desc) {
TextView statusDescription = mView.findViewById(R.id.status_description_textView);
statusDescription.setText(desc);
}
public void setImage(Context context, String image) {
ImageView statusImage = mView.findViewById(R.id.status_image);
Picasso.with(context).load(image).into(statusImage);
}
}
}
And here is the log for the problem I'm getting
FATAL EXCEPTION: main
Process: com.example.akash.iametderick, PID: 12384
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.example.akash.iametderick.Status
at com.google.android.gms.internal.zzdzr.zzb(Unknown Source:842)
at com.google.android.gms.internal.zzdzr.zza(Unknown Source:0)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source:10)
at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:22)
at com.firebase.ui.database.ObservableSnapshotArray.getObject(ObservableSnapshotArray.java:160)
at com.firebase.ui.database.CachingObservableSnapshotArray.getObject(CachingObservableSnapshotArray.java:40)
at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:180)
at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:217)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6482)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6515)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5458)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724)
at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:285)
at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:342)
at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:358)
at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:365)
at android.support.v7.widget.GapWorker.run(GapWorker.java:396)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I've been trying to solve the problem from quite a long but couldn't find any solution.
This is my status node:
Status {
-L10rFvy6N-t7RiF7FJ6 {
date: ...;
description: ...;
image: ...;
title: ...''
}
date: ...;
description: ...;
image: ...;
title: ...''
}
The issue is with your data saved on firebase.
Your Node Status is a Object and you may have saved its value as long for that particular node in your database.
So check you database and compare it with other node . Specially the node which is having the problem will be in last as you said when I scroll down to the last pos so check your last node

How do I Query this in Android Studio using Firebase?

In my software I need a Query, how do I Query 2 information from the Database?? I need the "uid" and "book", check the link for watching my Database: https://i.stack.imgur.com/9TSt6.png
listWN = (RecyclerView) findViewById(R.id.listReading);
listWN.setLayoutManager(new LinearLayoutManager(this));
bookYouAreIn = getIntent().getStringExtra("book");
firebaseauth = FirebaseAuth.getInstance();
String currentUserId = firebaseauth.getCurrentUser().getUid();
mDatabase = FirebaseDatabase.getInstance().getReference("Data");
mQuery = mDatabase.orderByChild("book").equalTo(bookYouAreIn); **---> HOW DO I ADD HERE: AND mDatabase.orderByChild("uid").equalTo(firebaseauth.getCurrentUser().getUid());**
mDatabase.keepSynced(true);
if(!firebaseauth.getCurrentUser().getUid().equals(currentUserId)){
startActivity(new Intent(WordNote.this,LoginActivity.class));
finish();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_secondmenu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_addWords){
Intent postIntent = new Intent(WordNote.this, PostActivity.class);
postIntent.putExtra("bookToPost", bookYouAreIn);
startActivity(postIntent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
final FirebaseRecyclerAdapter<MyReading, MyReadingViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter <MyReading, MyReadingViewHolder>
(
MyReading.class,
R.layout.list_reading,
MyReadingViewHolder.class,
mQuery )
{
#Override
protected void populateViewHolder(final MyReadingViewHolder viewHolder, final MyReading model, final int position) {
final String wordNote_key = getRef(position).getKey();
viewHolder.setWord(model.getWord());
viewHolder.setNote(model.getNote());
mDatabase.child(wordNote_key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String user = (String) dataSnapshot.child("uid").getValue();
String bookNow = (String) dataSnapshot.child("book").getValue();
if(firebaseauth.getCurrentUser().getUid().equals(user)){
mDatabase.child(wordNote_key).orderByChild("uid").equals(user);
}
else {
viewHolder.nView.setVisibility(View.GONE); **--> IT DOESN'T GO AWAY, IT KEEPS STAYING AS A BLANK VIEW**
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
viewHolder.nView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent singleIntent = new Intent(WordNote.this, HandleWordNote.class);
singleIntent.putExtra("listWords", wordNote_key);
startActivity(singleIntent);
}
});
}
};
listWN.setAdapter(firebaseRecyclerAdapter);
See my answer from this post.
In your case, the field would be: uid_book: "OKtUxSleCGbU0F_Pasqua".
Hope it helps.

Error android firebase java.lang.NullPointerException

I'm getting error on getUid()
final String user_id = mAuth.getCurrentUser().getUid();
and this my activity code :
public class MainActivity extends AppCompatActivity {
private RecyclerView postList;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseUsers;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null){
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabase.keepSynced(true);
mDatabaseUsers.keepSynced(true);
postList = (RecyclerView) findViewById(R.id.post_list);
postList.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
postList.setLayoutManager(layoutManager);
}
#Override
protected void onStart() {
super.onStart();
CheckUserExist();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.post_row,
BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDescription());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
postList.setAdapter(firebaseRecyclerAdapter);
}
private void CheckUserExist() {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(user_id)){
Intent SetupIntent = new Intent(MainActivity.this, SetupActivity.class);
SetupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(SetupIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public static class BlogViewHolder extends RecyclerView.ViewHolder{
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setImage(final Context ctx, final String image){
final ImageView post_image = (ImageView) mView.findViewById(R.id.post_img);
// Picasso.with(ctx).load(image).into(post_image);
Picasso.with(ctx).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(post_image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(image).into(post_image);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_add){
startActivity(new Intent(MainActivity.this, PostActivity.class));
}
if (item.getItemId() == R.id.action_logout){
logout();
}
return super.onOptionsItemSelected(item);
}
private void logout() {
mAuth.signOut();
}
}
The problem happens when you try to call mAuth.getCurrentUser().getUid(). Apparently there is no current user at the time, so that call fails.
Instead use:
private void CheckUserExist() {
if (mAuth.getCurrentUser() != null) {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(user_id)){
Intent SetupIntent = new Intent(MainActivity.this, SetupActivity.class);
SetupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(SetupIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
In general, you'll want to use an auth state listener for this, similar to the one you already have in onCreate.
In fact, it seems to me that both could easily be folded into a single listener: one that starts the login activity if the user isn't signed in and optionally registers the user with the database if they are.
The code for that:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabase.keepSynced(true);
mDatabaseUsers.keepSynced(true);
postList = (RecyclerView) findViewById(R.id.post_list);
postList.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
postList.setLayoutManager(layoutManager);
}
#Override
protected void onStart() {
super.onStart();
CheckUserExist();
FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null){
// The user is not signed in, start login flow
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
else {
// The user is signed in, register them in database
String user_id = user.getUid();
mDatabaseUsers.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()){
Intent SetupIntent = new Intent(MainActivity.this, SetupActivity.class);
SetupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(SetupIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore onCancelled
}
});
}
}
});
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.post_row,
BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDescription());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
postList.setAdapter(firebaseRecyclerAdapter);
}
I also fixed the way you check if the user already exists in the database. Retrieving all users to then client-side check if one of the keys exists is a waste of bandwidth that will become especially evident as your number of users grows. The code I wrote checks precisely whether this user's UID already exists in the database, which is the minimum data you can check.
It is because you are not initializing mauth.
remove onstart method and copy the code to oncreate. oncreate will be
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null){
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabase.keepSynced(true);
mDatabaseUsers.keepSynced(true);
postList = (RecyclerView) findViewById(R.id.post_list);
postList.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
postList.setLayoutManager(layoutManager);
CheckUserExist();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.post_row,
BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDescription());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
postList.setAdapter(firebaseRecyclerAdapter);
}

Categories

Resources