SearchData Method resets query? Firebase Database Android - java

In general, the thing is, I have three fragments. In the second snippet, it gets the data provided, here's the code.
1)MyPostFragment.class
public class MyPostsFragment extends PostListFragment {
public MyPostsFragment() {}
#Override
public Query getQuery(DatabaseReference databaseReference) {
return databaseReference.child("songsDB")
.orderByChild("stars/" + getUid())
.equalTo(true);
}
2)PostListFragment
public abstract class PostListFragment extends Fragment {
private DatabaseReference mDatabase;
private FirebaseRecyclerAdapter mAdapter;
private RecyclerView mRecycler;
private Activity mActivity;
Query mRef;
SearchView searchView;
LinearLayoutManager mManager;
FirebaseDatabase mFirebaseDatabase;
public PostListFragment() {
}
#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);
mRecycler = rootView.findViewById(R.id.messages_list);
mRecycler.setHasFixedSize(true);
mDatabase = FirebaseDatabase.getInstance().getReference();
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
// Set up Layout Manager, reverse layout
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
Query postsQuery = getQuery(mDatabase);
ShowData(postsQuery);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
SearchData(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//Filter as you type
SearchData(newText);
return false;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
private FirebaseRecyclerAdapter getMAdapter(Query query){
mActivity = getActivity();
final Dialog mDialog = new Dialog(mActivity, R.style.NewDialog);
mDialog.addContentView(
new ProgressBar(mActivity),
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
);
mDialog.setCancelable(true);
mDialog.show();
FirebaseRecyclerOptions<Post> options = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(query, Post.class)
.build();
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options) {
#Override
protected void onBindViewHolder(PostViewHolder viewHolder, int position, final Post model) {
final DatabaseReference postRef = getRef(position);
// Determine if the current user has liked this post and set UI accordingly
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);
}
if (!TextUtils.isEmpty(model.kzSongytblink))
viewHolder.mImage.setImageResource(R.drawable.on_line_logo);
else viewHolder.mImage.setImageResource(R.drawable.off_line_logo);
// Bind Post to ViewHolder, setting OnClickListener for the star button
viewHolder.bindToPost(model, new View.OnClickListener() {
#Override
public void onClick(View starView) {
// Need to write to both places the post is stored
DatabaseReference globalPostRef = mDatabase.child("songsDB").child(postRef.getKey());
// Run two transactions
onStarClicked(globalPostRef);
}
});
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, PostDetailActivity.class);
intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postRef.getKey());
startActivity(intent);
}
});
}
#Override
public PostViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
return new PostViewHolder(inflater.inflate(R.layout.item_post, viewGroup, false));
}
};
return mAdapter;
}
public void ShowData(Query postsQuery) {
mAdapter=getMAdapter(postsQuery);
mRecycler.setAdapter(mAdapter);
}
public void SearchData(String searchText){
//SearchData
mFirebaseDatabase = FirebaseDatabase.getInstance();
mRef = FirebaseDatabase.getInstance().getReference("songsDB");
Query postsQuery= mRef.orderByChild("kzSongTitle").startAt(searchText).endAt(searchText + "\uf8ff");
mAdapter=getMAdapter(postsQuery);
mRecycler.setAdapter(mAdapter);
}
#Override
public void onStart() {
super.onStart();
if (mAdapter != null) {
mAdapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
if (mAdapter != null) {
mAdapter.stopListening();
}
}
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) {
Log.d("postTransaction", "onComplete:" + dataSnapshot.getKey());
}
});
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public abstract Query getQuery(DatabaseReference databaseReference);
}
If you remove the SearchData method, everything is loaded normally, but the searching is not working and I need it.
Without method SearchData :
If you don't remove SearchData load all data from database in all fragments.
I need to fix it, but I don't know how. Help me please.
With method SearchData :

Related

RecyclerView disappearing after switching between fragments on a particular Activity

The problem I have been facing with the development is that there is a recyclerview inside my fragment which gets disappeared after I switch between two fragments on a particular activity. On the first time when the fragment loads everything works fine but afterwards I don't understand what goes wrong. I had tried to refer to various ways that people had posted over github like notifyDatasetChanged, etc. But nothing seems to work. I would appreciate if someone could help me out with this issue.
So here are my classes.
The ProfileFragment.java :
public class ProfileFragment extends Fragment {
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
RecyclerView itemRecycler;
List<ModelProfile> modelProfiles;
AdapterProfile adapterProfile;
String storagePath= "Users_Profile_Cover_Image/-";
ImageView avatarIv,dp;
CardView card,cardArrow;
TextView nameTv, emailTv, phoneTv;
Button logout,update;
ExtendedFloatingActionButton fab;
ProgressDialog pd;
//..
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view= inflater.inflate(R.layout.fragment_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user= firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference= getInstance().getReference();
loadItems();
return view;
}
private void loadItems() {
//Problem could be here
GridLayoutManager layoutManager= new GridLayoutManager(getContext(),3);
itemRecycler.setHasFixedSize(true);
itemRecycler.setLayoutManager(layoutManager);
itemRecycler.setVisibility(View.VISIBLE);
CollectionReference ref =FirebaseFirestore.getInstance().collection("All_Posts");
com.google.firebase.firestore.Query query = ref.whereEqualTo("uid",uid);
FirestoreRecyclerOptions<ModelProfile> options = new FirestoreRecyclerOptions.Builder<ModelProfile>()
.setQuery(query,ModelProfile.class).build();
adapterProfile = new AdapterProfile(options,getActivity());
itemRecycler.setAdapter(adapterProfile);
adapterProfile.startListening();
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
return;
}
assert value != null;
Log.i("Size",String.valueOf(value.getDocuments().size()));
if (value.getDocuments().size() > 0) { // List is populated
card.setVisibility(View.GONE);
cardArrow.setVisibility(View.GONE);
} else { // List is empty
card.setVisibility(View.VISIBLE);
cardArrow.setVisibility(View.VISIBLE);
}
}
});
}
//
// #Override
// public void onStart() {
// super.onStart();
// adapterProfile.startListening();
// }
//
//
//
// #Override
// public void onStop() {
// super.onStop();
// adapterProfile.stopListening();
// }
#Override
public void onResume() {
super.onResume();
adapterProfile.startListening();
}
}
Adapter:-
public class AdapterProfile extends FirestoreRecyclerAdapter<ModelProfile,AdapterProfile.MyHolder> {
Context context;
public String im;
public AdapterProfile(#NonNull FirestoreRecyclerOptions<ModelProfile> options, Activity Context) {
super(options);
context = Context;
}
#Override
protected void onBindViewHolder(#NonNull MyHolder holder, int position, #NonNull ModelProfile model) {
String uid = model.getUid();
String uEmail =model.getuEmail();
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//..
}
class MyHolder extends RecyclerView.ViewHolder{
//..
}
Activity on which Fragment switching takes place
public class LandingActivity extends AppCompatActivity {
FirebaseAuth firebaseAuth;
DatabaseReference userDbRef;
FirebaseUser user;
String uid,dp;
ChipNavigationBar chipNavigationBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new InventoryFragment()).commit();
bottomMenu();
}
private void bottomMenu() {
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
//problem could be here as well.........
#Override
public void onItemSelected(int i) {
Fragment fragment=null;
switch(i) {
case R.id.bottom_nav_2:
fragment = new CltFragment();
break;
case R.id.bottom_nav_3:
fragment = new MaceFragment();
break;
case R.id.bottom_nav_profile:
fragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
}
private void checkUserStatus()
{
FirebaseUser user= firebaseAuth.getCurrentUser();
if(user !=null)
{
uid=user.getUid();
}
else
{
startActivity(new Intent(LandingActivity.this,MainActivity.class));
finish();
}
}
#Override
public void onResume() {
//Problem could be here
super.onResume();
Intent intent = getIntent();
String frag = "";
if(intent.hasExtra("frag")) {
frag = intent.getExtras().getString("frag");
}
else
{
//..
}
switch(frag)
{
//..
case "ProfileFragment":
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ProfileFragment()).commit();
chipNavigationBar.setItemSelected(R.id.bottom_nav_profile,true);
break;
}
}
}
Thanks for having looked at my Problem!
Try using this
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,new InventoryFragment()).commit();
Instead of this
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new InventoryFragment()).commit();

Firebase firestore Recycle View in fragment. How to do delete on slide

I'm working on my school project with Firebase firestore and firebase Auth. It's something like a Kanban app.
My intend is to add delete documents from database while slide, and move documents to another catalog while sliding left-right. My main activity (TestActivity) is tabbed, so I want the deletion or moving to depend on direction and actual tab. Each tab have own Recycle View. You know: To do, In progress, Done.
I tried to follow Code Flow: https://www.youtube.com/watch?v=ub6mNHWGVHw&list=PLrnPJCHvNZuAXdWxOzsN5rgG2M4uJ8bH1
but my project need fragments, and with them, his "NoteAdapter" doesn't work. I found this tutorial: https://www.youtube.com/watch?v=FFHuYcB3YnU
and used it to place the adapter in right fragment.
Everything works until I want to do something with the firebase documents. This doesn't work at all or I just don't have idea where to place it:
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
adapter.deleteItem(viewHolder.getAdapterPosition());
}
}).attachToRecyclerView(recyclerView);
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
Im using firebase and fragments first time.
Here comes some of my code: TestActivity (my main, I have also a drawer with user info and signout button, but this button which doesn't work,too):
public class TestActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private TabLayout tabLayout;
private ViewPager viewPager;
private SectionsPagerAdapter adapter;
private DrawerLayout drawer;
FirebaseAuth mAuth;
FirebaseUser currentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Toolbar toolbar = findViewById(R.id.toolbar); // toolbar staje sie action bar
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
updateNavHeader();
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tabs);
adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.AddFragment(new TodoFragment(), "To Do");
adapter.AddFragment(new InprogressFragment(), "In Progress");
adapter.AddFragment(new DoneFragment(), "Done");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.add_todo);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Add new item", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
updateUI();
}
});
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
// po zalogowaniu dane w drawer sie zmienia
public void updateNavHeader() {
NavigationView navigationView =(NavigationView) findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
TextView navUserName = headerView.findViewById(R.id.nav_username);
TextView navUserEmail = headerView.findViewById(R.id.nav_useremail);
ImageView userAvatar = headerView.findViewById(R.id.nav_useravatar);
navUserName.setText(currentUser.getDisplayName());
navUserEmail.setText(currentUser.getEmail());
if (currentUser.getPhotoUrl() != null) {
Glide.with(this).load(currentUser.getPhotoUrl()).into(userAvatar);
} else {
Glide.with(this).load(R.drawable.userphoto).into(userAvatar);
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
if (item.getItemId() == R.id.nav_signout) {
FirebaseAuth.getInstance().signOut();
Intent loginActivity = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(loginActivity);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void updateUI() {
Intent NewActivity = new Intent(getApplicationContext(), NewActivity.class);
startActivity(NewActivity);
finish();
}
}
TodoFragment:
public class TodoFragment extends Fragment {
private View v;
private RecyclerView recyclerView;
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference TodoRef= db.collection("ToDo");
FirebaseAuth mAuth;
String Uemail;
public TodoFragment() {
// Required empty public constructor
}
public static TodoFragment newInstance() {
TodoFragment fragment = new TodoFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
Query q =TodoRef.whereEqualTo("email", Uemail);
FirestoreRecyclerOptions options=new FirestoreRecyclerOptions.Builder<Item>().setQuery(q, Item.class).build();
FirestoreRecyclerAdapter<Item, ItemViewHolder>adapter= new FirestoreRecyclerAdapter<Item, ItemViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ItemViewHolder itemViewHolder, int i, #NonNull Item item) {
itemViewHolder.textViewItem.setText(item.getTextitem());
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
ItemViewHolder viewHolder = new ItemViewHolder(v);
return viewHolder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
public static class ItemViewHolder extends RecyclerView.ViewHolder{
TextView textViewItem;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
textViewItem = itemView.findViewById(R.id.item_text);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_todo, container, false);
recyclerView = v.findViewById(R.id.recycler_view_todo);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth=FirebaseAuth.getInstance();
Uemail= mAuth.getCurrentUser().getEmail();
return v;
}
}
My Item class:
public class Item {
private String textitem;
private String email;
public Item(){
//needed
}
public Item(String textitem, String email) {
this.email=email;
this.textitem=textitem;
}
public String getTextitem() {
return textitem;
}
public void setTextitem(String textitem) {
this.textitem = textitem;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
And my Section Pager Adapter:
public SectionsPagerAdapter( FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
#Override
public int getCount() {
return titles.size();
}
public void AddFragment(Fragment fragment, String title ){
fragments.add(fragment);
titles.add(title);
}
}
I did my best to find the solution on my own, but I apparently failed.
EDIT:
I finally found out how to handle it.
I moved adapter to independent class again, but with little changes in both fragments and adapter.
My adapter now: (with moving and deleting docs in Firestore)
public class ItemAdapter extends FirestoreRecyclerAdapter<Item, ItemAdapter.NoteHolder> {
public ItemAdapter(#NonNull FirestoreRecyclerOptions<Item> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull NoteHolder holder, int position, #NonNull Item model) {
holder.textViewTitle.setText(model.getTextitem());
}
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,
parent, false);
return new NoteHolder(v);
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
Log.d("Firestore", "DocumentSnapshot successfully deleted!");
}
public void moveItem(int position, CollectionReference ColRef) {
DocumentReference from= getSnapshots().getSnapshot(position).getReference();
DocumentReference to =ColRef.document();
moveFirestoreDocument( from, to);
}
public void moveFirestoreDocument(final DocumentReference fromPath, final DocumentReference toPath) {
fromPath.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
toPath.set(document.getData())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("Firestore", "DocumentSnapshot successfully written!");
fromPath.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("Firestore", "DocumentSnapshot successfully deleted!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("Firestore", "Error deleting document", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("Firestore", "Error writing document", e);
}
});
} else {
Log.d("Firestore", "No such document");
}
} else {
Log.d("Firestore", "get failed with ", task.getException());
}
}
});
}
class NoteHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
public NoteHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.item_text);
}
}
}
And my Fragment now looks like this:
public class TodoFragment extends Fragment {
private View v;
private RecyclerView recyclerView;
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference TodoRef = db.collection("ToDo");
CollectionReference InProgRef = db.collection("InProgress");
ItemAdapter adapter;
FirebaseAuth mAuth;
String Uemail;
public TodoFragment() {
}
public static TodoFragment newInstance() {
TodoFragment fragment = new TodoFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_todo, container, false);
recyclerView = v.findViewById(R.id.recycler_view_todo);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth=FirebaseAuth.getInstance();
Uemail= mAuth.getCurrentUser().getEmail();
setUpRecyclerView(recyclerView);
return v;
}
private void setUpRecyclerView(RecyclerView recyclerView) {
Query q =TodoRef.whereEqualTo("email", Uemail);
FirestoreRecyclerOptions<Item> options = new FirestoreRecyclerOptions.Builder<Item>()
.setQuery(q, Item.class)
.build();
adapter = new ItemAdapter(options);
recyclerView.setAdapter(adapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT|ItemTouchHelper.UP) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int right = 8;
if(direction==right){
adapter.moveItem(viewHolder.getAdapterPosition(),InProgRef);
}else{
adapter.deleteItem(viewHolder.getAdapterPosition());
}
}
}).attachToRecyclerView(recyclerView);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
To sum up:
setUpRecyclerView function neded to get the right Recycler View as an argument, without it there was NullPointer Excepction all the time.
I made a mistake with wrong layout in inflaters, too
Hope it will be usefull for somebody.

Make detailed data from the recyclerview with intent in extends Fragment

Make detailed data from the recyclerview with intent in extends Fragment. what I know is using .putExtra, but I don't know how to write it in the fragment
public class NoteFragment extends Fragment {
private static final String TAG = NoteFragment.class.getSimpleName();
private RecyclerView recyclerView;
private NoteAdapter adapter;
private OnNoteFragmentListener listener;
public NoteFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_note, container, false);
recyclerView = view.findViewById(R.id.rv_notes);
FloatingActionButton fab = view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onAddButtonClicked();
}
}
});
adapter = new NoteAdapter(getContext());
recyclerView.setAdapter(adapter);
listener.onNotesLoad(adapter);
displayAsGrid();
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_note, menu);
super.onCreateOptionsMenu(menu, inflater);
}
private void displayAsList() {
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
adapter.setLayout(Constant.LAYOUT_MODE_LIST);
}
private void displayAsGrid() {
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(layoutManager);
adapter.setLayout(Constant.LAYOUT_MODE_GRID);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_show_list:
displayAsList();
return true;
case R.id.action_show_grid:
displayAsGrid();
return true;
case R.id.action_logout:
Log.i(TAG, "Logout click");
if (listener != null) {
listener.onLogoutMenuClicked();
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnNoteFragmentListener) {
listener = (OnNoteFragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ "must implement OnNoteFragmentListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
public interface OnNoteFragmentListener {
void onNotesLoad(NoteAdapter adapter);
void onAddButtonClicked();
void onLogoutMenuClicked();
}
}
I want the data contained in the recyclerview to be displayed on the new activity page according to the recyclerview that I clicked with the command .putExtra where do I put the code?
If you want to start activity, you need to use Intent. Parameters for intent has to be passed in your click listener. More information how to start activity is here Start activity
And here is example how to use listener in RecyclerView

Using SearchView to retrieve matching values in Firebase database

I have an activity where I want to search matching values in my firebase database. I don't want anything to appear up until something is typed on my SearchBar, after something has been typed I want to display values that match what was typed in my SearchBar. I have created an activity and it is not displaying anything up until you type something, my problem is that it does not retrieve the matching values but it shows everything within my database directory.
This is my activity:
public class MyUsersActivity extends AppCompatActivit {
private Toolbar toolbar, searchtollbar;
private RecyclerView mUsersList;
private DatabaseReference mUsersDatabase;
private LinearLayoutManager mLayoutManager;
Menu search_menu;
MenuItem item_search;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setTitle("Search Users");
//toolbar.setTitleTextColor(android.graphics.Color.WHITE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mLayoutManager = new LinearLayoutManager(this);
mUsersList = (RecyclerView) findViewById(R.id.users_list);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(mLayoutManager);
setSearchtollbar();
}
#Override
protected void onStart() {
super.onStart();
}
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDisplayName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserStatus(String status){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(status);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.my_profile).into(userImageView);
}
}
public void setSearchtollbar()
{
searchtollbar = (Toolbar) findViewById(R.id.searchtoolbar);
if (searchtollbar != null) {
searchtollbar.inflateMenu(R.menu.menu_search);
search_menu=searchtollbar.getMenu();
searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar,1,true,false);
else
searchtollbar.setVisibility(View.GONE);
}
});
item_search = search_menu.findItem(R.id.action_filter_search);
MenuItemCompat.setOnActionExpandListener(item_search, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
circleReveal(R.id.searchtoolbar,1,true,false);
}
else
searchtollbar.setVisibility(View.GONE);
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true;
}
});
initSearchView();
} else
Log.d("toolbar", "setSearchtollbar: NULL");
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void circleReveal(int viewID, int posFromRight, boolean containsOverflow, final boolean isShow)
{
final View myView = findViewById(viewID);
int width=myView.getWidth();
if(posFromRight>0)
width-=(posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material))-(getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)/ 2);
if(containsOverflow)
width-=getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_overflow_material);
int cx=width;
int cy=myView.getHeight()/2;
Animator anim;
if(isShow)
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0,(float)width);
else
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, (float)width, 0);
anim.setDuration((long)220);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if(!isShow)
{
super.onAnimationEnd(animation);
myView.setVisibility(View.INVISIBLE);
}
}
});
// make the view visible and start the animation
if(isShow)
myView.setVisibility(View.VISIBLE);
// start the animation
anim.start();
}
public void initSearchView()
{
final SearchView searchView = (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();
// Enable/Disable Submit button in the keyboard
searchView.setSubmitButtonEnabled(false);
// Change search close button image
ImageView closeButton = (ImageView) searchView.findViewById(R.id.search_close_btn);
closeButton.setImageResource(R.drawable.ic_close);
// set hint and the text colors
EditText txtSearch = ((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text));
txtSearch.setHint("Search..");
txtSearch.setHintTextColor(Color.DKGRAY);
txtSearch.setTextColor(getResources().getColor(R.color.colorPrimary));
// set the cursor
AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
try {
Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.set(searchTextView, R.drawable.search_cursor); //This sets the cursor resource ID to 0 or #null which will make it visible on white background
} catch (Exception e) {
e.printStackTrace();
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
callSearch(query);
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
callSearch(newText);
return true;
}
public void callSearch(String query) {
//Do searching
Log.i("query", "" + query);
if(!query.equals("")){
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.users_single_layout,
UsersViewHolder.class,
mUsersDatabase
) {
#Override
protected void populateViewHolder(UsersViewHolder usersViewHolder, Users users, int position) {
usersViewHolder.setDisplayName(users.getName());
usersViewHolder.setUserStatus(users.getStatus());
usersViewHolder.setUserImage(users.getThumb_image(), getApplicationContext());
final String user_id = getRef(position).getKey();
usersViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent profileIntent = new Intent(MyUsersActivity.this, ProfileActivity.class);
profileIntent.putExtra("user_id", user_id);
startActivity(profileIntent);
}
});
}
};
mUsersList.setAdapter(firebaseRecyclerAdapter);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_search:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar,1,true,true);
else
searchtollbar.setVisibility(View.VISIBLE);
item_search.expandActionView();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
How can I implement the match function to retrieve what's matching in my database?

Reset RecyclerView adapter from another Fragment

I have a Fragment that contains a RecyclerView. I am trying to implement a filter on the RecyclerView. The filter UI opens a new Fragment Dialog where the user will input a value. Once the user hits the Search Button in the Fragment Dialog, the value should be returned to the RecyclerView Fragment and the existing data in the view should be cleared. I want to re-populate the RecyclerView with the new set of data that I will obtain from the server. My problem is that, I have a method called resetAdapterDetails() in the RecyclerView Fragment which works as expected if called from the RecyclerView Fragment itself. But, when I try to call the same method from the Fragment Dialog, I get an exception:
transactionList.clear(); --> is trying to clear a list which is null
Though the data is still visible in the RecyclerView.
The RecyclerView Fragment:
public class TransactionHistoryFragment extends Fragment implements SearchView.OnQueryTextListener, DateRangePickerFragment.OnDateRangeSelectedListener{
private RecyclerView recyclerview;
private TransactionHistoryAdapter adapter;
private List<Transaction> transactionList;
public TransactionHistoryFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_transaction_history, container, false);
recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerview.setLayoutManager(layoutManager);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
getTransactionHistory("");
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.transactions_history_menu, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.filter_date:
FragmentManager fmDate = getActivity().getFragmentManager();
DateRangePickerFragment dialogFragmentDate = DateRangePickerFragment.newInstance(this, true);
dialogFragmentDate.show(fmDate, "Sample Fragment");
return true;
case R.id.filter_mobile:
FragmentManager fmMobile = getActivity().getFragmentManager();
SearchMobileFragment dialogFragmentMobile = new SearchMobileFragment ();
dialogFragmentMobile.show(fmMobile, "Sample Fragment");
//resetAdapterDetails();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onQueryTextChange(String newText) {
final List<Transaction> filteredModelList = filter(transactionList, newText);
adapter.setFilter(filteredModelList);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
//for filtering the list
private List<Transaction> filter(List<Transaction> models, String query) {
query = query.toLowerCase();final List<Transaction> filteredModelList = new ArrayList<>();
for (Transaction model : models) {
final String text = model.getTxnStatus().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
//for populating the list
private void getTransactionHistory(String agentId){
GetTransactionHistoryTask task = new GetTransactionHistoryTask("agent1", "password");
task.getTransactionsByAgent("OU23","OU230000000123456789").subscribe(transactionHistoryResponse -> {
if(transactionHistoryResponse != null && transactionHistoryResponse.getTransactions() != null && transactionHistoryResponse.getTransactions().size() > 0 && transactionHistoryResponse.getErrors().size() == 0){
transactionList = transactionHistoryResponse.getTransactions();
adapter = new TransactionHistoryAdapter(transactionList);
recyclerview.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
recyclerview.setAdapter(adapter);
onClickListnerRecyclerView();
}
else{
}
}, e -> e.printStackTrace());
}
private void onClickListnerRecyclerView() {
recyclerview.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
try {
final Transaction transactionModel= (Transaction) adapter.getObjectAt(position);
Intent i = new Intent(getActivity(), TransactionDetailsActivity.class);
i.putExtra("transaction_object",transactionModel);
startActivity(i);
}
catch (Exception e){
Log.e("List issue", e.toString());
}
}
})
);
}
#Override
public void onDateRangeSelected(int startDay, int startMonth, int startYear, int endDay, int endMonth, int endYear) {
}
public void fetchDateRange(String startDate, String endDate) {
Log.e("DateRange",startDate + "\n" + endDate);
}
public void fetchMobileNumber(String mobileNumber) {
Log.e("Mobile",mobileNumber);
resetAdapterDetails();
}
public boolean resetAdapterDetails(){
try {
transactionList.clear();
adapter.notifyDataSetChanged();
recyclerview.setAdapter(adapter);
} catch (Exception e) {
Log.e("Reset Error", ""+e.getMessage());
}
return true;
}
}
The Dialog Fragment:
public class SearchMobileFragment extends DialogFragment {
EditText mMobileNumberEditText;
Button search_button;
public SearchMobileFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_search_mobile, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMobileNumberEditText = (EditText) view.findViewById(R.id.mobile_number_editText);
search_button = (Button) view.findViewById(R.id.search_button);
search_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
TransactionHistoryFragment obj = new TransactionHistoryFragment();
obj.fetchMobileNumber(mMobileNumberEditText.getText().toString());
}
});
}
}
The fetchMobileNumber() method in the TransactionHistoryFragment (RecyclerView Fragment) is called through the fetchMobileNumber() method which is called from the SearchMobileFragment (Dialog Fragment).
Where am I going wrong? Why the transactionList.clear(); is throwing the null pointer exception?
You are getting the issue because you are creating new TransactionHistoryFragment instance search_button click in SearchMobileFragment. Which makes it's all variables null and initialize it again and here your transactionList becomes null.
You can achieve the same thing easily with different way also. As the place of SearchMobileFragment as a DialogFragment you can make it as Activity and start it as startActivityForResult from your TransactionHistoryFragment and implement onActivityResult callback to doing the fiteration.
But right now in your case you can manage it in different ways also:
First way:
As you are doing in your DialogFragment
search_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
/*TransactionHistoryFragment obj = new TransactionHistoryFragment();
obj.fetchMobileNumber(mMobileNumberEditText.getText().toString());*/
}
});
Don't do the call for fetchMobileNumber here, in onResume of your TransactionHistoryFragment you should make a call for this. On the click of search_button save the filter data to SharedPreferences and use that in onResume of the TransactionHistoryFragment for filtering and after that clear this saved data from SharedPreferences onPause of this fragment.
You should remove
transactionList.clear();
of code from resetAdapterDetails() in TransactionHistoryFragment, because after search filter you will get updated transactionList which is already passed to adapter then forcefully no need to clear it. Or have a check before clearing it like:
if(transactionList!=null){
transactionList.clear();
}
Second way: Using BroadcastReceiver you can achieve the same thing.
Register a receiver in your TransactionHistoryFragment and sendBroadcast from SearchMobileFragment. In onReceive of the TransactionHistoryFragment do the filtration process.
I had resolved the above issue in a different way. In the Dialog Fragment I have implemented a View.OnClickListener and have created an Interface to initialize the same from the RecyclerView Fragment. I am posting the complete source codes below; the SearchMobileFragment now looks like:
public class SearchMobileFragment extends DialogFragment implements View.OnClickListener{
private OnMobileNumberSelectedListener onMobileNumberSelectedListener;
EditText mMobileNumberEditText;
Button mSearchButton;
public SearchMobileFragment() {
// Required empty public constructor
}
public static SearchMobileFragment newInstance(OnMobileNumberSelectedListener callback) {
SearchMobileFragment searchMobileFragment = new SearchMobileFragment();
searchMobileFragment.initialize(callback);
return searchMobileFragment;
}
public void initialize(OnMobileNumberSelectedListener callback) {
onMobileNumberSelectedListener = callback;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_search_mobile, container, false);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
mMobileNumberEditText = (EditText) root.findViewById(R.id.mobile_number_editText);
mSearchButton = (Button) root.findViewById(R.id.search_button);
mSearchButton.setOnClickListener(this);
return root;
}
#Override
public void onStart() {
super.onStart();
if (getDialog() == null)
return;
getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
}
public void setOnMobileNumberSelectedListener(OnMobileNumberSelectedListener callback) {
this.onMobileNumberSelectedListener = callback;
}
#Override
public void onClick(View v) {
dismiss();
onMobileNumberSelectedListener.onMobileNumberSelected(mMobileNumberEditText.getText().toString());
}
public interface OnMobileNumberSelectedListener {
void onMobileNumberSelected(String mobileNumber);
}
}
The RecyclerView Fragment modifications:
public class TransactionHistoryFragment extends Fragment implements SearchView.OnQueryTextListener,
DateRangePickerFragment.OnDateRangeSelectedListener, SearchMobileFragment.OnMobileNumberSelectedListener{
private RecyclerView recyclerview;
private TransactionHistoryAdapter adapter;
private List<Transaction> transactionList;
SearchView search;
public static final String TIMERANGEPICKER_TAG = "timerangepicker";
public TransactionHistoryFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_transaction_history, container, false);
recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerview.setLayoutManager(layoutManager);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
getTransactionHistory();
}
#Override
public void onResume() {
Log.e("onResumeTHF","invoked");
super.onResume();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.transactions_history_menu, menu);
search = (SearchView) menu.findItem(R.id.action_search).getActionView();
search.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.filter_date:
FragmentManager fmDate = getActivity().getFragmentManager();
DateRangePickerFragment dialogFragmentDate = DateRangePickerFragment.newInstance(this, true);
dialogFragmentDate.show(fmDate, "Sample Fragment");
return true;
case R.id.filter_mobile:
FragmentManager fmMobile = getActivity().getFragmentManager();
SearchMobileFragment dialogFragmentMobile = SearchMobileFragment.newInstance(this);
dialogFragmentMobile.show(fmMobile, "Sample Fragment");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onQueryTextChange(String newText) {
Log.e("newText",newText);
final List<Transaction> filteredModelList = filter(transactionList, newText);
adapter.setFilter(filteredModelList);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public void onMobileNumberSelected(String mobileNumber) {
Log.e("mobileNumber",mobileNumber);
resetAdapterDetails();
}
public boolean resetAdapterDetails(){
try {
transactionList.clear();
adapter.notifyDataSetChanged();
recyclerview.setAdapter(adapter);
} catch (Exception e) {
Log.e("Reset Error", ""+e.getMessage());
}
return true;
}
}
Happy coding!
The null pointer exception is because when you create a new TransactionHistoryFragment using new onViewCreated is not called and hence transactionList is never initialized. You can create a setter for the list or pass it as a constructor to the fragment to fix this

Categories

Resources