Hello I implemented a search but when trying to filter nothing happens someone knows some way to make it work correctly, I can't identify where it is wrong. Thanks in advance. any help is welcome.
Below are codes of my activity where is the recycler view. And model contacts.
I really don't know what I'm doing wrong.
Contacts Model
public class Contacts {
public String name, status, image;
public Contacts()
{
}
public Contacts(String name, String status, String image) {
this.name = name;
this.status = status;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
My Activity
public class FindFriendsActivity extends AppCompatActivity
{
private Toolbar mToolbar;
private RecyclerView FindFriendsRecyclerList;
private DatabaseReference UsersRef;
private SearchView searchView;
private Query query;
private FirebaseRecyclerOptions<ColorSpace.Model> options;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_friends);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
FindFriendsRecyclerList = (RecyclerView) findViewById(R.id.find_friends_recycler_list);
FindFriendsRecyclerList.setLayoutManager(new LinearLayoutManager(this));
mToolbar = (Toolbar) findViewById(R.id.find_friends_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Find Friends");
searchView = findViewById(R.id.materialSearchPrincipal);
}
#Override
protected void onStart()
{
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new Builder<Contacts>()
.setQuery(UsersRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, FindFriendViewHolder> adapter =
new FirebaseRecyclerAdapter<Contacts, FindFriendViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull FindFriendViewHolder holder, final int position, #NonNull Contacts model)
{
holder.userName.setText(model.getName());
holder.userStatus.setText(model.getStatus());
Picasso.get().load(model.getImage()).placeholder(R.drawable.profile_image).into(holder.profileImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String visit_user_id = getRef(position).getKey();
Intent profileIntent = new Intent(FindFriendsActivity.this, ProfileActivity.class);
profileIntent.putExtra("visit_user_id", visit_user_id);
startActivity(profileIntent);
}
});
}
#NonNull
#Override
public FindFriendViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
FindFriendViewHolder viewHolder = new FindFriendViewHolder(view);
return viewHolder;
}
};
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
private void fetch(Query query) {
FirebaseRecyclerOptions<Contacts> options =
new Builder<Contacts>()
.setQuery(query, Contacts.class)
.build();
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("User").orderByChild("name").equalTo(s);
if(s.equals("")){
query = FirebaseDatabase.getInstance()
.getReference()
.child("name");
}
fetch(query);
return false;
}
});
FindFriendsRecyclerList.setAdapter(adapter);
adapter.startListening();
}
public static class FindFriendViewHolder extends RecyclerView.ViewHolder
{
TextView userName, userStatus;
CircleImageView profileImage;
public FindFriendViewHolder(#NonNull View itemView)
{
super(itemView);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
profileImage = itemView.findViewById(R.id.users_profile_image);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.options_menu, menu);
MenuItem item = menu.findItem(R.id.menuPesquisa);
return true;
}
}
You need a new reference to adapter in fetch() method, because after every search the returned item count is changing. That's why in my example I have done like this in the fetch() method:
adapter = new CustomFirebaseRecylerAdapter<Model, CustomFirebaseRecylerAdapter.ViewHolder>(options);
adapter.startListening();
recyclerView.setAdapter(adapter);
try creating a new adapter instance in the fetch() method and then setting up the following:
adapter.startListening();
FindFriendsRecyclerList.setAdapter(adapter);
Related
I'm a cs student and now I have to write an app using firebase and android studio for a project.
I'm so new in this and now I faced a problem. in my FindFriends activity when i run my app and then search for any user it starts to show all the users(Even deleted one) and not the one I searched in the box.
also it says E/RecyclerView: No adapter attached; skipping layout and I couldn't find why?
Here is my FindFriends Activity:
{
private Toolbar mToolbar;
private ImageButton SearchButton;
private EditText SearchInputText; //searchField
private RecyclerView SearchResultList;
private DatabaseReference allUsersDatabaseRef;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_friends);
allUsersDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Users");
mToolbar = (Toolbar) findViewById(R.id.find_friends_app_bar_layout);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Search For Friends");
SearchResultList = (RecyclerView) findViewById(R.id.search_result_list);
SearchResultList.setHasFixedSize(true);
SearchResultList.setLayoutManager(new LinearLayoutManager(this));
SearchButton = (ImageButton) findViewById(R.id.search_for_friends_button);
SearchInputText = (EditText) findViewById(R.id.search_box_input);
SearchButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String searchBoxInput = SearchInputText.getText().toString();
SearchForFriends(searchBoxInput);
}
});
}
private void SearchForFriends(String searchBoxInput)
{
Toast.makeText(this, "Searching...", Toast.LENGTH_LONG).show();
Query searchForFriendsQuery = allUsersDatabaseRef.orderByChild("fullname")
.startAt(searchBoxInput).endAt(searchBoxInput + "\uf8ff");
FirebaseRecyclerOptions<FindFriends> option =
new FirebaseRecyclerOptions.Builder<FindFriends>()
.setQuery(allUsersDatabaseRef, FindFriends.class)
.build();
FirebaseRecyclerAdapter<FindFriends, FindFriendsViewHolder> firebaseRecyclerAdapter
= new FirebaseRecyclerAdapter<FindFriends, FindFriendsViewHolder>(option)
{
#Override
protected void onBindViewHolder(#NonNull FindFriendsViewHolder holder, final int position, #NonNull FindFriends model)
{
holder.setFullname(model.getFullname());
holder.setStatus(model.getStatus());
holder.setProfileimage(getApplicationContext(), model.getProfileimage());
holder.mView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String visit_user_id = getRef(position).getKey();
Intent profileIntent = new Intent(FindFriendsActivity.this, PersonProfileActivity.class);
profileIntent.putExtra("visit_user_id", visit_user_id);
startActivity(profileIntent);
}
});
}
#NonNull
#Override
public FindFriendsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.all_users_display_layout,parent, false);
FindFriendsViewHolder viewHolder = new FindFriendsViewHolder(view);
return viewHolder;
}
};
firebaseRecyclerAdapter.startListening();
SearchResultList.setAdapter(firebaseRecyclerAdapter);
}
public class FindFriendsViewHolder extends RecyclerView.ViewHolder
{
View mView;
public FindFriendsViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setProfileimage(Context ctx ,String profileimage)
{
CircleImageView myImage = (CircleImageView) mView.findViewById(R.id.all_users_profile_image);
Picasso.get().load(profileimage).placeholder(R.drawable.profile).into(myImage);
}
public void setFullname(String fullname)
{
TextView myName = (TextView) mView.findViewById(R.id.all_users_full_name);
myName.setText(fullname);
}
public void setStatus(String status)
{
TextView myStatus = (TextView) mView.findViewById(R.id.all_users_Status);
myStatus.setText(status);
}
}
}
also my FindFriends class:
package com.example.pingoo;
public class FindFriends
{
public String profileimage, fullname, status;
public FindFriends()
{
}
public FindFriends(String profileimage, String fullname, String status) {
this.profileimage = profileimage;
this.fullname = fullname;
this.status = status;
}
public String getProfileimage() {
return profileimage;
}
public void setProfileimage(String profileimage) {
this.profileimage = profileimage;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
I will appreciate if anyone could help me with this because it's sooo nesseccary for me
The searchForFriendsQuery looks fine to me at first glance. But that's not what you're passing to the adapter, as you're still using allUsersDatabaseRef there:
.setQuery(allUsersDatabaseRef, FindFriends.class)
That should probably be:
.setQuery(searchForFriendsQuery, FindFriends.class)
I'm retrieving data from firebase and trying to display that in recycler view, every thing is fine but it only shows one item in the list (there are total 14 items)
comment if you do not understand the question
This is my main activity where i get datasnapshots from firebase
public class cakes_activity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<Data> listdata;
private DatabaseReference mref;
private NorthAdaptor north;
private final Context context = this;
public int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cakes);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
EditText editText = (EditText) findViewById(R.id.editText) ;
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//FIREBASE
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mref= FirebaseDatabase.getInstance().getReference("Cakes");
mref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Data data = dataSnapshot.getValue(Data.class);
listdata = new ArrayList<>();
listdata.add(data);
north = new NorthAdaptor(context,listdata);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.hasFixedSize();
recyclerView.setAdapter(north);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
and the following code is my adaptor class:
public class NorthAdaptor extends RecyclerView.Adapter<NorthAdaptor.NorthHolder> {
private LayoutInflater inflater;
ArrayList<Data> northy;
public NorthAdaptor(Context context,ArrayList<Data> northy)
{
inflater=LayoutInflater.from(context);
this.northy=northy;
}
public NorthHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_item,parent,false);
NorthHolder holder = new NorthHolder(view);
return holder;
}
#Override
public void onBindViewHolder(NorthHolder holder, int position) {
holder.text2.setText(northy.get(position).getName());
holder.text3.setText("₹."+northy.get(position).getRS());
}
#Override
public int getItemCount() {
return northy.size();
}
class NorthHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView text,text2,text3;
ImageView img;
private final Context context;
public NorthHolder(View itemview)
{
super(itemview);
context = itemView.getContext();
CardView card = (CardView) itemView.findViewById(R.id.card);
text3=(TextView)itemView.findViewById(R.id.Rs);
text2 = (TextView) itemView.findViewById(R.id.itemtext2);
img = (ImageView) itemView.findViewById(R.id.itemimage);
card.setOnClickListener(this);
}
#Override
public void onClick(View view){
Toast.makeText(
cakes_activity.this,
"Your message here",
Toast.LENGTH_SHORT
).show();
}
}
}
this is my java class to store the data received from firebase
public class Data {
private String ID,Name,image,RS;
public Data(){
}
public Data(String ID, String Name, String image, String RS) {
this.ID = ID;
this.Name = Name;
this.image= image;
this.RS = RS;
}
public String getId() {
return ID;
}
public String getRS() {
return RS;
}
public void setId(String id) {
this.ID = id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getimage() {
return image;
}
public void setImg(String image) {
this.image = image;
}
}
listdata = new ArrayList<>();
north = new NorthAdaptor(context,listdata);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.hasFixedSize();
recyclerView.setAdapter(north);
you need to write this code in onCreate instead of onchildadded
I have recyclerview recieving data from firebase and i want to make last item uploaded to be first item in the list.I'm using GridLayoutManager and want to display a pic with a text, all of this work fine but i want to make them in order like instagram, does any one know something like that ?
Here is my code
public class ItemsUser extends Fragment {
private View mMainView;
private RecyclerView mUsersList;
private String user_id;
private DatabaseReference mUserDatabase;
private FirebaseRecyclerAdapter<ItemRecycleview,UserRecycleView> firebaseRecyclerAdapter;
private DatabaseReference mDatabaseReference;
private FirebaseListAdapter<ItemRecycleview> firebaseListAdapter;
public ItemsUser() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mMainView = inflater.inflate(R.layout.fragment_items_user, container, false);
mUsersList = (RecyclerView) mMainView.findViewById(R.id.recyclerView_profile);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(new GridLayoutManager(getActivity(),3));
ProfileUser activity = (ProfileUser) getActivity();
user_id = activity.getMyData();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users_photos").child(user_id);
mUserDatabase.keepSynced(true);
return mMainView;
}
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ItemRecycleview, UserRecycleView>(
ItemRecycleview.class,
R.layout.recycleview_item,
UserRecycleView.class,
mUserDatabase
) {
#Override
protected void populateViewHolder(UserRecycleView viewHolder, ItemRecycleview model, int position) {
viewHolder.setImageName(model.getImageName());
viewHolder.setImageURL(model.getImageURL(),getContext());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String key = firebaseRecyclerAdapter.getRef(mUsersList.getChildLayoutPosition(v)).getKey();
Intent imageIntent = new Intent(getActivity(), ImageActivity.class);
imageIntent.putExtra("imageKey",key);
imageIntent.putExtra("user_id",user_id);
startActivity(imageIntent);
}
});
}
};
mUsersList.setAdapter(firebaseRecyclerAdapter);
}
public static class UserRecycleView extends RecyclerView.ViewHolder {
View mView;
public UserRecycleView(View itemView) {
super(itemView);
mView = itemView;
}
public void setImageName(String imageName){
TextView userNameView = (TextView) mView.findViewById(R.id.ImageNameTextView);
userNameView.setText(imageName);
}
public void setImageURL(final String imageURL,final Context ctx){
final ImageView userImageView = (ImageView) mView.findViewById(R.id.imageView);
Picasso.with(ctx).load(imageURL).networkPolicy(NetworkPolicy.OFFLINE).into(userImageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(imageURL).into(userImageView);
}
});
}
}
}
and this is ItemRecyclerview:
public class ItemRecycleview {
public String imageName;
public String imageURL;
public ItemRecycleview(){
}
public ItemRecycleview(String imageName, String imageURL) {
this.imageName = imageName;
this.imageURL = imageURL;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
}
hey guys i just found the answer :D
all you need to do is to add this method in firebaseRecyclerAdapter
here it's:
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ItemRecycleview, UserRecycleView>(
ItemRecycleview.class,
R.layout.recycleview_item,
UserRecycleView.class,
mUserDatabase
) {
#Override
public ItemRecycleview getItem(int position) {
return super.getItem(getItemCount() - 1 - position);
}
#Override
protected void populateViewHolder(UserRecycleView viewHolder, ItemRecycleview model, int position) {
viewHolder.setImageName(model.getImageName());
viewHolder.setImageURL(model.getImageURL(),getContext());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String key = firebaseRecyclerAdapter.getRef(mUsersList.getChildLayoutPosition(v)).getKey();
Intent imageIntent = new Intent(getActivity(), ImageActivity.class);
imageIntent.putExtra("imageKey",key);
imageIntent.putExtra("user_id",user_id);
startActivity(imageIntent);
}
});
}
};
and that will make it done
Have you tried using setReverseLayout() method to make first element last in the list
GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(),3);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mUsersList.setLayoutManager(mLayoutManager);
So, i'm trying to create app that shows list of writers(image,name,bio) and the thing is that I have problem implementing search functionality. The guide for working with RecyclerView I used is here.
Code: MainActivity
public class MainActivity extends AppCompatActivity {
private FirebaseFirestore db;
private FirestoreRecyclerAdapter adapter;
private LinearLayoutManager linearLayoutManager;//nodrosina kada veida recycle attelos
private List<Klasiki> list;
#BindView(R.id.imageRecycleView)
RecyclerView klasikiList; //tas pats kas find by ID
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
linearLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
klasikiList.setLayoutManager(linearLayoutManager);
db = FirebaseFirestore.getInstance();
getList();
}
//atgriez ierakstus no datubazes un nodrosina atteloshanu recycle view
private void getList(){
Query query = db.collection("klasiki");
FirestoreRecyclerOptions<Klasiki> response = new FirestoreRecyclerOptions.Builder<Klasiki>()
.setQuery(query, Klasiki.class)
.build();
adapter = new FirestoreRecyclerAdapter<Klasiki, klasikiHolder>(response) {
#Override
protected void onBindViewHolder(final klasikiHolder holder, int position, final Klasiki model) {
holder.name.setText(model.getName());
holder.shortBio.setText(model.getShortBio());
Glide.with(getApplicationContext()).load(model.getImage()).into(holder.image);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, BioActivity.class);
//Parnes mainigos uz bio activity
Bundle extras = new Bundle();
extras.putString("imageInfo", model.getImage());
extras.putString("nameInfo", model.getName());
extras.putString("bioInfo", model.getFullBio());
intent.putExtras(extras);
startActivity(intent);
}
});
}
#Override
public klasikiHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.klasiki_layout, parent, false);
return new klasikiHolder(view);
} //nodrosina jauna ieraksta returnu
#Override
public void onError(FirebaseFirestoreException e) {
Log.e("error", e.getMessage());
}
};
adapter.notifyDataSetChanged();
klasikiList.setAdapter(adapter);
}
//izsauc mainigos
public class klasikiHolder extends RecyclerView.ViewHolder{
#BindView(R.id.name)
TextView name;
#BindView(R.id.klasikiImage)
ImageView image;
#BindView(R.id.shortBio)
TextView shortBio;
public klasikiHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
Constructor
public class Klasiki {
private String Name;
private String Image;
private String shortBio;
private String fullBio;
public Klasiki(){}
public Klasiki(String name, String image, String shortBio, String fullBio) {
Name = name;
Image = image;
this.shortBio = shortBio;
this.fullBio = fullBio;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getShortBio() {
return shortBio;
}
public void setShortBio(String shortBio) {
this.shortBio = shortBio;
}
public String getFullBio() {
return fullBio;
}
public void setFullBio(String fullBio) {
this.fullBio = fullBio;
}
}
I think I have to use other RecyclerViewthan FirestoreRecyclerOptions but i'm not sure, really new to android programming. :)
UPDATE:
So I made something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
// Retrieve the SearchView and plug it into SearchManager
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
querySearch = db.collection("klasiki").whereEqualTo("name", text);
if (!text.trim().isEmpty()){
getList(querySearch);
adapter.startListening();
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.trim().isEmpty()){
getList(queryFinal);
adapter.startListening();
}
return false;
}
});
return true;
}
Probably not the best solution, but now I have different problem.. Is there a way to make sub string searches for Firestore? Like db.collection("klasiki").whereEqualTo("name", Ja); And it shows names where it starts with Ja.
In order to search for a writter you need to create a Query.
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query nameOfTheWritterQuery = rootRef.collection("writters")
.whereEqualTo("writterName", "Eidemanis Roberts");
Seeing your Klasiki class, I need to tell you that you do not respect Java Naming Conventions rules for all your fields and you can have problems while deserializing. Your model class should look like this:
public class Klasiki {
private String name, image, shortBio, fullBio;
public Klasiki( ){}
public Klasiki(String name, String image, String shortBio, String fullBio) {
this.name = name;
this.image = image;
this.shortBio = shortBio;
this.fullBio = fullBio;
}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getImage() {return image;}
public void setImage(String image) {this.image = image;}
public String getShortBio() {return shortBio;}
public void setShortBio(String shortBio) {this.shortBio = shortBio;}
public String getFullBio() {return fullBio;}
public void setFullBio(String fullBio) {this.fullBio = fullBio;}
}
Please see the fields now. All start will small letter.
This is SearchActivity.java
public class SearchActivity extends AppCompatActivity
{
/*UI*/
private EditText mSearchText;
private Button mSearchBtn;
private Toolbar mSearchToolbar;
private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;
private String value;
private TextWatcher tw;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mSearchText = (EditText)findViewById(R.id.activity_search_search_text);
mSearchBtn = (Button)findViewById(R.id.activity_search_search_btn);
mSearchToolbar = (Toolbar)findViewById(R.id.activity_search_toolbar);
setSupportActionBar(mSearchToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
mSearchBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
value = mSearchText.getText().toString();
Toast.makeText(SearchActivity.this, "value test 1: " + value, Toast.LENGTH_LONG).show();
searchText(value);
}
});
}
private void searchText(final String value)
{
Toast.makeText(SearchActivity.this, "value test 2: " + value, Toast.LENGTH_LONG).show();
mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager())
{
private final Fragment[] mFragments = new Fragment[]
{
new FragmentSearch(value)
};
#Override
public Fragment getItem(int position)
{
return mFragments[position];
}
#Override
public int getCount()
{
return mFragments.length;
}
};
mViewPager = (ViewPager) findViewById(R.id.activity_search_view_pager);
mViewPager.setAdapter(mPagerAdapter);
}
}
This is FragmentSearch.java
public class FragmentSearch extends MainFragment
{
public String value;
public FragmentSearch(String value)
{
this.value = value;
}
#Override
public Query getQuery(DatabaseReference databaseReference)
{
Toast.makeText(getActivity().this, "value test 3: " + value, Toast.LENGTH_LONG).show();
Query postsQuery = databaseReference.child("Post").orderByChild("title").equalTo(value);
return postsQuery;
}
}
This is MainFragment.java
public abstract class MainFragment extends Fragment
{
private DatabaseReference mDatabase;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
private RecyclerView mRecycler;
private LinearLayoutManager mManager;
public MainFragment()
{
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_all_posts, container, false);
mDatabase = FirebaseDatabase.getInstance().getReference();
mRecycler = (RecyclerView)rootView.findViewById(R.id.messages_list);
mRecycler.setHasFixedSize(true);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
Query postsQuery = getQuery(mDatabase);
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
PostViewHolder.class, postsQuery)
{
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position)
{
final DatabaseReference postRef = getRef(position);
final String postKey = postRef.getKey();
viewHolder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// Intent intent = new Intent(getActivity(), PostDetailActivity.class);
// intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
// startActivity(intent);
}
});
if(model.stars.containsKey(getUid()))
{
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_24);
}
else
{
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
}
viewHolder.bindToPost(model, new View.OnClickListener()
{
#Override
public void onClick(View starView)
{
DatabaseReference globalPostRef = mDatabase.child("Post").child(postRef.getKey());
DatabaseReference userPostRef = mDatabase.child("UserPost").child(model.uid).child(postRef.getKey());
onStarClicked(globalPostRef);
onStarClicked(userPostRef);
}
});
}
};
mRecycler.setAdapter(mAdapter);
}
private void onStarClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.stars.containsKey(getUid())) {
// Unstar the post and remove self from stars
p.starCount = p.starCount - 1;
p.stars.remove(getUid());
} else {
// Star the post and add self to stars
p.starCount = p.starCount + 1;
p.stars.put(getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
}
});
}
#Override
public void onDestroy()
{
super.onDestroy();
if (mAdapter != null)
{
mAdapter.cleanup();
}
}
public String getUid()
{
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public abstract Query getQuery(DatabaseReference databaseReference);
}
This is PostViewHolder.java
public class PostViewHolder extends RecyclerView.ViewHolder
{
public TextView titleView;
public TextView authorView;
public ImageView starView;
public TextView numStarsView;
public TextView bodyView;
public PostViewHolder(View itemView)
{
super(itemView);
titleView = (TextView) itemView.findViewById(R.id.post_title);
authorView = (TextView) itemView.findViewById(R.id.post_author);
starView = (ImageView) itemView.findViewById(R.id.star);
numStarsView = (TextView) itemView.findViewById(R.id.post_num_stars);
bodyView = (TextView) itemView.findViewById(R.id.post_body);
}
public void bindToPost(Post post, View.OnClickListener starClickListener)
{
titleView.setText(post.title);
authorView.setText(post.author);
numStarsView.setText(String.valueOf(post.starCount));
bodyView.setText(post.body);
starView.setOnClickListener(starClickListener);
}
}
This is Post.java
#IgnoreExtraProperties
public class Post
{
public String uid;
public String author;
public String title;
public String body;
public int starCount = 0;
public String type;
public Map<String, Boolean> stars = new HashMap<>();
public Post()
{
}
public Post(String uid, String author, String title, String body, String type)
{
this.uid = uid;
this.author = author;
this.title = title;
this.body = body;
this.type = type;
}
#Exclude
public Map<String, Object> toMap()
{
HashMap<String, Object> result = new HashMap<>();
result.put("uid", uid);
result.put("author", author);
result.put("title", title);
result.put("body", body);
result.put("starCount", starCount);
result.put("stars", stars);
result.put("type", type);
return result;
}
}
Thank you so much for reading. I created a program to search title of the posts. When I type title in the EditText then press Search button, my toast1 test, toast2 test, and toast3 test give correct and same value and it successfully lists what I want with Query. But the problem is that when I type different text in EditText after deleting the previous text then press enter, toast3 test(in FragmentSearch.java) stays the same and does not change value. So, it just gives the previous result, not changed result. Can anyone assist me with this? Thank you!
The problem is that you only change the value on the FragmentSearch constructor. And this constructor is only called once, and not when you press Enter.
You should change your getQuery method to have this value as a parameter.
On your MainFragment.java:
public abstract Query getQuery(DatabaseReference databaseReference, String value);
On your FragmentSearch.java:
#Override
public Query getQuery(DatabaseReference databaseReference, String value)
{
this.value = value;
Toast.makeText(getActivity().this, "value test 3: " + value, Toast.LENGTH_LONG).show();
Query postsQuery = databaseReference.child("Post").orderByChild("title").equalTo(value);
return postsQuery;
}