Recycle disappear when switching between fragments - android

I have four fragments inside DashboardActvity. I have recycle view in HomeFragment and it is the default page loading first up. Recycle view appear first time but when I switch to another fragment and come again to HomeFragment it disappear.
Here is my DashbaordActivity.
public class DashboardActivity extends AppCompatActivity {
// views
private BottomNavigationView bottomNav;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setOnNavigationItemSelectedListener(bottomNavMethod);
getSupportFragmentManager().beginTransaction().replace(R.id.container, new HomeFragment()).commit() ;
}
// click event listener
private BottomNavigationView.OnNavigationItemSelectedListener bottomNavMethod =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment =null;
switch (item.getItemId()) {
case R.id.home:
fragment = new HomeFragment();
break;
case R.id.chat:
fragment = new ChatFragment();
break;
case R.id.map:
fragment = new MapsFragment();
break;
case R.id.users:
fragment = new UserFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
return true;
}
};
}
Here is my HomeFragment
public class HomeFragment extends Fragment {
// views
private View homeView;
private RecyclerView childList;
private Adapter adapter;
// variables
private IAPI api;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private SharedPreferences preferences;
private List<Child> cList = new ArrayList<>();
private Integer image = R.drawable.avatar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
homeView = inflater.inflate(R.layout.fragment_home, container, false);
preferences = getActivity().getSharedPreferences(Constatnt.MY_PREFERENCE, Context.MODE_PRIVATE);
api = RetrofitClient.getInstance().create(IAPI.class);
childList = homeView.findViewById(R.id.child_rec_view);
adapter = new Adapter(getContext(), cList, image);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2, GridLayoutManager.VERTICAL, false);
childList.setLayoutManager(gridLayoutManager);
childList.setAdapter(adapter);
return homeView;
}
private void getChildren() {
int parentId = preferences.getInt("Id", 0);
compositeDisposable.add(api.getChildren(parentId)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new Consumer<List<Child>>() {
#Override
public void accept(List<Child> children) throws Exception {
for (Child c:children) {
cList.add(c);
}
}
}));
}
#Override
public void onStart() {
super.onStart();
getChildren();
}
}
What is the issue and how I solve this?

override
onViewCreated()
and add set adapter inside this method
childList = view.findViewById(R.id.child_rec_view);
adapter = new Adapter(getContext(), cList, image);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2, GridLayoutManager.VERTICAL, false);
childList.setLayoutManager(gridLayoutManager);
childList.setAdapter(adapter);

Related

Empty RecyclerView on Switching between Fragments

I am trying to implement tablayout in a fragment which is already part of BottomNavigationView, I am facing a problem while navigating through navigation bar, There is a recycler view in a fragment which is the part of tablayout, now when I navigate between fragments via BottomNavigation the recyclerview becomes empty, and there is nothing in the logcat.
MainActivity
public class MainActivity extends AppCompatActivity {
private BottomNavigationView navigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
initComponent();
loadFragment(new HomeFragment());
}
private void initComponent() {
navigation = findViewById(R.id.navigation);
BottomNavigationViewHelper.disableShiftMode(navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// ViewAnimation.fadeOutIn(fragme);
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.home_main:
fragment = new HomeFragment();
break;
case R.id.search:
fragment = new SearchFragment();
break;
case R.id.notifications:
fragment = new NotificationsFragment();
break;
case R.id.favourite:
fragment = new FavouriteFragment();
break;
}
return loadFragment(fragment);
}
});
findViewById(R.id.bt_menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
HomeFragment
public class HomeFragment extends Fragment {
private ViewPager view_pager;
private TabLayout tab_layout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, null);
view_pager = view.findViewById(R.id.view_pager);
setupViewPager(view_pager);
tab_layout = view.findViewById(R.id.tab_layout);
tab_layout.setupWithViewPager(view_pager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new PresetsFragment(), "Presets");
/* adapter.addFragment(new PresetsFragment(), "Tutorials");
adapter.addFragment(new PresetsFragment(), "Categories");*/
viewPager.setAdapter(adapter);
}
#Override
public void onDestroy() {
super.onDestroy();
tab_layout = null;
view_pager = null;
}
PresetsFragment
public class PresetsFragment extends Fragment {
RecyclerView recyclerView;
PresetsAdapter presetsAdapter;
String[] presetList = {"s", "s", "d", "d"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_presets, container, false);
recyclerView = view.findViewById(R.id.presetsRecyclerView);
presetsAdapter = new PresetsAdapter(presetList, getActivity());
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(presetsAdapter);
//presetsAdapter.notifyDataSetChanged();
return view;
}
#Override
public void onResume() {
super.onResume();
}
}
I have spent so many hours to figure it out but still unable to get it..
from your loadFragment method you are using FrameLayout and replacing fragment on BottomNavigation selection when you do so you are creating a new fragment every time if you used a ViewPager it will work fine with you

RecyclerView won't show items until switched between fragments

I am designing an app that has 4 different fragments on the homeActivity using bottomNavigation to switch between them and on the first page that I am using as a news feed, the items do not show until I switch to a different fragment, then back again. I understand there are problems similar to this on SO but no solutions seem to help in my case.
I assume the problem is something to do with the difference in onCreate() and onCreateView in fragments.
Any help is appreciated.
public class HomeFragment extends Fragment {
View v;
private RecyclerView recyclerView;
private List<Drink> drinksList;
RecyclerViewAdapter recyclerViewAdapter;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_home, container, false);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drinksList = new ArrayList<>();
drinksList.add(new Drink("Latte",999,"Coffee","test",1.99,77,R.drawable.latte));
drinksList.add(new Drink("Black Tea",123,"Tea", "test", 1.50,11,R.drawable.blacktea));
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = v.findViewById(R.id.recyclerView);
recyclerViewAdapter = new RecyclerViewAdapter(drinksList,getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
}
}
EDIT
adding HomeActivity
public void setUpMenuNav() {
mMainFrame = findViewById(R.id.mainFrame);
bottomNavigationView = findViewById(R.id.bottomNaviationView);
homeFragment = new HomeFragment();
socialFragment = new SocialFragment();
trackingFragment = new TrackingFragment();
locationFragment = new LocationFragment();
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navHome:
setFragment(homeFragment);
return true;
case R.id.navSocial:
setFragment(socialFragment);
return true;
case R.id.navTracking:
setFragment(trackingFragment);
return true;
case R.id.navLocation:
setFragment(locationFragment);
return true;
default:
return false;
}
}
});
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.mainFrame, fragment);
fragmentTransaction.commit();
}
Then setUpMenuBar is called in the onCreate() method
on your onCreate() method on HomeActivity add setFragment(new HomeFragment()).
that should do the trick.

Open a fragment from a fragment's fragment?

I have a Fragment with a ListView. When I click one of the item, a new Fragment is opened, and from this Fragment I want to open a new Fragment witha a Button.
I try to write the code, but it's a mess. When a click the Button, the program is crashed.
Should I use another way? I call the third Fragment like the second
Activity:
public class Grade extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceSt
ate);
setContentView(R.layout.activity_grade);
BottomNavigationView bottomNav = findViewById(R.id.lista_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
new Objectlist()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_tantargylista:
selectedFragment = new Objectlist();
break;
case R.id.nav_dolgozatlista:
selectedFragment = new Examlist();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
selectedFragment).commit();
return true;
}
};
}
1st Fragment:
public class Objectlist extends Fragment {
View v;
DB mydb;
ListView listView;
private String teszt;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_objectlist, container, false);
listView = (ListView)v.findViewById(R.id.Gradeview);
mydb = new DB(getActivity());
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Nincs jegyek hozzáadva", Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
String jegyAtlag="0";
Cursor data = mydb.JegyekAtlaga(teszt);
while (data.moveToNext()) jegyAtlag=data.getString(0);
String jegyDarab="0";
data = mydb.JegyekDarabszama(teszt);
while (data.moveToNext()) jegyDarab=data.getString(0);
if (jegyAtlag.equals("") || jegyDarab.equals(""))
else {
bundle.putString("Tantárgy átlaga", jegyAtlag);
bundle.putString("Tantárgy darabszáma", jegyDarab);
TextView jegyekHeader = (TextView) v.findViewById(R.id.header);
jegyekHeader.setText(teszt);
Fragment targyAdatok = new targyAdatok();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, targyAdatok);
ListView listaNezet = (ListView) v.findViewById(R.id.Gradeview);
listaNezet.setVisibility(View.GONE);
FragTan.commit();
}
}
}
);
}
return v;
}
}
2nd Fragment:
public class targyAdatok extends Fragment {
public targyAdatok() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_targy_adatok, container, false);
Button elemzes = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.targyAdatok,jegyekAllando);
FragTan.commit();
}
});
return v;
}
}
3rd Fragment:
public class jegyekAllando extends Fragment {
DB mydb;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = getArguments();
String jegyAtlagSt = bundle.getString("Tantárgy átlaga");
String jegyDarabSt = bundle.getString("Tantárgy darabszáma");
return rootView;
}
}
I solved my problem. The problem was that a replaced the wrong fragment. Every time I have to replace the Activity's Fragment.

How to implement a Recycler View with CardView in a Fragment [Android - Java]?

There are quite a few tutorials about this online. However, I've tried many and none of them could do what I expected properly.
I'm very new to Android and App development, but have some experience developing websites and API's. I have developed a website and wanted to create a simple Android app to show a feed of events for the users.
So after some research, it seems the best way to handle efficiently big lists of JSON Data coming from an API is with RecyclerView, and CardViews would boost up a little the design.
So I setup a project with a bottom navbar and have created three tabs (Events, Profile and Notifications). These tabs return a Fragment and the List should be inside the Events Fragment. I have hardcoded it to display 5 items, but it never shows up the cards. So I'm not sure where its wrong. The other fragments show up correctly
Here's my code:
BaseFragment
public abstract class BaseFragment extends AppCompatActivity {
protected abstract Fragment createFragment();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.content);
if(fragment == null){
fragment = createFragment();
fm.beginTransaction()
.add(R.id.events_fragment_container, fragment)
.commit();
}
}
}
Events Fragment, Adapter and ViewHolder
public class EventsRecyclerFragment extends Fragment{
public static Fragment newInstance(){
return new EventsRecyclerFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.events_recycler_view_fragment, container, false);
RecyclerView recyclerView = view.findViewById(R.id.events_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(new EventsRecyclerViewAdapter());
return view;
}
private class EventsRecyclerViewHolder extends RecyclerView.ViewHolder{
private CardView mCardView;
private TextView mTextView;
public EventsRecyclerViewHolder(View itemView) {
super(itemView);
}
public EventsRecyclerViewHolder(LayoutInflater inflater, ViewGroup container){
super(inflater.inflate(R.layout.events_card_view, container, false));
mCardView = itemView.findViewById(R.id.events_card_container);
}
}
private class EventsRecyclerViewAdapter extends RecyclerView.Adapter<EventsRecyclerViewHolder>{
#Override
public EventsRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(getContext());
return new EventsRecyclerViewHolder(inflater, parent);
}
#Override
public void onBindViewHolder(EventsRecyclerViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 5;
}
}
}
How I'm using on Activity
public class UserActivity extends AppCompatActivity {
public static final String PREFS_NAME = "Preferences";
private static final String PREF_EMAIL = "EMAIL";
private static final String PREF_PASSWORD = "PASSWORD";
private static final String PREF_TOKEN = "TOKEN";
Button btnLogout;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
switch (item.getItemId()) {
case R.id.navigation_events:
transaction.replace(R.id.content, new EventsRecyclerFragment().newInstance()).commit();
return true;
case R.id.navigation_profile:
transaction.replace(R.id.content, new UserFragment()).commit();
return true;
case R.id.navigation_notifications:
transaction.replace(R.id.content, new NotificationsFragment()).commit();
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
btnLogout = (Button) findViewById(R.id.btnLogin);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
}
Could anyone help me on how would I make this basic list show up?
Thanks in advance
Two changes are required :
UserActivity : Remove the new keyword from EventsRecyclerFragment() instance initialization as the newInstance() method returns a new instance itself.
public class UserActivity extends AppCompatActivity {
public static final String PREFS_NAME = "Preferences";
private static final String PREF_EMAIL = "EMAIL";
private static final String PREF_PASSWORD = "PASSWORD";
private static final String PREF_TOKEN = "TOKEN";
Button btnLogout;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
switch (item.getItemId()) {
case R.id.navigation_events:
transaction.replace(R.id.content, EventsRecyclerFragment().newInstance()).commit();
return true;
case R.id.navigation_profile:
transaction.replace(R.id.content, new UserFragment()).commit();
return true;
case R.id.navigation_notifications:
transaction.replace(R.id.content, new NotificationsFragment()).commit();
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
}
EventsRecyclerFragment : Always set orientation of recycler view during its initialization.
public class EventsRecyclerFragment extends Fragment{
public static Fragment newInstance(){
return new EventsRecyclerFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.events_recycler_view_fragment, container, false);
RecyclerView recyclerView = view.findViewById(R.id.events_recycler_view);
LinearLayoutManager linearLayoutManager =new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(new EventsRecyclerViewAdapter());
return view;
}
private class EventsRecyclerViewHolder extends RecyclerView.ViewHolder{
private CardView mCardView;
private TextView mTextView;
public EventsRecyclerViewHolder(View itemView) {
super(itemView);
}
public EventsRecyclerViewHolder(LayoutInflater inflater, ViewGroup container){
super(inflater.inflate(R.layout.events_card_view, container, false));
mCardView = itemView.findViewById(R.id.events_card_container);
}
}
private class EventsRecyclerViewAdapter extends RecyclerView.Adapter<EventsRecyclerViewHolder>{
#Override
public EventsRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(getContext());
return new EventsRecyclerViewHolder(inflater, parent);
}
#Override
public void onBindViewHolder(EventsRecyclerViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 5;
}
}
}

Load only one fragment and replace its content only

Actually, i created a navigation drawer that has three items and on clicking on every item it goes to its fragment that displays certain type of products , so i have an Activity with three fragments for each type of them.
If i would like to add another product type i will have to create its fragment.
So ,My question is , are there any methods that can only make one fragment and every time an item is clicked only the data inside the fragment to be changed/replaced and not to replace the whole fragment itself with another ?
Edited my main activity:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
DrawerLayout drawerLayout;
RecyclerView recyclerView;
String navTitles[];
private NavigationView navigationView;
TypedArray navIcons;
RecyclerViewAdapter recyclerViewAdapter;
ActionBarDrawerToggle drawerToggle;
Fragment[] fFragments = new Fragment[3];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Let's first set up toolbar
setupToolbar();
//Initialize Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerMainActivity);
//Setup Titles and Icons of Navigation Drawer
navTitles = getResources().getStringArray(R.array.navDrawerItems);
navIcons = getResources().obtainTypedArray(R.array.navDrawerIcons);
recyclerViewAdapter = new RecyclerViewAdapter(navTitles, navIcons, this);
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.setClickedListener(new RecyclerViewAdapter.ClickListerner() {
#Override
public void onItemlistener(int index) {
updateUIWithIndex(index);
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//Finally setup ActionBarDrawerToggle
setupDrawerToggle();
//Add the Very First Fragment to the Container
updateUIWithIndex(1);
}
// on click update fragment
private void updateUIWithIndex(int index) {
drawerLayout.closeDrawers();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment fFragment = null;
if (fFragments[index - 1] == null) {
switch (index) {
case 1:
fFragment = new FirstFragment();
break;
case 2:
fFragment = new SecondFragment();
break;
case 3:
fFragment = new ThirdFragment();
break;
}
fFragments[index - 1] = fFragment;
} else {
fFragment = fFragments[index - 1];
}
fragmentTransaction.replace(R.id.containerView, fFragment);
fragmentTransaction.commit();
}
void setupToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
void setupDrawerToggle() {
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
//This is necessary to change the icon of the Drawer Toggle upon state change.
drawerToggle.syncState();
}
}
My Fragment :
public class FirstFragment extends Fragment implements ClickListner {
private final String LOG_TAG = FirstFragment.class.getSimpleName();
private DisplayAdapter recyclerViewAdapter;
private RecyclerView recyclView;
private ArrayList<Products> pProduct = null;
private List<Products> prods = null;
ProductDbHelper pDB;
ProgressDialog mJsonDialog;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.all_products, container, false);
pDB = new ProductDbHelper(getActivity());
mJsonDialog = new ProgressDialog(getActivity());
mJsonDialog.setIndeterminate(true);
if (pDB.isDataAvailable() == 0) {
mJsonDialog.setMessage("Parsing JSON feed...");
mJsonDialog.show();
getFeed();
} else {
new FetchDatabaseTask().execute();
}
return myView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclView = (RecyclerView) view.findViewById(R.id.RecycleList);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclView.setLayoutManager(layoutManager);
recyclerViewAdapter = new DisplayAdapter(getActivity(), new ArrayList<Products>());
recyclView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.setClickListener(this);
}
#Override
public void itemClicked(View view, Parcelable product) {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("P", product);
startActivity(intent);
}
public void getFeed() {
RestInterface interfaces = Client.getClient().create(RestInterface.class);
Call<List<Products>> call = interfaces.getProductsReport();
call.enqueue(new Callback<List<Products>>() {
#Override
public void onResponse(Call<List<Products>> call, Response<List<Products>> response) {
prods = response.body();
for (int i = 0; i < prods.size(); i++) {
pDB.addShop(prods.get(i));
}
new FetchDatabaseTask().execute();
if (mJsonDialog.isShowing())
mJsonDialog.dismiss();
}
#Override
public void onFailure(Call<List<Products>> call, Throwable t) {
Log.e(LOG_TAG, "FFFF" + t.toString());
}
});
}
public class FetchDatabaseTask extends AsyncTask<Void, Void, List<Products>> {
protected void onPreExecute() {
mJsonDialog.setMessage("Reading from internal storage...");
mJsonDialog.show();
}
#Override
protected List<Products> doInBackground(Void... voids) {
// get all the shop's products
List<Products> lProduct = pDB.getAllShops();
// in the second fragment , sort the products' price in ascending order
List<Products> lProduct = pDB.sortShopsAscend();
// in the third fragment sort the products descendingly
List<Products> lProduct = pDB.sortShopsDescend();
return lProduct;
}
protected void onPostExecute(List<Products> shops) {
super.onPostExecute(shops);
if (shops != null) {
if (recyclerViewAdapter != null) {
recyclerViewAdapter.setData(shops);
} else {
pProduct = new ArrayList<>();
pProduct.addAll(shops);
}
}
if (mJsonDialog.isShowing())
mJsonDialog.dismiss();
}
}
}
Make those changes in the MainActivity class :
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
DrawerLayout drawerLayout;
RecyclerView recyclerView;
String navTitles[];
private NavigationView navigationView;
TypedArray navIcons;
RecyclerViewAdapter recyclerViewAdapter;
ActionBarDrawerToggle drawerToggle;<
//If you want to use the first fragment only
FirstFragment fragment = null;
.
.
.
recyclerViewAdapter.setClickedListener(new RecyclerViewAdapter.ClickListerner() {
#Override
public void onItemlistener(int index) {
//Call this method to close the drawer layout or you can simply call the close method here
updateUIWithIndex(index);
//Do something depending on the index
if(index == 0){
//Call getFeed() for example
fragment.getFeed();
}
else if(index == 1){
//call another method
}
}
});
.
.
.
// on click update fragment
//I don't know if you still need the index in this method
private void updateUIWithIndex(int index) {
//Close the drawer Layout anyway
drawerLayout.closeDrawers();
if (fragment == null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
//Create an instance of the FirstFragment
fragment = new FirstFragment();
fragmentTransaction.replace(R.id.containerView, fragment);
fragmentTransaction.commit();
}
}
You can simply pass variable to Fragment method.
Completely updated post
In your case:
set fragment as field in your MainActivity
private FirstFragment firstFragment;
Run this fragment in your OnCreate method in MainActivity
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
firstFragment = null;
firstFragment = new FirstFragment();
fragmentTransaction.replace(R.id.containerView, firstFragment );
fragmentTransaction.commit();
Then replace updateUIWithIndex method to fragment method, so you have:
recyclerViewAdapter.setClickedListener(new RecyclerViewAdapter.ClickListerner() {
#Override
public void onItemlistener(int index) {
firstFragment.getFeed(index)
}
});
Pass index to getFeed:
public void getFeed(int index) {
final int currentIndex = index;
RestInterface interfaces = Client.getClient().create(RestInterface.class);
Call<List<Products>> call = interfaces.getProductsReport();
call.enqueue(new Callback<List<Products>>() {
#Override
public void onResponse(Call<List<Products>> call, Response<List<Products>> response) {
prods = response.body();
for (int i = 0; i < prods.size(); i++) {
pDB.addShop(prods.get(i));
}
new FetchDatabaseTask(currentIndex ).execute();
if (mJsonDialog.isShowing())
mJsonDialog.dismiss();
}
#Override
public void onFailure(Call<List<Products>> call, Throwable t) {
Log.e(LOG_TAG, "FFFF" + t.toString());
}
});
Add constructor to FetchDatabaseTask class
public class FetchDatabaseTask extends AsyncTask<Void, Void, List<Products>> {
private int currentIndex = 0;
FetchDatabaseTask(int index) {
currentIndex = index;
}
//ur others methods here
}
And then you can do as you need in onPreExecute,doInBackground and onPostExecute methods like this:
protected void onPostExecute(List<Products> shops) {
super.onPostExecute(shops);
switch (currentIndex) {
case 0:
if (shops != null) {
if (recyclerViewAdapter != null) {
recyclerViewAdapter.setData(shops);
} else {
pProduct = new ArrayList<>();
pProduct.addAll(shops);
}
}
if (mJsonDialog.isShowing())
mJsonDialog.dismiss();
break;
case 1:
//ur SecondFragment code
break;
case 2:
//ur ThirdFragment code
break;
}
}
So you can use only one fragment for every type of product or whatever you want.

Categories

Resources