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);
}
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 have implemented a cardview along with a recyclerview that fetch data from firebase. I want to implement onclick methods to cards that goes for different activities. How can i add on click method for the cards? Here is my mainactivity.
public class English extends AppCompatActivity {
ViewHolder apt;
RecyclerView mRecyclerView;
FirebaseDatabase mFirebaseDatabase;
DatabaseReference mRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_english);
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mFirebaseDatabase = FirebaseDatabase.getInstance();
mRef = mFirebaseDatabase.getReference("English");
}
private void firebaseSearch(String searchText){
Query firebaseSearchQuery=mRef.orderByChild("artist").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<englishacti, ViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<englishacti, ViewHolder>(englishacti.class,R.layout.row,ViewHolder.class,firebaseSearchQuery) {
#Override
protected void populateViewHolder(ViewHolder holder, englishacti model, int position) {
holder.setDetails(getApplicationContext(),model.getAlbum(),model.getDescription(),model.getImage(),model.getArtist());
}
};
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<englishacti,ViewHolder> firebaseRecyclerAdapter;
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<englishacti, ViewHolder>(englishacti.class,R.layout.row,ViewHolder.class,mRef) {
#Override
protected void populateViewHolder(ViewHolder viewHolder, englishacti model, int position) {
viewHolder.setDetails(getApplicationContext(), model.getAlbum(), model.getDescription(), model.getImage(), model.getArtist());
}
};
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.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) {
firebaseSearch(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
firebaseSearch(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if (id==R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
}
please take a look at my snipshed code, in my case i use this way to implement setonlclick in recycleview item and send value to other activity
holder.setName(userName);
holder.setUserImage(userThumb, getContext());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chatIntent = new Intent(getContext(), Tampung_chatActivity.class);
chatIntent.putExtra("user_id", list_user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
}
});
full code you can see at here :
full snipshed code implement onclick with recycleview and firebase
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();
I can able to retrieve data from Firebase to App through RecyclerView. But when I am trying to add Search view its not working.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
final SearchView searchView =(SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.menusearch));
SearchManager searchManager =(SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName());
//searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//SearchText.setText(newText);
Query Q = mDatabase.child("Recipees").orderByChild("cusine").startAt(newText).endAt("");
FirebaseRecyclerAdapter<ImageRetrieve, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ImageRetrieve, BlogViewHolder>(
ImageRetrieve.class,
R.layout.recipe_row,
BlogViewHolder.class,
Q
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, ImageRetrieve model, int position) {
viewHolder.setCusine(model.getCusine());
viewHolder.setCatagory(model.getCatagory());
viewHolder.setRecipe(model.getRecipe());
viewHolder.setUrl(getApplicationContext(), model.getUrl());
}
};
mRecipeList.setAdapter(firebaseRecyclerAdapter);
return false;
}
});
return true;
}
Try this it may help :
Query Q = mDatabase.child("Recipees").orderByChild("cusine").startAt(newText).endAt(newText+"\uf8ff");
So that mean query have wrong.
Try This:-->
mDatabase.child("Recipees").orderByChild("cusine").equalTo(newText);
Try the code below, it might be helpful:
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
// if searchView is not empty
if(!text.isEmpty()){
// call seearch method if user starts typing
search(text);
}
//else
else{
// set TextField empty
search("");
}
return true;
}
});
// method to perform search
private void search(String newText)
{
ArrayList<> searchList = new ArrayList<>();
// creates a query to initiate the search
Query Q = mDatabase.child("Recipees")
.orderByChild("cusine").startAt(newText).endAt(newText + "\uf8ff");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
//clears the arrayList
searchList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
final ImageRetrieve imageRetrieve =
snapshot.getValue(ImageRetrieve.class);
//adds the rooms searched to the arrayList
searchList.add(imageRetrieve);
}
//NB: recyclerView is the view object in your activity that populates data
FirebaseRecyclerAdapter firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter(yourActivity.this,searchList);
recyclerView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// display message if error occurs
}
});
}
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.