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.
Related
Thank you for helping me. The menu didn't appear and the list view in the recycler view is unclickable.
This is the menu part.
public class QuizListActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_list);
mAuth = FirebaseAuth.getInstance();
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerBView);
new FirebaseDatabaseHelper().readQuiz(new FirebaseDatabaseHelper.DataStatus() {
#Override
public void DataIsLoaded(List<Quiz> quizzes, List<String> keys) {
new RecyclerConfig().setConfig(mRecyclerView, QuizListActivity.this, quizzes, keys);
}
#Override
public void DataIsInserted() {
}
#Override
public void DataIsUpdated() {
}
#Override
public void DataIsDeleted() {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
FirebaseUser user = mAuth.getCurrentUser();
getMenuInflater().inflate(R.menu.quizlistmenu, menu);
if(user!=null) {
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(true);
menu.getItem(2).setVisible(true);
}
return super.onCreateOptionsMenu(menu);
}
public boolean onPrepareOptionsMenu(Menu menu)
{FirebaseUser user = mAuth.getCurrentUser();
if(user!=null) {
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(true);
menu.getItem(2).setVisible(true);
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.new_book:
startActivity(new Intent(this, NewQuestionActivity.class));
return true;
case R.id.user_approval:
startActivity(new Intent(this, Approval.class));
return true;
case R.id.signout:
mAuth.signOut();
invalidateOptionsMenu();
RecyclerConfig.logout();
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the menu.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/new_book"
android:title="New Question" />
<item
android:id="#+id/user_approval"
android:title="Registered User" />
<item
android:id="#+id/signout"
android:title="Sign Out" />
</menu>
This is the Recycler part.
public class RecyclerConfig
{
FirebaseAuth mAuth;
private static FirebaseUser user;
private Context mContext;
private QuizAdapter mQuizAdapter;
public void setConfig(RecyclerView mRecyclerView, Context context, List<Quiz> quizzes, List<String> keys)
{
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
mContext = context;
mQuizAdapter = new QuizAdapter(quizzes, keys);
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
mRecyclerView.setAdapter(mQuizAdapter);
}
class QuizItemView extends RecyclerView.ViewHolder
{
private TextView mquestion,mans1,mans2,mans3,mans4,mcorrect,mcategoryid;
private String key;
public QuizItemView(ViewGroup parent)
{
super(LayoutInflater.from(mContext)
.inflate(R.layout.quizlistitem, parent, false));
mquestion = (TextView) itemView.findViewById(R.id.questiontv);
mans1 = (TextView) itemView.findViewById(R.id.ans1tv);
mans2 = (TextView) itemView.findViewById(R.id.ans2tv);
mans3 = (TextView) itemView.findViewById(R.id.ans3tv);
mans4 = (TextView) itemView.findViewById(R.id.ans4tv);
mcorrect = (TextView) itemView.findViewById(R.id.correcttv);
mcategoryid = (TextView) itemView.findViewById(R.id.categorytv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(user!=null) {
Intent intent = new Intent(mContext, QuizDetailActivity.class);
intent.putExtra("key", key);
intent.putExtra("question", mquestion.getText().toString());
intent.putExtra("answer1", mans1.getText().toString());
intent.putExtra("answer2", mans2.getText().toString());
intent.putExtra("answer3", mans3.getText().toString());
intent.putExtra("answer3", mans4.getText().toString());
intent.putExtra("answer3", mcorrect.getText().toString());
intent.putExtra("categoryid", mcategoryid.getText().toString());
mContext.startActivity(intent);
}
/*else
{
mContext.startActivity(new Intent(mContext, SignInActivity.class));
}*/
}
});
}
public void bind(Quiz quizzes, String key)
{
mquestion.setText(quizzes.getQuestion());
mans1.setText(quizzes.getAnswer1());
mans2.setText(quizzes.getAnswer2());
mans3.setText(quizzes.getAnswer3());
mans4.setText(quizzes.getAnswer4());
mcorrect.setText(quizzes.getCorrect());
mcategoryid.setText(quizzes.getCategoryid());
this.key = key;
}
}
class QuizAdapter extends RecyclerView.Adapter<QuizItemView>
{
private List<Quiz> mQuizList;
private List<String> mKeys;
public QuizAdapter(List<Quiz> mQuizList, List<String> mKeys) {
this.mQuizList = mQuizList;
this.mKeys = mKeys;
}
#NonNull
#Override
public QuizItemView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new QuizItemView(parent);
}
#Override
public void onBindViewHolder(#NonNull QuizItemView holder, int position) {
holder.bind(mQuizList.get(position), mKeys.get(position));
}
#Override
public int getItemCount() {
return mQuizList.size();
}
}
public static void logout()
{
user = null;
}
}
This is the login / register part.
public class SignInActivity extends AppCompatActivity {
MaterialEditText edtNewEmail,edtNewPassword,edtnewName, edtnewAge, edtnewAddress, edtStatus; // for register
MaterialEditText edtEmail,edtPassword; //for Signin
Button btnRegister,btnSignIn;
FirebaseAuth mAuth;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mAuth = FirebaseAuth.getInstance();
//Firebase
database = FirebaseDatabase.getInstance();
users = database.getReference("User");
edtEmail = (MaterialEditText)findViewById(R.id.edtEmail);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
btnSignIn = (Button)findViewById(R.id.signInBtn);
btnRegister = (Button)findViewById(R.id.regBtn);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showSignUpDialog();
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn(edtEmail.getText().toString(),edtPassword.getText().toString());
}
});
}
private void signIn(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user).exists())
{
if(!user.isEmpty())
{
User login = dataSnapshot.child(user).getValue(User.class);
if(login.getPassword().equals(pwd))
{
Common.currentUser = login;
if(login.getStatus().equals("Admin"))
{
mAuth.signInWithEmailAndPassword(edtEmail.getText().toString(),
edtPassword.getText().toString());
Toast.makeText(SignInActivity.this, "User signed in", Toast.LENGTH_LONG).show();
Intent intent = new Intent(SignInActivity.this,QuizListActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); return;
}
else if(login.getStatus().equals("User") && login.getApproval().equals("Y"))
{
Intent homeactivity = new Intent(SignInActivity.this,Home.class);
startActivity(homeactivity);
finish();
}
else if(login.getStatus().equals("User") && login.getApproval().equals("N"))
{
Intent adminactivity = new Intent(SignInActivity.this,Home.class);
startActivity(adminactivity);
finish();
}
}
else
Toast.makeText(SignInActivity.this,"Login Failed",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SignInActivity.this,"Please fill in",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(SignInActivity.this,"User doesn't exist",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showSignUpDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SignInActivity.this);
alertDialog.setTitle("Sign Up");
//alertDialog.setMessage("Please fill full information");
LayoutInflater inflater = this.getLayoutInflater();
View activity_register = inflater.inflate(R.layout.activity_register,null);
//edtNewUserName = (MaterialEditText)activity_register.findViewById(R.id.edtNewUserName);
edtNewEmail = (MaterialEditText)activity_register.findViewById(R.id.edtNewEmail);
edtNewPassword = (MaterialEditText)activity_register.findViewById(R.id.edtNewPassword);
edtnewName = (MaterialEditText)activity_register.findViewById(R.id.edtnewName);
edtnewAge = (MaterialEditText)activity_register.findViewById(R.id.edtnewAge);
edtnewAddress = (MaterialEditText)activity_register.findViewById(R.id.edtnewAddress);
edtStatus = (MaterialEditText)activity_register.findViewById(R.id.edtStatus);
alertDialog.setView(activity_register);
//alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final User user = new User(edtNewEmail.getText().toString(),
edtNewPassword.getText().toString(),edtnewName.getText().toString(),
edtnewAge.getText().toString(),edtnewAddress.getText().toString(),edtStatus.getText().toString(),
"N");
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user.getEmail()).exists())
Toast.makeText(SignInActivity.this,"User already exist.",Toast.LENGTH_LONG).show();
else
{
if(dataSnapshot.child(user.getStatus()).exists() && user.getStatus() == "Admin")
{
mAuth.createUserWithEmailAndPassword(edtNewEmail.getText().toString(),
edtNewPassword.getText().toString())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
FirebaseDatabase.getInstance().getReference("User")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user);
}
}
});
}
else {
users.child(user.getEmail())
.setValue(user);
Toast.makeText(SignInActivity.this, "User registered.", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
The login and register works well then after login the list recycler view is shown accurately but the menu didn't appear and the recycler view is unclickable.
For the menu, it previously stated that a null reference or something.
For your first question, which is why menu didn't appear because you didn't initialize the FirebaseUser. You need to initiliaze it at method onCreate.
at Class.
private FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_list);
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
}
next, at your onCreateOptionsMenu.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.quizlistmenu, menu);
if(user!=null) {
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(true);
menu.getItem(2).setVisible(true);
}
return super.onCreateOptionsMenu(menu);
}
I'm making a chat application that uses Firebase as a backend, but I'm having trouble getting the RecyclerView to scroll to the bottom of the list. I have a chatActivity that has the following methods:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Id = getIntent().getExtras().getString("matchId");
Pic = findViewById(R.id.displayImageMessages);
thoughtButton = findViewById(R.id.messageThought);
//SET MENU
menuButton = findViewById(R.id.messageMenu);
menuButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
optionMenu = new PopupMenu(ChatActivity.this,menuButton);
optionMenu.getMenuInflater().inflate(R.menu.popup_menu2,optionMenu.getMenu());
optionMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
if(menuItem.getItemId() == R.id.one){
backtoMain();
return true;
}
else if (menuItem.getItemId() == R.id.two){
return true;
}
else if(menuItem.getItemId() == R.id.three){
FirebaseAuth auth = FirebaseAuth.getInstance();
auth.signOut();
backtoMenu();
return true;
}
else{
return false;
}
}
});
optionMenu.show();
}
});
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
//LOAD PICTURE
URI = getIntent().getExtras().getString("displayPic");
Glide.with(this).load(URI).thumbnail(0.4f).into(Pic);
//RETRIEVE CHAT
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseUser = FirebaseDatabase.getInstance().getReference().child("users").child(currentUserID).child("connections").child(Id).child("ChatId");
databaseChat = FirebaseDatabase.getInstance().getReference().child("chat");
getChatId();
mSendEditText = findViewById(R.id.messageText);
mSendButton = findViewById(R.id.send);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
mRecyclerView = (RecyclerView) findViewById(R.id.ChatRecycler);
mRecyclerView.setNestedScrollingEnabled(true);
mRecyclerView.setHasFixedSize(false);
linearLayoutManager = new LinearLayoutManager(ChatActivity.this);
mChatLayoutManager = linearLayoutManager;
mRecyclerView.setLayoutManager(mChatLayoutManager);
mChatAdapter = new ChatViewAdapter(getDataSetChat(),ChatActivity.this);
mRecyclerView.setAdapter(mChatAdapter);
mRecyclerView.addItemDecoration(new VerticalSpaceItemDecoration(20));
}
and
private void getChatId() {
databaseUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
chatId = dataSnapshot.getValue().toString();
databaseChat = databaseChat.child(chatId);
getChatMessages();
linearLayoutManager.scrollToPositionWithOffset(resultsChat.size(),0);
Log.d("messageTAG",String.valueOf(mChatAdapter.getItemCount()));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
and
private void getChatMessages() {
databaseChat.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists()){
String message = null;
String createdbyuser = null;
long timestamp = 0;
if (dataSnapshot.child("text").getValue()!=null){
message = dataSnapshot.child("text").getValue().toString();
}
if (dataSnapshot.child("createdBy").getValue()!=null){
createdbyuser = dataSnapshot.child("createdBy").getValue().toString();
}
if (dataSnapshot.child("timestamp").getValue()!=null){
timestamp = Long.valueOf(dataSnapshot.child("timestamp").getValue().toString());
}
if (message!=null&&createdbyuser!=null){
Boolean currentUserBoolean = false;
if (createdbyuser.equals(currentUserID)){
currentUserBoolean = true;
}
ChatObject newMessage = new ChatObject(message,currentUserBoolean,timestamp);
resultsChat.add(newMessage);
mChatAdapter.notifyDataSetChanged();
}
//SETS VISABILITY OF THOUGHTS BUTTON IF CHAT SIZE IS ABOVE 10
if(resultsChat.size() > 10){
thoughtButton.setVisibility(View.VISIBLE);
}
}
}
I've tried various layoutManager.ScrollToPosition or adapter.ScrollToPosition etc, but I'd appreciate any thoughts you have on this problem?
Try using
mRecyclerView.scrollToPosition(resultsChat.size() - 1);
In databaseChat.addChildEventListener()
Like this :
ChatObject newMessage = new ChatObject(message,currentUserBoolean,timestamp);
resultsChat.add(newMessage);
mRecyclerView.scrollToPosition(resultsChat.size() - 1); //here
mChatAdapter.notifyDataSetChanged();
Hi I am using Firebase Database with search query. I am also using offline method to store data from firebase offline. But after implementing searchview when I am opening the page it is showing blank. Data is coming after clicking the search icon. How to solve this? My application is on the playstore. It is the Link of the Application
And Here is my search query Code
private void firebaseUserSearch(String searchText) {
Query firebaseSearchQuery = mUserDatabase.orderByChild("Title").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Blog,BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.bank_row,
BlogViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, final Blog model, int position) {
final String fav_key=getRef(position).getKey();
viewHolder.setDetails(getApplicationContext(), model.getTitle(), model.getDescription(), model.getExample());
viewHolder.setFavourite(fav_key);
viewHolder.favourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mfavourite=true;
databasefavourite.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(mfavourite){
if (dataSnapshot.child(fav_key).hasChild("Title")){
databasefavourite.child(fav_key).child("Title").removeValue();
mfavourite = false;
}else {
databasefavourite.child(fav_key).child("Title").setValue(model.getTitle());
mfavourite = false;
}
if (dataSnapshot.child(fav_key).hasChild("Description")){
databasefavourite.child(fav_key).child("Description").removeValue();
mfavourite = false;
}else {
databasefavourite.child(fav_key).child("Description").setValue(model.getDescription());
mfavourite = false;
}
if (dataSnapshot.child(fav_key).hasChild("Example")){
databasefavourite.child(fav_key).child("Example").removeValue();
mfavourite = false;
}else {
databasefavourite.child(fav_key).child("Example").setValue(model.getExample());
mfavourite = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
It is my code for onStart()
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Blog,Idioms.BlogViewHolder>firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<Blog, Idioms.BlogViewHolder>
(Blog.class,R.layout.bank_row,Idioms.BlogViewHolder.class,mUserDatabase) {
#Override
protected void populateViewHolder(Idioms.BlogViewHolder viewHolder, final Blog model, int position) {
final String fav_key=getRef(position).getKey();
viewHolder.setDetails(getApplicationContext(), model.getTitle(), model.getDescription(), model.getExample());
viewHolder.setFavourite(fav_key);
viewHolder.favourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mfavourite=true;
databasefavourite.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(mfavourite){
if (dataSnapshot.child(fav_key).hasChild("Title")){
databasefavourite.child(fav_key).child("Title").removeValue();
mfavourite = false;
}else {
databasefavourite.child(fav_key).child("Title").setValue(model.getTitle());
mfavourite = false;
}
if (dataSnapshot.child(fav_key).hasChild("Description")){
databasefavourite.child(fav_key).child("Description").removeValue();
mfavourite = false;
}else {
databasefavourite.child(fav_key).child("Description").setValue(model.getDescription());
mfavourite = false;
}
if (dataSnapshot.child(fav_key).hasChild("Example")){
databasefavourite.child(fav_key).child("Example").removeValue();
mfavourite = false;
}else {
databasefavourite.child(fav_key).child("Example").setValue(model.getExample());
mfavourite = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
And it is my search action code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
firebaseUserSearch(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
firebaseUserSearch(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
I'm doing a realtime tracking application from a tutorial online, Here i'm setting the presence system using firebase. But it's crashing with:
/java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
I don't understand what's wrong the guy who coded this has it working perfectly.
The exception is happening at this line :if(dataSnapshot.getValue(Boolean.class)){
When i log this on screen the datasnapshot object has a key but no value
HELP!
ListOnline Class
//firebase
DatabaseReference onlineRef,currentUserRef,counterRef;
FirebaseRecyclerAdapter<User,ListOnlineViewHolder> adapter;
//View
RecyclerView listOnline;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_online);
//setting the recyclerview
listOnline = (RecyclerView)findViewById(R.id.listOnlineRecyclerview);
listOnline.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listOnline.setLayoutManager(layoutManager);
//set toolbar and menu / join,logout
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbarID);
toolbar.setTitle("Presence System");
setSupportActionBar(toolbar);
//firebase
onlineRef = FirebaseDatabase.getInstance().getReference().child("info/connected");
counterRef = FirebaseDatabase.getInstance().getReference("lastOnline"); //create new child name lastOnline
currentUserRef = FirebaseDatabase.getInstance().getReference().child(FirebaseAuth.getInstance().getCurrentUser().getUid());
setupSystem();
//after setup we load all users and display in recyclerview
//this is online list
updateList();
}
private void updateList() {
adapter = new FirebaseRecyclerAdapter<User, ListOnlineViewHolder>(
User.class,R.layout.user_layout,ListOnlineViewHolder.class,counterRef
) {
#Override
protected void populateViewHolder(ListOnlineViewHolder viewHolder, User model, int position) {
viewHolder.emailTextView.setText(model.getEmail());
}
};
adapter.notifyDataSetChanged();
listOnline.setAdapter(adapter);
}
private void setupSystem() {
onlineRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue(Boolean.class)){
currentUserRef.onDisconnect().removeValue();
//set online user in list
counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(FirebaseAuth.getInstance().getCurrentUser().getEmail(),"Online");
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
counterRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren()){
User user = postSnapshot.getValue(User.class);
Log.d("LOG",""+user.getEmail()+"is "+user.getStatus());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_join:
counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(FirebaseAuth.getInstance().getCurrentUser().getEmail(),"Online");
break;
case R.id.action_logout:
currentUserRef.removeValue();
}
return super.onOptionsItemSelected(item);
}
}
User Class
public class User {
private String email,status;
public User(String email, String status) {
this.email = email;
this.status = status;
}
public User() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}}
MainActivity
public class MainActivity extends AppCompatActivity {
Button signInButton;
private final static int LOGIN_PERMISSION = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = (Button) findViewById(R.id.signInButton);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().setAllowNewEmailAccounts(true).build(),LOGIN_PERMISSION);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == LOGIN_PERMISSION){
startNewActivity(resultCode,data);
}
}
private void startNewActivity(int resultcode, Intent data) {
if(resultcode == RESULT_OK){
Intent intent = new Intent(MainActivity.this,ListOnline.class);
startActivity(intent);
finish();
}
else{
Toast.makeText(this,"login failed!!",Toast.LENGTH_SHORT).show();
}
}}
In your setupSystem() method, you are attaching a listener to onlineRef (the info/connected node) and then marshalling the returned value to a Boolean value.
However, DataSnapshot#getValue() will return null if there is no data at the specified location in the database. If this happens, the dataSnapshot.getValue(Boolean.class) call will create a Boolean variable with the value of null, which then cannot be checked for a true value in your current if statement (see Check if null Boolean is true results in exception).
You could check that getValue() does not return null first by adding a null-check to your if statement:
if(dataSnapshot.getValue() != null && dataSnapshot.getValue(Boolean.class)){
// ...
}
Or check that the location exists using DataSnapshot#exists():
if(dataSnapshot.exists() && dataSnapshot.getValue(Boolean.class)){
// ...
}
However, if you're trying to detect connection state, did you mean to attach the listener to the .info/connected node instead? As from the documentation:
For many presence-related features, it is useful for your app to know
when it is online or offline. Firebase Realtime Database provides a
special location at /.info/connected which is updated every time the
Firebase Realtime Database client's connection state changes. Here is
an example:
DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
System.out.println("connected");
} else {
System.out.println("not connected");
}
}
#Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
});
its null since it does not exist in the database..
onlineRef = FirebaseDatabase.getInstance().getReference().child("info/connected");
you are querying on the above location. So dataSnapshot is a snapshot of the above..
if(dataSnapshot.getValue(Boolean.class)){
This does not exist in the database.. Thus you get that error
It seems that you do not have a value in database. This will handle the error
if(dataSnapshot.getValue(Boolean.class) != null && dataSnapshot.getValue(Boolean.class)){
I have an activity for searching in firebase, it contains edittext for typing the text and button when I press the button The results supposed to appear in the recyclerview but when I press the button the first time nothing appears unless I press the button for the second time
the code of findDataActivity
public class FindDataActivity extends AppCompatActivity {
DatabaseReference db;
FirebaseHelper helper;
MyAdapter adapter;
RecyclerView rv;
EditText findETxt;
Button findBtn;
ArrayList<Paints> p;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_data);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//SETUP RECYCLER
rv = (RecyclerView) findViewById(R.id.rvsearch);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
//INITIALIZE FIREBASE DB
db = FirebaseDatabase.getInstance().getReference("Database");
adapter = new MyAdapter(FindDataActivity.this, p);
rv.setAdapter(adapter);
findBtn = (Button) findViewById(R.id.find_btn);
helper = new FirebaseHelper(db);
}
public void search(View view) {
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
findETxt = (EditText) findViewById(R.id.findETxt);
s = findETxt.getText().toString();
p=helper.retrieveSearch(s);
adapter = new MyAdapter(FindDataActivity.this, p);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id == android.R.id.home){
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
the code of firebase
public class FirebaseHelper {
DatabaseReference db;
Boolean saved=null;
Boolean saved1=null;
ArrayList<Paints> paints=new ArrayList<>();
ArrayList<String> keys=new ArrayList<>();
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//READ THEN RETURN ARRAYLIST FOR SEARCH ITEMS IN CASE OF SEARCHING ABOUT ITEM
public ArrayList<Paints> retrieveSearch(final String item) {
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchDataSearch(dataSnapshot,item);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchDataSearch(dataSnapshot,item);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return paints;
}
//IMPLEMENT FETCH DATA AND FILL ARRAYLIST FOR SEARCH
private void fetchDataSearch( DataSnapshot dataSnapshot,String item)
{
paints.clear();
//sorting and searching
final DatabaseReference myRef = db.child("items");
Query query = myRef.orderByChild("type").startAt(item)
.endAt(item + "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
Paints paint=messageSnapshot.getValue(Paints.class);
paints.add(paint);
//Toast.makeText(FindDataActivity.this, "found " + type + " unit: " + unit + " price " + price, Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
In your MyAdapter class you must create a method like this:
public void updateAdapter(ArrayList<Paints> paint){
this.paint= paint;
notifyDataSetChanged();
}
In your search method replace adapter.notifyDataSetChanged(); for adapter.updateAdapter(p);