Using SearchView to retrieve matching values in Firebase database - java

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?

Related

SearchData Method resets query? Firebase Database Android

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 :

FirebaseRecyclerAdapter OnItemClick from fragment to fragment

I'm using the firebaseRecyclerAdaper on a fragment and i want to open an item from de populated list from firebase and send the data to a new fragment. Can u guys tell me please how can i start the FragmentDetail from the onCLickListener on FragmentAllPosts and pass the PostModel parameter to it?
Main Activity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "TAG" ;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference , postsRef;
private StorageReference profileImgRef;
private CircleImageView circleImageViewMain;
private TextView nameEdtTxt, emailEdtTxt;
Fragment fragment= null;
private RecyclerView recyclerView;
private FloatingActionButton fab;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressDialog= new ProgressDialog(this);
progressDialog.setMessage("Please wait!");
progressDialog.setCanceledOnTouchOutside(false);
//Initialize Firebase modules
firebaseAuth=FirebaseAuth.getInstance();
databaseReference= FirebaseDatabase.getInstance().getReference().child("users");
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
profileImgRef= FirebaseStorage.getInstance().getReference();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
circleImageViewMain = (CircleImageView) header.findViewById(R.id.circleImageHeader);
nameEdtTxt = (TextView) header.findViewById(R.id.txtName);
emailEdtTxt =(TextView)header.findViewById(R.id.txtEmail);
if (firebaseAuth.getCurrentUser()!=null){
LoadUserData(CheckUserDataBase());
}
ViewPager vp_pages= (ViewPager) findViewById(R.id.vp_pages);
PagerAdapter pagerAdapter=new FragmentAdapter(getSupportFragmentManager());
vp_pages.setAdapter(pagerAdapter);
TabLayout tbl_pages= (TabLayout) findViewById(R.id.tabs);
tbl_pages.setupWithViewPager(vp_pages);
tbl_pages.setTabTextColors(ColorStateList.valueOf(Color.parseColor("#FFFFFF")));
tbl_pages.setHorizontalScrollBarEnabled(true);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragment= new AddPostFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.add(R.id.add_post_container, fragment).commit();
fab.hide();
}
});
}
class FragmentAdapter extends FragmentPagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentAllPosts();
case 1:
return new FragmentLosts();
case 2:
return new FragmentFounds();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
//
//Your tab titles
//
case 0:return "All";
case 1:return "Losts";
case 2: return "Founds";
default:return null;
}
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser user= firebaseAuth.getCurrentUser();
if (user == null){
SendUserToLogin();
} else {
CheckUserDataBase();
}
}
public static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
private void UpdateHome() {
}
private void LoadUserData(final String uid) {
try {
final File localFile =File.createTempFile("profile","png");
StorageReference filepath=profileImgRef.child(uid).child("profileImg/profile.png");
filepath.getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Picasso.get()
.load(localFile)
.placeholder(R.drawable.ic_account)
.into(circleImageViewMain);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this,
"Profile photo not found, please update your profile!",
Toast.LENGTH_SHORT).show();
SendUserToSetup();
}
});
} catch (IOException e) {
e.printStackTrace();
}
databaseReference.child(uid).child("userInfo").addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("name")){
String name = dataSnapshot.child("name").getValue().toString();
nameEdtTxt.setText(name);
String email = dataSnapshot.child("email").getValue().toString();
emailEdtTxt.setText(email);
} else {
Toast.makeText(MainActivity.this,
"Profile name does not exists, please update your profile",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
}
#Override
protected void onStop() {
super.onStop();
}
private String CheckUserDataBase() {
final String userID =firebaseAuth.getCurrentUser().getUid();
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(userID).hasChild("userInfo")){
SendUserToSetup();
} else {
UpdateHome();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
return userID;
}
private void SendUserToSetup() {
Intent i = new Intent(this,SetupActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
private void SendUserToLogin() {
Intent i = new Intent(this,LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() >0)
{
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
} else
{
super.onBackPressed();
}
fab.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id){
case R.id.nav_home:
super.onResume();
if (fragment!=null){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.remove(fragment).commit();
fab.show();
}
break;
case R.id.nav_profile:
super.onPause();
break;
case R.id.nav_my_posts:
super.onPause();
break;
case R.id.nav_messeges:
super.onPause();
break;
case R.id.nav_settings:
super.onPause();
break;
case R.id.nav_logout:
SendUserToLogin();
firebaseAuth.signOut();
break;
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Fragment with the FirebaseRecyclerAdapter
public class FragmentAllPosts extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private DatabaseReference postsRef;
private Context context= getContext();
Fragment mFragment;
Bundle mBundle;
public FragmentAllPosts() {
// Required empty public constructor
}
public static FragmentAllPosts newInstance(String param1, String param2) {
FragmentAllPosts fragment = new FragmentAllPosts();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
private RecyclerView recyclerAllPosts;
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
progressDialog= new ProgressDialog(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_all_posts,container,false);
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
recyclerAllPosts= v.findViewById(R.id.recycler_all_posts);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerAllPosts.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
#Override
public void onStart() {
super.onStart();
progressDialog.show();
FirebaseRecyclerOptions<PostsModel> options=
new FirebaseRecyclerOptions.Builder<PostsModel>()
.setQuery(postsRef,PostsModel.class)
.setLifecycleOwner(this)
.build();
FirebaseRecyclerAdapter<PostsModel,PostsViewHolder> adapter=
new FirebaseRecyclerAdapter<PostsModel, PostsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final PostsViewHolder holder, int position, #NonNull final PostsModel model) {
String processedTime= CalculateTime(model.getData());
Picasso.get().load(Uri.parse(model.getUserImg())).into(holder.circleImageView);
Picasso.get().load(Uri.parse(model.getImageUri())).into(holder.imageView);
holder.authorNdate.setText(model.getAuthor()+" updated "+processedTime);
holder.location.setText(model.getLocation());
holder.description.setText(model.getDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment frag= new FragmentDetail();
getFragmentManager().beginTransaction().replace(R.id.add_post_container,frag)
.addToBackStack(null).commit();
}
});
}
#NonNull
#Override
public PostsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_view,viewGroup,false );
PostsViewHolder viewHolder= new PostsViewHolder(view);
return viewHolder;
}
};
recyclerAllPosts.setAdapter(adapter);
progressDialog.dismiss();
adapter.startListening();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public String CalculateTime(String inputTime){
String timeOut;
Calendar currentTime= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat(getString(R.string.date_format));
dateFormat.format(currentTime.getTime());
SimpleDateFormat postFormat= new SimpleDateFormat(getString(R.string.date_format));
Calendar postTime = Calendar.getInstance();
try {
Date datePost=postFormat.parse(inputTime);
postTime.setTime(datePost);
} catch (ParseException e) {
e.printStackTrace();
}
long timeCurrent= currentTime.getTimeInMillis();
long timePost = postTime.getTimeInMillis();
long diff= timeCurrent- timePost;
long minutes= diff/(60*1000);
long hours = diff/(60 * 60 * 1000);
long days = diff/(24 * 60 * 60 * 1000);
if (minutes<59 && minutes>1){
timeOut=Long.toString(minutes)+" mins ago";
} else if (minutes<1){
timeOut=" just now";
}else if (hours<24 && minutes>59){
timeOut=Long.toString(hours)+" hour(s) ago";
}else {
timeOut=Long.toString(days)+" day(s) ago";
}
return timeOut;
}
static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setTag(this);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Detail Fragment:
public class FragmentDetail extends Fragment {
public FragmentDetail() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
}
I'd suggest a read on the documentation. Passing data between two activities should be done via interfaces.
As suggested by the official site

How Can I Update data in Recyclerview?

I Build an app that load data with Retrofit, into a recyclerview, my recyclerview load perfectly all data from JSON file, but when I try of an update with swipeRefreshLayout, and I intent load again the method loadFirstPage();, but simply add again the same data.
I search in google for any solution, but all my intents do not work in my code.
I intent used adapter.clear and load again, but not work fine.
The idea is if 1 item change from JSON file, update again the data in Recyclerview.
public class historial extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
User user = SharedPrefManager.getInstance(this).getUser();
private static final String TAG = "MainActivity";
PaginationAdapter adapter;
LinearLayoutManager linearLayoutManager;
private SwipeRefreshLayout swipeRefreshLayout;
RecyclerView recyclerView;
ProgressBar progressBar;
private static final int PAGE_START = 1;
private boolean isLoading = false;
private boolean isLastPage = false;
// limiting to 5 for this tutorial, since total pages in actual API is very large. Feel free to modify.
private int TOTAL_PAGES = 5;
private int currentPage = PAGE_START;
private NetworkInterface geosInterface;
int position;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.historial);
Toolbar toolbar = findViewById(R.id.toolbar);
//setting the title
toolbar.setTitle("elGEos School - Historial");
//placing toolbar in place of actionbar
setSupportActionBar(toolbar);
progressBar = findViewById(R.id.progressBar);
recyclerView = findViewById(R.id.recycler_view);
adapter = new PaginationAdapter(this);
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(historial.this);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new PaginationScrollListener(linearLayoutManager) {
#Override
protected void loadMoreItems() {
isLoading = true;
currentPage += 1;
// mocking network delay for API call
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
loadNextPage();
}
}, 1000);
}
#Override
public int getTotalPageCount() {
return TOTAL_PAGES;
}
#Override
public boolean isLastPage() {
return isLastPage;
}
#Override
public boolean isLoading() {
return isLoading;
}
});
//init serecyclerViewice and load data
geosInterface = NetworkApi.getClient().create(NetworkInterface.class);
loadFirstPage();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
//CODE FOR UPDATE HERE ???
if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false); // This hides the spinner
}
}
});
}
//TOOL BAR Y MENU
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu3, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.aboutback:
onBackPressed();
//Toast.makeText(this, "You clicked about", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
private void loadFirstPage() {
swipeRefreshLayout.setRefreshing(true);
Log.d(TAG, "loadFirstPage: ");
callTopMessage().enqueue(new Callback<TopMessage>() {
#Override
public void onResponse(Call<TopMessage> call, Response<TopMessage> response) {
// Got data. Send it to adapter
List<Result> results = fetchResults(response);
progressBar.setVisibility(View.GONE);
adapter.addAll(results);
if (currentPage <= TOTAL_PAGES) adapter.addLoadingFooter();
else isLastPage = true;
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFailure(Call<TopMessage> call, Throwable t) {
t.printStackTrace();
// TODO: 08/11/16 handle failure
swipeRefreshLayout.setRefreshing(false);
}
});
}
/**
* #param response extracts List<{#link Result>} from response
* #return
*/
private List<Result> fetchResults(Response<TopMessage> response) {
TopMessage topMessage = response.body();
return topMessage.getResults();
}
private void loadNextPage() {
swipeRefreshLayout.setRefreshing(true);
Log.d(TAG, "loadNextPage: " + currentPage);
callTopMessage().enqueue(new Callback<TopMessage>() {
#Override
public void onResponse(Call<TopMessage> call, Response<TopMessage> response) {
adapter.removeLoadingFooter();
isLoading = false;
List<Result> results = fetchResults(response);
adapter.addAll(results);
if (currentPage != TOTAL_PAGES) adapter.addLoadingFooter();
else isLastPage = true;
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFailure(Call<TopMessage> call, Throwable t) {
t.printStackTrace();
// TODO: 08/11/16 handle failure
swipeRefreshLayout.setRefreshing(false);
}
});
}
private Call<TopMessage> callTopMessage() {
return geosInterface.getTopMessage(
"Comfama",
"B",
"TTY651",
"1",
currentPage
);
}
#Override
public void onRefresh() {
}
}
Try this:
it is very simple to update and remove data in recycler view
REMOVE Data : There are 4 steps to remove an item from a RecyclerView adapter class like this:
list.remove(position);
recycler.removeViewAt(position);
adapter.notifyItemRemoved(position);
mAdapter.notifyItemRangeChanged(position, list.size());
make sure your data is set in adapter class like this after that you notifyData
private void setAdapter() {
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recycler_view.setLayoutManager(mLayoutManager);
mAdapter = new BankDetailsAdapter(getBankList,this);
recycler_view.setAdapter(mAdapter);
}
UPDATE data: There are 1 steps to update data like this:
adapter.notifyDataSetChanged();
it helps you

OrmLite get value from listView with Adapter

When I want to get a name of list which I pressed, I get "com.example.oleksandr.dream.DB.DreamDetails#528f8a90". How can I get a String value from my list? The problem is in "the onItemClick" methode.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private DBHelper mDbHelper = null;
private DreamDetails dreamDetails;
private ListView mListView;
private DrawerLayout drawerLayout;
private Toolbar mToolbar;
private Dao<DreamDetails, Integer> dreamDetailsDao;
private List<DreamDetails> dreamList;
private int selectedRecordPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listViewAllDreams);
try {
//Getting all Data from DB
dreamDetailsDao = getHelper().getDreamDetailsesDao();
dreamList = dreamDetailsDao.queryForAll();
// Set the header of the ListView
final LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.list_view, mListView, false);
mListView.addHeaderView(view);
// my own adapter!
mListView.setAdapter(new AdapterArrayDream(this,R.layout.list_view,dreamList,dreamDetailsDao));
mListView.setOnItemClickListener(this);
} catch (SQLException e) {
e.printStackTrace();
}
initToolbar();
initNavigationView();
FloatingActionButton myFab = (FloatingActionButton)findViewById(R.id.fab);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NewDream.class);
startActivity(intent);
}
});
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(i > 0)
{
selectedRecordPosition = i - 1;
// final Intent intent = new Intent(this, ViewDream.class);
Log.i("TAAAAAAG", "onClick " + adapterView.getItemAtPosition(selectedRecordPosition));
// intent.putExtra("D", String.valueOf(adapterView.getItemAtPosition(selectedRecordPosition)));
// startActivity(intent);
}
}
private void initNavigationView() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawlerLayout);
}
private void initToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle(R.string.app_name);
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
});
// mToolbar.inflateMenu(R.menu.menu);
}
// This is how, DatabaseHelper can be initialized for future use
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_list_dreams, menu);
return true;
}
private DBHelper getHelper() {
if (mDbHelper == null) {
mDbHelper = OpenHelperManager.getHelper(this, DBHelper.class);
}
return mDbHelper;
}
}
To create a query which looks up an account by name and password you would do the following:
QueryBuilder<Account, String> qb = accountDao.queryBuilder();
Where where = qb.where();
// the name field must be equal to "foo"
where.eq(Account.NAME_FIELD_NAME, "foo");
// and
where.and();
// the password field must be equal to "_secret"
where.eq(Account.PASSWORD_FIELD_NAME, "_secret");
PreparedQuery<Account, String> preparedQuery = qb.prepareQuery();

How to get data from the db in activity a, when activity b is closed in Android with ActiveAndroid

im new to this and have some problems, thanks for your help.
Situation:
I have a MainActivity and a second Activity called MainAddMedActivity. I get data from the second activity through an EditText and save it in the database. My intention is to display the data from the EditText in a ListView in the MainActivity by taking it from the database. How to do it the right way ?
Med:
#Table(name = "Med")
public class Med extends Model {
// Zähler für eindeutige IDs
private static long counter = 0;
#Column(name = "_id", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
public long id;
#Column(name = "Description", index = true)
public String description;
public Med() {
super();
}
public Med(String message) {
super();
id = counter++;
description = message;
}
}
MedDAO:
public class MedDAO {
public static List<Med> getAll(String text) {
return new Select()
.from(Med.class)
.where("Description like ?", new String[]{'%' + text + '%'})
.orderBy("Description")
.limit(40)
.execute();
}
public static List<Med> getAll() {
return new Select()
.all()
.from(Med.class)
.execute();
}
public static List<Med> getOneItem(String text) {
return new Select()
.from(Med.class)
.where("Description = ?", text)
.execute();
}
public static void insertMed(String msg){
new Med(msg).save();
}
public static void remove(String text) {
new Delete().from(Med.class).where("Description = ?", text).execute();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ArrayAdapter<String> listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), MainAddMedActivity.class);
startActivity(intent);
}
});
ListView mainListView = (ListView) findViewById(R.id.listView);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listAdapter.getItem(position);
//Aus DB entfernen
MedDAO.remove(item);
//Aus Liste im Gui entfernen
listAdapter.remove(item);
Toast.makeText(getBaseContext(), item + "gelöscht", Toast.LENGTH_SHORT).show();
}
});
//TODO: ArrayAdapter bugt
//Adapter für die Liste erzeugen
listAdapter = new ArrayAdapter<String>(this, R.layout.single_row, R.id.listMedNrPart);
mainListView.setAdapter(listAdapter);
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onResume() {
super.onResume();
// MedDAO.getLatestItem();
/*int max = listAdapter.getCount();
int i = 0;
while (i < max){
Log.d("MainActivity", listAdapter.getItem(i));
i++;
}*/
// listAdapter.add(MedDAO.getLatestItem().toString());
}
}
MainAddMedActivity:
public class MainAddMedActivity extends AppCompatActivity {
private EditText txtSearchMedicament;
private EditText txtNumberMedicament;
private TextView txtAlarmPrompt;
private TimePickerDialog timePickerDialog;
private Switch switchReminder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_add_med);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText description = (EditText) findViewById(R.id.txtSearchMedicament);
String text = description.getText().toString();
**//SAVE IN DATABASE**
MedDAO.insertMed(text);
//TODO: Close Activity
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.txtSearchMedicament = (EditText) findViewById(R.id.txtSearchMedicament);
this.txtNumberMedicament = (EditText) findViewById(R.id.txtNumberMedicament);
this.txtAlarmPrompt = (TextView) findViewById(R.id.txtAlarmPrompt);
this.switchReminder = (Switch) findViewById(R.id.switchReminder);
switchReminder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cancelSwitch();
}
}
});
A Content Provider could be used. It takes a good amount of code to implement but it binds your database to your view.
Here is an example of a Content Provider I have implemented in the past.
You construct a ContentValue object (basically a set of values to mimic a database row) for your database keys and set your new data there. You then use getContentResolver() to insert the ContentValue into your Content Provider, which in turn updates your database with your new data.
ContentValues values = new ContentValues();
values.put(DatabaseHelper.KEY_VENUE_NAME, store.getName());
values.put(DatabaseHelper.KEY_VENUE_CITY, store.getCity());
values.put(DatabaseHelper.KEY_VENUE_STATE, store.getState());
//insert row
context.getContentResolver().insert(Uri.parse(ContentProvider.base_CONTENT_URI + index), values);
Here's an example of the Content Provider Class (too much code for here) which implements the logic for inserting, deleting, querying, editing, and constructing URI paths to your database.
You can then set up and use a Cursor, which iterates through your data source, to access the data from your Content Provider, more specifically you can extend CursorAdapter to directly bind your views to database queries. Here is what one looks like:
public class StoreCursorAdapter extends SimpleCursorAdapter {
private static final String TAG = "VenueCursorAdapter";
DatabaseHelper databaseHelper;
private Context context;
private int layout;
private int selection; //MapsActivity.getStoreSelection();
public StoreCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
databaseHelper = DatabaseHelper.getInstance(context);
this.context = context;
this.layout = layout;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
selection = ((MapsActivity) context).getStoreSelection();
int position = c.getPosition();
int nameColumn = c.getColumnIndex(DatabaseHelper.KEY_VENUE_NAME);
String name = c.getString(nameColumn);
TextView nameText = (TextView) v.findViewById(R.id.nameTextView);
TextView ratingText = (TextView) v.findViewById(R.id.ratingTextView);
if(nameText != null && ratingText != null) {
nameText.setText(name);
}
}
}

Categories

Resources