searchView doesn't work after deleting database contents - android

I am a begineer in Android programming. I am getting trouble with this problem from 3 days. Any suggestion plz.
MainActivity.java
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener,
View.OnLongClickListener, BeneficiaryRecyclerAdapter.ListItemClickListener {
private AppCompatActivity activity = MainActivity.this;
public boolean is_in_action_mode = false;
private RecyclerView recyclerViewBeneficiary;
private Beneficiary beneficiary;
private ArrayList<Beneficiary> listBeneficiary;
ArrayList<Beneficiary> selection_list = new ArrayList<>();
private BeneficiaryRecyclerAdapter beneficiaryRecyclerAdapter;
private DatabaseHelper databaseHelper;
Toolbar toolbar;
TextView counter_text_view;
int counter = 0, id;
private SQLiteDatabase mDb;
private final static String TAG = "check";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//toolbar.inflateMenu(R.menu.menu_activity_main);
counter_text_view = (TextView) findViewById(R.id.counter_text);
counter_text_view.setText(getString(R.string.app_name));
recyclerViewBeneficiary = (RecyclerView) findViewById(R.id.listRecyclerView);
initObjects();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.addAccountFab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
AccountDetailActivity.class);
startActivity(intent);
}
});
}
private void initObjects() {
listBeneficiary = new ArrayList<>();
beneficiaryRecyclerAdapter = new BeneficiaryRecyclerAdapter(listBeneficiary, MainActivity.this,MainActivity.this);
Log.d(TAG,"listBeneficiary size[initObject()] = "+ listBeneficiary.size());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewBeneficiary.setLayoutManager(mLayoutManager);
recyclerViewBeneficiary.setItemAnimator(new DefaultItemAnimator());
//recyclerViewBeneficiary.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); // For Vertical line separation
recyclerViewBeneficiary.setHasFixedSize(true);
recyclerViewBeneficiary.setAdapter(beneficiaryRecyclerAdapter);
databaseHelper = new DatabaseHelper(activity);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listBeneficiary.clear();
listBeneficiary.addAll(databaseHelper. getAllBeneficiary());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
beneficiaryRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
newText = newText.toLowerCase();
ArrayList<Beneficiary> newList = new ArrayList<>();
Log.d(TAG,"listBeneficiary size[onQuery] = "+ listBeneficiary.size());
for (Beneficiary beneficiary: listBeneficiary) {
String name = beneficiary.getTitle().toLowerCase();
if (name.contains(newText))
newList.add(beneficiary);
}
beneficiaryRecyclerAdapter.setFilter(newList);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_activity_main,menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search by title");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
#Override
public boolean onLongClick(View v) {
toolbar.getMenu().clear();
toolbar.inflateMenu(R.menu.menu_action_mode);
toolbar.setBackgroundColor(getResources().getColor(R.color.colorActionMode));
counter_text_view.setVisibility(View.VISIBLE);
counter_text_view.setText("0 items selected");
is_in_action_mode = true;
beneficiaryRecyclerAdapter.notifyDataSetChanged();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
return true;
}
public void clearActionMode(){
is_in_action_mode = false;
toolbar.getMenu().clear();
toolbar.inflateMenu(R.menu.menu_activity_main);
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
getSupportActionBar().setDisplayHomeAsUpEnabled(false); // old = true
counter_text_view.setText(getString(R.string.app_name)); // New,good
counter = 0;
selection_list.clear();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.item_delete){
for (Beneficiary contact : selection_list) { //New
listBeneficiary.remove(contact); //New
databaseHelper.deleteSelectedItems(contact.getId());
}
beneficiaryRecyclerAdapter.notifyDataSetChanged(); //new
clearActionMode()
}
else if(item.getItemId()== android.R.id.home){
clearActionMode();
beneficiaryRecyclerAdapter.notifyDataSetChanged();
}
return true;
}
Intent intent = new Intent(this, AccountDetailActivity.class);
Uri currentUri =
ContentUris.withAppendedId(BeneficiaryEntry.CONTENT_URI, id);
intent.setData(currentUri);
startActivity(intent);
}
}
Inside BeneficiaryRecyclerAdapter
public void setFilter(ArrayList<Beneficiary> newList) {
listBeneficiary = new ArrayList<>();
listBeneficiary.addAll(newList);
notifyDataSetChanged();
}
At first the searchView works great many times but after I delete some row it doesn't respond. I have checked using Log.d, the problem is onQueryTextChange(String newText) is not getting any value but works after the mainActivity is resumed. So please let find my mistake.

Try to add
MenuItem menuItem = toolbar.getMenu().findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search by title");
searchView.setOnQueryTextListener(this);
to clearActionMode().

Related

Bottom navigation items quit the applicaiton when pressing on back button of the phone

I've implemented a bottom navigation in my application and it's working fine, but today I've tried to press the back button of the phone when I'm inside some activity, while doing so, I've noticed that it pretty much takes me out of the app , is there a way to solve this? for example instead of it taking me to the outside of app i want it to take me to home activity, is there some method i'm supposed to be using to handle these changes? if so please let me know, my code for the bottom navigation in the(for example exercice acitvity since i use the bottom navigation in 3 different activities)is :
public class Exercice extends AppCompatActivity {
DatabaseReference ref;
ArrayList<Deal> list;
RecyclerView recyclerView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercice);
ref = FirebaseDatabase.getInstance().getReference().child("medicines");
recyclerView = findViewById(R.id.rv);
searchView = findViewById(R.id.searchview);
/* RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
*/
//initialize and assign variables
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//set home selected
bottomNavigationView.setSelectedItemId(R.id.exercice);
//preform itemsselectedlistener
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.exercice:
finish();
return true;
case R.id.profile:
startActivity(new Intent(getApplicationContext()
, MainActivity.class));
overridePendingTransition(0, 0);
finish();
return true;
case R.id.home:
startActivity(new Intent(getApplicationContext()
, Home.class));
overridePendingTransition(0, 0);
finish();
}
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
if(ref != null){
ref.addValueEventListener(new ValueEventListener() {
#NonNull
#Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
list = new ArrayList<>();
for(DataSnapshot ds : snapshot.getChildren()){
list.add(ds.getValue(Deal.class));
}
AdapterClass adapterClass = new AdapterClass(list);
recyclerView.setAdapter(adapterClass);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Exercice.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
if (searchView != null){
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
}
private void search(String str) {
if (!str.equals("")){
ArrayList<Deal> myList = new ArrayList<>();
for (Deal object : list){
if(object.getDisease().toLowerCase().contains(str.toLowerCase())){
myList.add(object);
}
}
AdapterClass adapterClass = new AdapterClass(myList);
recyclerView.setAdapter(adapterClass);
}
}
}

Android - SearchView not working in fragment present in MainActivity

Hello so I have a MainActivity which consists of two fragments one is home and the other notifications.
When the app is opened by default the Home fragment is displayed.My app has a navigation bar which comes with an app bar by default where all the Menu Items are inflated.
My home fragment consists of Posts and in the app bar there's a search icon (SearchView) when i click it and search for something nothing happens.
HomeFragment.java
public class HomeFragment extends Fragment {
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 HomeFragment.OnFragmentInteractionListener mListener;
private RecyclerView rv;
private FirebaseAuth fba;
private List<PostActivity> postItems;
private FirebaseUser user;
private Toolbar toolbar;
private PostAdapter pa;
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
user = FirebaseAuth.getInstance().getCurrentUser();
fba = FirebaseAuth.getInstance();
// dr = FirebaseDatabase.getInstance().getReference().child("Chat_Profiles");
rv =view.findViewById(R.id.rvPostItems);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
rv.setLayoutManager(layoutManager);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
postItems = new ArrayList<>();
rv.addItemDecoration(new DividerItemDecoration(rv.getContext(), DividerItemDecoration.VERTICAL));
loadPosts();
registerForContextMenu(rv);
return view;
}
public void loadPosts() {
DatabaseReference dr = FirebaseDatabase.getInstance().getReference("Posts");
dr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postItems.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
PostActivity pac = ds.getValue(PostActivity.class);
postItems.add(pac);
pa = new PostAdapter(postItems, getActivity());
rv.setAdapter(pa);
pa.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(), "Failed !", Toast.LENGTH_SHORT).show();
}
});
}
public void searchPosts(String query){
DatabaseReference dr = FirebaseDatabase.getInstance().getReference("Posts");
dr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postItems.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
PostActivity pac = ds.getValue(PostActivity.class);
if(pac.getDesc().toLowerCase().contains(query.toLowerCase())) {
postItems.add(pac);
}
pa = new PostAdapter(postItems, getActivity());
rv.setAdapter(pa);
pa.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(), "Failed !", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.main,menu);
MenuItem searchPosts = menu.findItem(R.id.searchPosts);
SearchView searchView = (SearchView)MenuItemCompat.getActionView(searchPosts);
/*searchView.setIconified(true);
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));*/
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
if(!TextUtils.isEmpty(s))
searchPosts(s);
else
loadPosts();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(!TextUtils.isEmpty(s))
searchPosts(s);
else
loadPosts();
return false;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof HomeFragment.OnFragmentInteractionListener) {
mListener = (HomeFragment.OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements
,HomeFragment.OnFragmentInteractionListener
,NotificationFragment.OnFragmentInteractionListener{
private FirebaseAuth fba;
private FirebaseUser user;
private TextView welcomeUser;
private DatabaseReference dr;
private String name, thumb;
private Toolbar toolbar;
private MaterialSearchView msv;
private FloatingActionButton addPost;
private HomeFragment homeFragment;
private NotificationFragment notificationFragment;
private BottomNavigationView bnv;
private ImageView navImg;
private MenuItem itemToHide;
private Menu postsMenu = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fba = FirebaseAuth.getInstance();
/*if(!fba.getCurrentUser().isEmailVerified()){
fba.getCurrentUser().updateEmail(fba.getCurrentUser().getEmail());
fba.getCurrentUser().sendEmailVerification();
}*/
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("Newsy");
addPost = findViewById(R.id.add_post_btn);
addPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,AddPost.class);
startActivity(intent);
}
});
if (!(fba.getCurrentUser().isEmailVerified()) || fba.getCurrentUser() == null) {
startActivity(new Intent(this, LoginScreen.class));
}
/*if(fba.getCurrentUser()==null ){
startActivity(new Intent(this,LoginScreen.class));
}*/
ConnectionDetector cd = new ConnectionDetector(this);
if(cd.isConnected()){
Toast.makeText(this,"Connection Established !",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,"Your phone is Offline,Check your connection !",Toast.LENGTH_LONG).show();
}
user = fba.getCurrentUser();
String id = user.getUid();
dr = FirebaseDatabase.getInstance().getReference().child("Chat_Profiles").child(id);
//ConstraintLayout cl = (ConstraintLayout)findViewById(R.id.LoginScreen);
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);
if (drawer != null) {
drawer.addDrawerListener(toggle);
}
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
dr = FirebaseDatabase.getInstance().getReference().child("Chat_Profiles").child(fba.getCurrentUser().getUid());
if (navigationView != null) {
navigationView.setNavigationItemSelectedListener(this);
View nav_header = navigationView.getHeaderView(0);
dr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
name = dataSnapshot.child("name").getValue().toString();
thumb = dataSnapshot.child("image").getValue().toString();
CircleImageView circle = (CircleImageView) nav_header.findViewById(R.id.navImg);
Picasso.get().load(thumb).placeholder(R.drawable.default_avatar).into(circle);
welcomeUser = (TextView) nav_header.findViewById(R.id.WelcomeUser);
welcomeUser.setText(name);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(pappuLayout);
Menu menu = navigationView.getMenu();
MenuItem mt = menu.findItem(nav_gallery);
mt.setTitle("News 2");
MenuItem mt2 = menu.findItem(nav_camera);
mt2.setTitle("News 1");
MenuItem mt3 = menu.findItem(nav_sub);
mt3.setTitle("Subscribe !");
//FRAGMENTS MAIN PAGE
bnv = findViewById(R.id.bottomNavigationView2);
homeFragment = new HomeFragment();
replaceFragment(new HomeFragment());
bnv.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.bottomHome) {
replaceFragment(homeFragment);
return true;
} else if (itemId == R.id.bottomNotification) {
notificationFragment = new NotificationFragment();
replaceFragment(notificationFragment);
return true;
}
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser user = fba.getCurrentUser();
String id = user.getUid();
SharedPreferences sp = getSharedPreferences("USER", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Current_User", id);
editor.apply();
Intent intent = new Intent(getBaseContext(), MyUnityPlugin.class);
intent.putExtra("id", id);
dr.child("onlineStatus").setValue("true");
}
#Override
protected void onStop() {
super.onStop();
FirebaseUser user = fba.getCurrentUser();
dr.child("onlineStatus").setValue(ServerValue.TIMESTAMP);
}
#Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
}
#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.LogOut) {
fba.signOut();
finish();
startActivity(new Intent(this,LoginScreen.class));
return true;
}else if(id==R.id.settings){
startActivity(new Intent(this,ProfileActivity.class));
return true;
}else if(id==R.id.users){
startActivity(new Intent(this,Users.class));
return true;
}else if(id==R.id.search){
startActivity(new Intent(this,Users.class));
return true;
} else if (id == R.id.notificationSettings) {
startActivity(new Intent(this, SettingsActivity.class));
//startActivity(new Intent(this,UnityPlayerActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
if (itemId == R.id.nav_gallery) {
fragment = new GalleryFrag();
} else if (itemId == R.id.nav_camera) {
fragment = new CameraFrag();
} else if (itemId == R.id.nav_sub) {
fragment = new Subscribe();
} else if (itemId == R.id.nav_chat) {
fragment = new Chat();
} else if (itemId == R.id.nav_send) {
Intent i = new Intent(MainActivity.this, UnityPlayerActivity.class);
startActivity(i);
}
//replacing the fragment
if (fragment != null) {
ConstraintLayout fl = (ConstraintLayout) findViewById(pappuLayout);
fl.removeAllViews();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(pappuLayout, fragment).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(drawer_layout);
if (drawer != null) {
drawer.closeDrawer(GravityCompat.START);
}
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private void replaceFragment(Fragment fragment){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.postPage,fragment);
ft.addToBackStack(null);
ft.commit();
}
}
main.xml (Menu XML file)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="#+id/search"
android:title="Search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_action_search"
android:iconTint="#fff"
app:showAsAction="ifRoom"
app:actionViewClass="androidx.appcompat.widget.SearchView"
android:visible="false"
>
</item>
<item
android:id="#+id/searchPosts"
android:title="Search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_action_search"
android:iconTint="#fff"
app:showAsAction="ifRoom"
app:actionViewClass="androidx.appcompat.widget.SearchView"
>
</item>
<item
android:id="#+id/notificationSettings"
android:icon="#drawable/baseline_settings_applications_white_18dp"
android:orderInCategory="100"
android:title="Settings"
app:showAsAction="ifRoom">
</item>
<item
android:id="#+id/LogOut"
android:orderInCategory="100"
android:title="Log Out"
app:showAsAction="never" />
<item
android:id="#+id/settings"
android:title="My Profile! "
>
</item>
<item
android:id="#+id/users"
android:title="All users"
>
</item>
</menu>

Adding List to Cloud Firebase - Android

I do everything according to great guides from Youtube. https://www.youtube.com/watch?v=W-L6Cr2WP18 - I recommend. Unfortunately, instead of activity, I use a fragment and I have an error.
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private String userEmail, userName;
private GoogleApiClient googleApiClient;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore rootRef;
private FirebaseAuth.AuthStateListener authStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
GoogleSignInAccount googleSignInAccount = GoogleSignIn.getLastSignedInAccount(this);
if(googleSignInAccount != null){
String userEmail = googleSignInAccount.getEmail();
String userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
firebaseAuth = FirebaseAuth.getInstance();
rootRef = FirebaseFirestore.getInstance();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if(firebaseUser == null){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
};
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_menu1);
}
private void signOut(){
Map<String, Object> map = new HashMap<>();
map.put("tokenId", FieldValue.delete());
rootRef.collection("users").document(userEmail).update(map).addOnSuccessListener(new OnSuccessListener<Void>(){
#Override
public void onSuccess(Void aVoid){
firebaseAuth.signOut();
if(googleApiClient.isConnected()){
Auth.GoogleSignInApi.signOut(googleApiClient);
}
}
});
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
firebaseAuth.addAuthStateListener(authStateListener);
}
#Override
protected void onStop() {
super.onStop();
if(googleApiClient.isConnected()){
googleApiClient.disconnect();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//wybieranie fragmentu
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_menu1:
fragment = new Menu1Goals();
break;
case R.id.nav_menu2:
fragment = new Menu2();
break;
case R.id.nav_menu3:
fragment = new Menu3();
break;
}
//replacing the fragment - zmienianie fragmentów
//Transakcja fragmentu to seria zmian dotyczących fragmentu, które chcemy wykonać w tym samym momencie
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
//przekazywanie wybranego fragmentu do interfejsu
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}
//------------------------------------Top Menu----------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
//getting the search view from the menu
MenuItem searchViewItem = menu.findItem(R.id.menuSearch);
//getting search manager from systemservice
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
//getting the search view
final SearchView searchView = (SearchView) searchViewItem.getActionView();
//you can put a hint for the search input field
searchView.setQueryHint("Czego wspólnie poszukamy?");
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
//by setting it true we are making it iconified
//so the search input will show up after taping the search iconified
//if you want to make it visible all the time make it false
searchView.setIconifiedByDefault(true);
//here we will get the search query
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//do the search here
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_button:
signOut();
return true;
case R.id.action_settings:
//settings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//------------------------------------------------------------------------------------------
Fragment:
public class DailyFragment extends Fragment{
Toast toast;
private FirebaseFirestore rootRef;
private CollectionReference dailyGoalsRef;
private String userEmail, userName;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_daily, container, false);
FloatingActionButton fab2 = layout.findViewById(R.id.fab2);
fab2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Zadania na dzisiaj");
final EditText editText = new EditText(getContext());
editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
editText.setHint("Podaj cel");
editText.setHintTextColor(Color.GRAY);
builder.setView(editText);
builder.setPositiveButton("Utwórz", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nazwa_celu = editText.getText().toString().trim();
addGoalsList(nazwa_celu);
}
});
builder.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
dailyGoalsRef = rootRef.collection("goalsData").document(userEmail).collection("dailyGoals");
return layout;
}
private void addGoalsList(String nazwa_celu){
String goalsListId = dailyGoalsRef.document().getId();
GoalsModel goalsModel = new GoalsModel(goalsListId, nazwa_celu, userName);
dailyGoalsRef.document(goalsListId).set(goalsModel).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "Lista celów stworzona pomyślnie!");
}
});
}
}
To solve this, change the following lines of code:
if(googleSignInAccount != null){
String userEmail = googleSignInAccount.getEmail();
String userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
with
if(googleSignInAccount != null){
userEmail = googleSignInAccount.getEmail();
userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
This fields are already declared as global.
You are using in your fragment the following line of code:
dailyGoalsRef = rootRef.collection("goalsData").document(userEmail).collection("dailyGoals");
Where the userEmail is null. This is happening because you are not passing the userEmail from the activity to the fragment. Just declaring it as a global variable does not solve the problem.
To solve this, create a method in your activity that returns the userEmail.
public String getUserEmail() {return userEmail;}
And in your fragment, create a String field String userEmail as global and call that method like this:
userEmail = ((MainActivity) getActivity()).getUserEmail();

How can I implement tabs in an Android Browser?

I am trying to implement tab functionality in an Android browser. I tried to save the webpage in a cache, but I can't figure out how to save multiple of them and load them when the user switches tabs. How could I implement this?
I would like to save the current webpage in a cache when the user wants to add a new tab and open Main_activity, and then next time when the user switches tabs, the current webpage should get saved in a cache, and the intended webpage of the intended tab gets loaded in the webview. Now the issue is, I don't know how to handle multiple webpages in a cache, and select which one to load when.
My code consists of two activities, main_activity with some icons and webView_activity with a simple webview. I am using a custom dialog box with a ListView in it, so I will need to add new rows for new tabs and edit them when tabs are switched.
Here is my main_activity
public class MainActivity extends AppCompatActivity {
ImageView yt,google,gm,twitter;
SearchView g_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
g_search = (SearchView) findViewById(R.id.g_search);
g_search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
yt = (ImageView) findViewById(R.id.yt);
google = (ImageView) findViewById(R.id.google);
gm = (ImageView) findViewById(R.id.gm);
twitter = (ImageView) findViewById(R.id.twitter);
yt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.youtube.com");
startActivity(i);
}
});
google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.google.com");
startActivity(i);
}
});
gm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.gmail.com");
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.twitter.com");
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m1, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_new_tab){
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(MainActivity.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(MainActivity.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
Here is my web_view activity
public class webview1 extends AppCompatActivity {
CustomWebView web1;
String search_q,shortcut;
FloatingActionButton fab;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview1);
web1 = (CustomWebView) findViewById(R.id.web1);
web1.setGestureDetector(new GestureDetector(new CustomGestureDetector()));
web1.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(final WebView view, int errorCode, String description,
final String failingUrl) {
fragmentManager.beginTransaction()
.replace(R.id.container, new blankState())
.commit();
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
registerForContextMenu(web1);
// web1.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
web1.getSettings().setJavaScriptEnabled(true);
web1.getSettings().setBuiltInZoomControls(true);
web1.getSettings().setDisplayZoomControls(false);
web1.getSettings().setLoadWithOverviewMode(true);
web1.getSettings().setUseWideViewPort(true);
search_q=getIntent().getStringExtra("query");
shortcut=getIntent().getStringExtra("shortcut");
bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_toolbar);
ImageView action_back = (ImageView) findViewById(R.id.action_back);
action_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
bottomNavigationView.setVisibility(GONE);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// code for launching new tab here
}
});
web1.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress ){
frame_layout.setVisibility(View.VISIBLE);
progress_bar.setProgress(progress);
if(progress==100){
frame_layout.setVisibility(GONE);
srl.setRefreshing(false);
}
super.onProgressChanged(view, progress);
}
});
progress_bar.setProgress(0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_url){
ShowUrlDialog();
return true;
}
if(item.getItemId()==R.id.action_home){
Intent i = new Intent(webview1.this,MainActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_new_tab){
// code to launch new tab here
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(webview1.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(webview1.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m2, menu);
// Associate searchable configuration with the SearchView
return true;
}
#Override
public void onBackPressed() {
if (web1.canGoBack()) {
web1.goBack();
} else {
super.onBackPressed();
}
}
}

Load data from service only once on fragment

I have a fragment that loads data everytime you click on it, I want its behavior to be in a way that if I clicked on it once and moved to another fragment when I go back to it, it does not reload the data and it does not show the "Loading spinner" anymore. How do I do that? This is my fragment code:
public ConsultantFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);//Make sure you have this line of code.
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View consultantView = inflater.inflate(R.layout.fragment_consultant, container, false);
//consultantList = new ArrayList<>();
//consultantLisView = (ListView) consultantView.findViewById(R.id.consultant_listview);
swipeRefreshLayout = (SwipeRefreshLayout) consultantView.findViewById(R.id.consultant_list_swipe_refresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
retrieveConsultantList();
consultantRecyclerView.setAdapter(consultantRecylerViewAdapter);
}
});
consultantRecyclerView = (RecyclerView) consultantView.findViewById(R.id.consultant_recyclerview);
setUpDialog();
FloatingActionButton createConsultantFab = (FloatingActionButton) consultantView.findViewById(R.id.add_consultant);
createConsultantFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent createConsultantIntent = new Intent(getContext(), CreateConsultantActivity.class);
startActivity(createConsultantIntent);
}
});
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.consultant_list_title);
retrieveConsultantList();
return consultantView;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
searchMenuItem = menu.findItem(R.id.action_search);
searchView = (SearchView) searchMenuItem.getActionView();
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
/// searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
consultantRecylerViewAdapter.getFilter().filter(newText);
consultantRecylerViewAdapter.notifyDataSetChanged();
return false;
}
private void setUpConsultantRecyclerView(List<Consultant> consultantList) {
consultantRecylerViewAdapter = new ConsultantRecylerViewAdapter(getContext(), consultantList);
consultantRecyclerView.setAdapter(consultantRecylerViewAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
consultantRecyclerView.setLayoutManager(linearLayoutManager);
consultantRecyclerView.setItemAnimator(new DefaultItemAnimator());
}
public void setUpDialog() {
consultantListLoadingDialog = ProgressDialog.show(getContext(),
"Loading consultant",
"Please wait");
}
private void retrieveConsultantList() {
final StringRequest consultantStringRequest = new StringRequest(Request.Method.GET,
Constants.BASE_URL.concat(Constants.CONSULTANT_KEY_WORD),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//eventList = new ArrayList<>();
JsonDataParser parseJSON = new JsonDataParser();
setUpConsultantRecyclerView(parseJSON.jsonArrayToConsultantList(response));
consultantListLoadingDialog.dismiss();
//consultantListAdapter.addAll();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleyRequestQueue.getInstance(getContext()).addToRequestQueue(consultantStringRequest);
}
}
Remove your method which is getting results from the server from onCreateView. onCreateView called all time when you replace fragments. Instead do one time work in onCreate.
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
retrieveConsultantList();
}

Categories

Resources