Send data from fragment to another fragment - android

I have a fragment in which I'm asking the user to select his team. It opens another fragment and user can select his team. But I'm stuck because unable to send the team details to the previous fragment.
User clicks the button to set home team, select the team from team_select_fragment, but I'm unable to send team details to the first fragment.
Below is the code for mathc_fragment where the user fills match data:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_create_match, container, false);
Toolbar toolbar = rootView.findViewById(R.id.nav_toolbar);
((PlayerProfileActivity) getActivity()).getSupportActionBar().setTitle("Create Match");
city_name = rootView.findViewById(R.id.cityNameEditText);
ground_name = rootView.findViewById(R.id.groundNameEditText);
setupImageButton(rootView);
setupNumberOfPlayersButton(rootView);
setupHalfTimeButton(rootView);
preferenceConfig = new SharedPreferenceConfig(this.getContext());
requestQueue = Volley.newRequestQueue(getActivity());
Button startMatch = rootView.findViewById(R.id.start_match_bn);
return rootView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
rootActivity = (PlayerProfileActivity) context;
} catch (Exception exception) {
rootActivity = null;
}
}
private void setupImageButton(final View rootView) {
//Select Home team
ImageButton homeTeamImageButton = rootView.findViewById(R.id.homeTeamImageButton);
homeTeamImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getChildFragmentManager().beginTransaction().add(R.id.create_match_container,new TeamSelect()).commit();
}
});
//select away team
ImageButton awayTeamImageButton = rootView.findViewById(R.id.awayTeamImageButton);
awayTeamImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getChildFragmentManager().beginTransaction().add(R.id.create_match_container,new TeamSelect()).commit();
}
});
}
This is the code for team_select_fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_team_select, container, false);
editText = rootView.findViewById(R.id.team_select_search);
recyclerView = rootView.findViewById(R.id.team_select_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
list_items = new ArrayList<>();
teamSelectAdapter = new TeamSelectAdapter(list_items, getContext());
recyclerView.setAdapter(teamSelectAdapter);
teamSelectAdapter.setOnItemClickListener(this);
loadRecyclerViewData();
return rootView;
}
private void loadRecyclerViewData() {
stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
int success = jsonObject.getInt("success");
if(success==1){
JSONArray jsonArray = jsonObject.getJSONArray("Teams");
for (int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject_current = jsonArray.getJSONObject(i);
TeamSelectModelClass teamSelectModelClass = new TeamSelectModelClass(
jsonObject_current.getString("team_id"),
jsonObject_current.getString("team_name"),
jsonObject_current.getString("team_logo_url")
);
list_items.add(teamSelectModelClass);
}
teamSelectAdapter.notifyDataSetChanged();
}else if(success==0){
String message = jsonObject.getString("Message");
Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
})
};
requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public void onItemClick(int position) {
TeamSelectModelClass clickedItem = list_items.get(position);
String team_id = clickedItem.getTeam_id();
String team_name = clickedItem.getTeam_name();
String team_logo = clickedItem.getTeam_logo_url();
}

2 solution :
-If you back to the fragment (by create new fragment),create a call back like
A extends Fragment(){
public A setMethod(X a){
this.a = a;
return this;
}
}
and in fragment B call
new A().setData(yourdata)
Second solution is you just add your data to SharePreference and get it when you return from the other fragment

use following method in your parent Activity(Activity where you are loading your fragments)
public void changeFragment(Fragment nextFragment, boolean addToBackstack) {
int containerId = R.id.content_frame;
FragmentManager fragmentManager = getSupportFragmentManager();
final FragmentTransaction transaction = fragmentManager
.beginTransaction();
if (fragmentManager.findFragmentById(containerId) != null) {
fragmentName = fragmentManager.findFragmentById(containerId);
}
transaction.replace(containerId, nextFragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (addToBackstack == true) {
transaction.addToBackStack(fragmentName.getClass().getName());
}
currentFragment = nextFragment.getClass().toString();
transaction.commit();
}
and call this method in your fragments wherever you want as follows
YourFragment yourFragment = new YourFragment ();
final MainActivity mainActivity = (MainActivity) activity;
mainActivity.changeFragment(yourFragment, true);

Related

Passing Search Result From fragment To Another fragment

I Have Fragment That Do the Search And Get The Result From The Server
and send the Result To another Fragment withe list view
To show it . the result it show empty list nothing show
Fragment Search
public class Search extends Fragment implements View.OnClickListener {
EditText Drugname;
Button SendDrug;
private ProgressDialog plog;
private List<SearchAvailDrug> drugreq= new ArrayList<SearchAvailDrug> () ;
private CustomListAdapter adapter;
public Search() {
// Required empty public constructor
}
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
Drugname=(EditText) view.findViewById(R.id.searchdrug);
SendDrug =(Button) view.findViewById(R.id.startdrug) ;
adapter = new CustomListAdapter(this, drugreq);
SendDrug.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
SendDataUp(Drugname.getText().toString());
}
#Override
public void onDetach() {
super.onDetach();
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void SendDataUp(final String Drugname){
Log.i("SendDataUp","Start");
String url = Urls.URL_AvailDrug;
//showing dialog box
plog = new ProgressDialog(getActivity());
plog.setIndeterminate(false);
plog.setMessage("Registration Please wait ...");
plog.show();
// Start Using Volley
// Request a string response
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(String response) {
hidePDialog();
String UserIdNum=null;
Log.v("Search",response);
try {
if (response.equalsIgnoreCase(String.valueOf(false)))
{
hidePDialog();
;
}
else
{
for (int i = 0; i < response.length(); i++) {
JSONArray RideJArray = new JSONArray(response);
SearchAvailDrug ride = new SearchAvailDrug(); ride.setDrugBrand(jpart.getString("BrandName")); ride.setPharmcyNameAr(jpart.getString("phname_ar")); ride.setPharmcyNameEn(jpart.getString("phname_ar"));
ride.setPhinfo(jpart.getString("info")); ;
ride.setLang(jpart.getDouble("lang"));
ride.setLat(jpart.getDouble("lat"));
drugreq.add(ride);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
Bundle args = new Bundle();
args.putParcelableArrayList("mylist", (ArrayList<? extends Parcelable>) drugreq);
Fragment fragment = new Listpage();
fragment.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_nav_main, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
// shownextpage();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidePDialog();
// Error handling
System.out.println("Something went wrong!");
error.printStackTrace();
Toast.makeText(getActivity(), "FAILED TO CONNECT",Toast.LENGTH_LONG).show();
}
})
{
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("BrandName",Drugname);
return params;
}
};
// Add the request to the queue
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
private void shownextpage(){
Bundle args = new Bundle();
Fragment fragment = new Listpage();
fragment.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_nav_main, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private void hidePDialog() {
if (plog != null) {
plog.dismiss();
plog = null;
}
}
}
and it show it in the another fragment List view
and here is the code
public class Listpage extends Fragment {
private ListView listView;
private CustomListAdapter adapter;
private List<SearchAvailDrug> drugreq= new ArrayList<SearchAvailDrug>() ;
public Listpage() {
// 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_Listpage_list, container, false);
Bundle args = getArguments();
ArrayList<SearchAvailDrug>arrayList;
// arrayList = (ArrayList<SearchAvailDrug>)args.getParcelableArrayList("mylist");
drugreq = args.getParcelableArrayList("mylist");
adapter = new CustomListAdapter(this, drugreq);
listView = (ListView) view.findViewById(R.id.listpharmcy);
listView.setAdapter(adapter);
return view;
}
}
the problem it show me empty list view
after i load the fragment
You should follow the "newInstance" recommendation when dealing with Fragments and arguments, otherwise, Android OS might recreate the instance with null arguments.
https://stackoverflow.com/a/9245510/6828464

Tablayout on swipe not refreshing in android

I am implementing tablayout using view pager and in my scenario I have two tab. In my first tab I have add data which store in share preference. and when I move to second tab then data should be retrieve from share preference and show in listview. When I add the data from my first tab then data is added successfully but not show in my second tab means I have to close my application and again restart the app so that I can see saved the detail which saved from my first tab.
Below is my Activity code.
public class FragmentExample extends AppCompatActivity {
private ViewPagerAdapter viewPagerAdapter;
#BindView(R.id.tabCountryState)
TabLayout tabCountryState;
#BindView(R.id.viewPager)
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_example);
ButterKnife.bind(this);
setViewPager();
setTabIcon();
viewPager.setOffscreenPageLimit(2);
tabCountryState.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.e("Current tab is ", "===> " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setViewPager() {
// set Adaapter.
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), FragmentExample.this);
viewPager.setAdapter(viewPagerAdapter);
tabCountryState.setupWithViewPager(viewPager);
}
// set custom icon to tab in Tablayout.
private void setTabIcon() {
// First Tab
View firstTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_first, null);
TextView tvFirsIcon = ButterKnife.findById(firstTab, R.id.tvFirsIcon);
tvFirsIcon.setText("First Tab");
tabCountryState.getTabAt(0).setCustomView(firstTab);
// First Tab
View secondTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_second, null);
TextView tvSecondIcon = ButterKnife.findById(secondTab, R.id.tvSecondIcon);
tvSecondIcon.setText("Second Tab");
tabCountryState.getTabAt(1).setCustomView(secondTab);
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Context context;
private FirstFragment firstFragment;
private SecondFragment secondFragment;
public ViewPagerAdapter(FragmentManager fm, Context mainActivity) {
super(fm);
context = mainActivity;
new FirstFragment();
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
firstFragment = new FirstFragment();
return firstFragment;
case 1:
secondFragment = new SecondFragment();
return secondFragment;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return " " + position;
}
}
}
Here is my FirstFragment in which I have added the data into share preference.
public class FirstFragment extends Fragment {
private View v;
#BindView(R.id.btnSubmit)
Button btnSubmit;
#BindView(R.id.edtCityName)
EditText edtCityName;
#BindView(R.id.spStateName)
Spinner spStateName;
private Unbinder unbinder;
private ArrayList<String> alStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private SpinnerStateAdapter spinnerAdapter;
private int spinnerPosition;
private String strCityName, strSpinnerValue;
#OnClick(R.id.btnSubmit)
public void submit(View view) {
if (spinnerPosition !=0) {
strCityName = edtCityName.getText().toString().trim();
alAllStateCity = SessinoManager.getCityList(getActivity());
if (strCityName.length() > 0) {
alAllStateCity.get(spinnerPosition).getAlCityName().add(new CityStateModel(strCityName));
} else {
}
// Save new data to Session.
SessinoManager.saveCityList(getActivity(), alAllStateCity);
SecondFragment.cityAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "Detail saved successfully ", Toast.LENGTH_SHORT).show();
edtCityName.setText("");
} else {
Toast.makeText(getActivity(), "Please select state", Toast.LENGTH_SHORT).show();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_first, container, false);
unbinder = ButterKnife.bind(this, v);
// arraylist checking if data is available into session.
if(SessinoManager.getCityList(getActivity()).size()>0){
Log.e("First fragment "," if condition ");
alAllStateCity = SessinoManager.getCityList(getActivity());
alStateName = new ArrayList<>();
for(int i=0;i<alAllStateCity.size();i++){
alStateName.add(alAllStateCity.get(i).getStrStateName());
}
setStateSpinner();
}else{
loadArraylist();
setStateSpinner();
}
return v;
}
private void setStateSpinner() {
spStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
strSpinnerValue = alStateName.get(i).toString().trim();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinnerAdapter = new SpinnerStateAdapter(getActivity(), alStateName);
spStateName.setAdapter(spinnerAdapter);
}
private void loadArraylist() {
alAllStateCity = new ArrayList<>();
alStateName = new ArrayList<>();
alStateName.add(0, "Select State");
alStateName.add("Gujarat");
alStateName.add("Maharashtra");
alStateName.add("Madhya Pradesh");
for (int i = 0; i < alStateName.size(); i++) {
alAllStateCity.add(new AllStateCityModel(alStateName.get(i), alAllStateCity.size(), new ArrayList<CityStateModel>()));
}
SessinoManager.saveCityList(getActivity(), alAllStateCity);
}
#Override public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
Log.e("First fragment "," on destroy");
}
}
Here is my SecondFragment in which I have to get saved detail from Share preference.
public class SecondFragment extends Fragment {
private View v;
private Unbinder unbinder;
#BindView(R.id.lvCityList)
ListView lvCityList;
#BindView(R.id.spinnerStateName)
Spinner spinnerStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private ArrayList<CityStateModel> alCityName;
private ArrayList<String> alStateName;
private int spinnerPosition;
private SpinnerStateAdapter spinnerAdapter;
private ArrayList<String> alCity;
public static CityAdapter cityAdapter;
private Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_two, container, false);
unbinder = ButterKnife.bind(this, v);
context = getActivity();
loadArrayList(context);
Log.e("onCreateView", "onCreateView");
return v;
}
private void loadArrayList(Context context) {
alCityName = new ArrayList<>();
alStateName = new ArrayList<>();
alAllStateCity = SessinoManager.getCityList(context);
for (int j = 0; j < alAllStateCity.size(); j++) {
// Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName());
// get state name from session
alStateName.add(alAllStateCity.get(j).getStrStateName());
setSpinner(context);
}
}
private void setSpinner(Context context) {
spinnerAdapter = new SpinnerStateAdapter(context, alStateName);
spinnerStateName.setAdapter(spinnerAdapter);
spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
setList(spinnerPosition);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setList(int position) {
alCityName = alAllStateCity.get(position).getAlCityName();
alCity = new ArrayList<>();
for (int i = 0; i < alCityName.size(); i++) {
// Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity());
alCity.add(alCityName.get(i).getStrCity());
}
cityAdapter = new CityAdapter(context, alCity);
lvCityList.setAdapter(cityAdapter);
cityAdapter.notifyDataSetChanged();
}
}
And I am saving data into Share preference which is given below.
public class SessinoManager {
private static final String CITY_PREFERENCE = "city_preference";
// Save data to share preference.
public static void saveCityList(Context context, ArrayList<AllStateCityModel> alAllPlayList) {
try {
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonUsers = gson.toJson(alAllPlayList);
editor.putString("all_play_list", jsonUsers);
editor.commit();
// Check to save data into share preferent
for(int j=0;j<alAllPlayList.size();j++){
Log.e("State name ","----------------------"+alAllPlayList.get(j).getStrStateName());
ArrayList<CityStateModel> cityName = alAllPlayList.get(j).getAlCityName();
for(int i=0;i<cityName.size();i++){
Log.e("cityName "," in session ==> "+cityName.get(i).getStrCity());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static ArrayList<AllStateCityModel> getCityList(Context context)
{
SharedPreferences settings;
List<AllStateCityModel> users = new ArrayList<>();
settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE);
if (settings.contains("all_play_list"))
{
String jsonUsers = settings.getString("all_play_list", null);
Gson gson = new Gson();
AllStateCityModel[] userItems = gson.fromJson(jsonUsers,AllStateCityModel[].class);
users = Arrays.asList(userItems);
users= new ArrayList<AllStateCityModel>(users);
}
return (ArrayList<AllStateCityModel>) users;
}
}
When I add new city detail into first tab then data is data successfully but when I swipe or move to next then data is not displaying and I have to restart whole application to get updated data from Share preference. Kindly help me to resolve this issue. Thanks in advance.
I have resolved the problem by implementing below method setUserVisibleHint.
public class SecondFragment extends Fragment {
private View v;
private Unbinder unbinder;
#BindView(R.id.lvCityList)
ListView lvCityList;
#BindView(R.id.spinnerStateName)
Spinner spinnerStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private ArrayList<CityStateModel> alCityName;
private ArrayList<String> alStateName;
private int spinnerPosition;
private SpinnerStateAdapter spinnerAdapter;
private ArrayList<String> alCity;
public static CityAdapter cityAdapter;
private Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_two, container, false);
unbinder = ButterKnife.bind(this, v);
context = getActivity();
loadArrayList(context);
// Log.e("onCreateView", "onCreateView");
return v;
}
private void loadArrayList(Context context) {
alCityName = new ArrayList<>();
alStateName = new ArrayList<>();
alAllStateCity = SessinoManager.getCityList(context);
for (int j = 0; j < alAllStateCity.size(); j++) {
// Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName());
// get state name from session
alStateName.add(alAllStateCity.get(j).getStrStateName());
setSpinner(context);
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.e("setUserVisibleHint","setUserVisibleHint "+isVisibleToUser);
if(isVisibleToUser==true){
loadArrayList(context);
}
}
#Override
public boolean getUserVisibleHint() {
Log.e("getUserVisibleHint","getUserVisibleHint "+super.getUserVisibleHint());
return super.getUserVisibleHint();
}
private void setSpinner(Context context) {
spinnerAdapter = new SpinnerStateAdapter(context, alStateName);
spinnerStateName.setAdapter(spinnerAdapter);
spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
setList(spinnerPosition);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setList(int position) {
alCityName = alAllStateCity.get(position).getAlCityName();
alCity = new ArrayList<>();
for (int i = 0; i < alCityName.size(); i++) {
// Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity());
alCity.add(alCityName.get(i).getStrCity());
}
cityAdapter = new CityAdapter(context, alCity);
lvCityList.setAdapter(cityAdapter);
cityAdapter.notifyDataSetChanged();
}
}

How to save loaded listView state in fragment?

I have one activity, fragment with listView and fragment with details for each listView item. I am getting fragments data from API. How should I save loaded date and listView position correctly to be able to restore it when I am returning back to the listView?
I tried to implement this solution Once for all, how to correctly save instance state of Fragments in back stack? but I cannot restore my listView correctly.
My MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
listFragment = new ListFragment();
fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, listFragment);
fragmentTransaction.commit();
if (savedInstanceState != null) {
//Restore the fragment's instance
listFragment = (ListFragment)getSupportFragmentManager().getFragment(savedInstanceState, "listContent");
}
...
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "listContent", listFragment);
}
and ListFragment
public class ListFragment extends Fragment {
public static final String REQUEST_TAG = "ProjectListFragment";
private int page;
private View view;
private RelativeLayout loading ;
private PagingListView listView;
private PagingProjectListAdapter adapter;
private ArrayList<String> projects = new ArrayList<>();
private ArrayList<String> loadedProjects = new ArrayList<>();
public ListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_list, container, false);
listView = (PagingListView) view.findViewById(R.id.projectsListView);
loading = (RelativeLayout) view.findViewById(R.id.loading);
//page = 1;
adapter = new PagingProjectListAdapter(getContext(), ListFragment.this);
listView.setAdapter(adapter);
listView.setHasMoreItems(true);
// Inflate the layout for this fragment
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// FIXME not used
listView.onFinishLoading(true, projects);
//Restore the fragment's state here
} else {
projects.clear();
page = 1;
listView.setPagingableListener(new PagingListView.Pagingable() {
#Override
public void onLoadMoreItems() {
new CustomVolleyAsyncTask().execute();
}
});
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentPosition", 0);
//Save the fragment's state here
}
public void itemClickMethod(View detailsView) {
LinearLayout linearLayout = (LinearLayout) detailsView;
String bid = linearLayout.getContentDescription().toString();
Bundle bundle = new Bundle();
String k = "ProjectID";
bundle.putString(k, bid);
DetailsFragment detailsFragment = new DetailsFragment();
detailsFragment.setArguments(bundle);
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, detailsFragment, "DetailsFragmentTag");
ft.addToBackStack(null);
ft.commit();
}
private class CustomVolleyAsyncTask extends SafeAsyncTask<List<String>> implements Response.Listener,
Response.ErrorListener {
public List<String> status = null;
private RequestQueue mQueue;
#Override
public List<String> call() throws Exception {
mQueue = CustomVolleyRequestQueue.getInstance(view.getContext())
.getRequestQueue();
String url = "http://www.myapi.com/api/v1/data/" + Integer.toString(page);
final CustomJSONObjectRequest jsonRequest = new CustomJSONObjectRequest(Request.Method
.GET, url,
new JSONObject(), this, this);
jsonRequest.setTag(REQUEST_TAG);
mQueue.add(jsonRequest);
// TODO rm redundant result
return status;
}
#Override
public void onErrorResponse(VolleyError error) {
// FIXME check no response case crash
//mTextView.setText(error.getMessage());
}
#Override
public void onResponse(Object response) {
try {
JSONArray projectsJSON = new JSONArray(((JSONObject) response).getString("projects"));
loadedProjects.clear();
for (int i=0; i < projectsJSON.length(); i++) {
loadedProjects.add(projectsJSON.getJSONObject(i).toString());
}
page++;
listView.onFinishLoading(true, loadedProjects);
if (loading.getVisibility() == View.VISIBLE && !listView.isLoading()){
listView.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}}}
}
currently, my savedInstanceState is always null, what am I missing?
I think, that your fragment created twice, when configuration changed. Here Staffan explain, why this happend. I resolve similar problem by this way (in activity onCreate):
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(TAG);
if(fragment==null)
fragmentManager.beginTransaction()
.add(R.id.container, NewsFragment.newInstance(),TAG)
.commit();

Fragment disappearing when coming back from another Fragment

I have a viewpager with 3 fragments to make a swipeable widget. When I first load the app they show properly and all the click events work as expected. Same with hitting the back button after clicking each OnClick, sends me back to landingpagenotlogged in and the viewpager/fragments are displayed as expected. My problem is when I hit my menu button and come back to the landing page my view pager disappears.
I did try to use getChildFragmentManager() when setting the adapter and it works but then my onClick events do not work any more as I get no view to id *******.
I have also tried to place the adapter in the onResume(); with no luck at all.
Along with the viewpager, my viewpagerindicator is not working for the homewidget but working for the carousel. Not sure if that is the code or the layout. But I set it up the same way as the carousel and still not seeing it within the screen when run.
Landingpagenotlogged
public class LandingPageFragmentLoggedOut extends LandingPageFragment {
private static final String TAG = LandingPageFragmentLoggedOut.class.getSimpleName();
private ViewPager viewPager;
private RelativeLayout myStoreTab;
private Button signIn;
private final static Fragment instance = new LandingPageFragmentLoggedOut();
LoggedOutWidgetAdapter mAdapter;
ViewPager mPager;
public static final int ITEMS = 3;
static public Fragment getInstance() {
return instance;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
getActivity().startService(new Intent(getActivity().getApplicationContext(),
WeeklyAdService.class));
setShoppingListFocusChangeListener();
setSignInBtnClickListener();
super.setViewPagerMotionListeners(viewPager);
setMenuTouchListener();
setTabClickListener();
return view;
}
#Override
protected void inflateFragmentView(LayoutInflater inflater, ViewGroup container) {
view = inflater.inflate(R.layout.landingpage_not_logged_in, container,
false);
RelativeLayout thisLayout = (RelativeLayout) view
.findViewById(R.id.landingpage_logged_out_parent_layout);
TileBackground.fixBackgroundRepeat(thisLayout);
imgArch = view.findViewById(R.id.frag_tab);
}
private void setSignInBtnClickListener() {
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, String> params = new HashMap<>();
Intent intent = new Intent(getActivity(), SignInActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(
R.anim.enter_in_from_bottom, R.anim.anim_static);
params.put("Module", "Home");
FlurryAgent.logEvent(FlurryConstants.GOTO_SIGN_IN, params);
}
});
}
private void setTabClickListener() {
myStoreTab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tabSelection = 1;
tabSelectionListener.onTabSelectionListener(tabSelection);
toggleStoreTabIndicator(1);
}
});
}
#Override
#SuppressLint("WrongViewCast")
protected void setUIreferences() {
viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
overlay = view.findViewById(R.id.landingpage_screenOverlay);
indicator = (LinePageIndicator) view.findViewById(R.id.image_slider_indicator);
this.signIn = (Button) view.findViewById(R.id.landingpg_sign_in_btn);
shoppingListBtn = (ImageView) view.findViewById(R.id.icnlistoptions);
myStoreTab = (RelativeLayout) view.findViewById(R.id.frag_tab);
menuButton = (Button) view.findViewById(R.id.imgBanner_list);
logoButton = (ImageView) view.findViewById(R.id.headerLogo);
addShoppingListItemWidget = (EditText) view.findViewById(R.id.editAddItemNotLoggedIn);
addShoppingListItemWidget.setOnKeyListener(null);
addedItemConfirmation = view.findViewById(R.id.addedItemConfirmation);
imgScanner = (ImageView) view.findViewById(R.id.imgScannerNotLoggedIn);
toggleScannerVisibility(true);
itemAddedText = (TextView) view.findViewById(R.id.item_added_text);
weeklyAdImg = (ImageView) view.findViewById(R.id.weeklyad_img);
defaultWelcomeMsg = (ImageView) view.findViewById(R.id.landing_page_default_img);
setWeeklyAdThumbNail();
if(imgUrl!=null)
Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
else
Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);
//setWeeklyAdOnClickListener();
setWeeklyAdClickListener();
couponsGrid = view.findViewById(R.id.coupons_grid);
couponsPlaceholderImg = (ImageView) view.findViewById(R.id.feat_coupons);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
itemAddedText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
}
imgScanner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PermissionHandler.openCamera(getActivity());
}
});
mShoppingListAdd = (RelativeLayout) view.findViewById(R.id.shoppinglis_shortcut);
mShoppingListAdd.setVisibility(View.GONE);
mAdapter = new LoggedOutWidgetAdapter(getFragmentManager());
mPager = (ViewPager) view.findViewById(R.id.vpHomePageWidget);
mPager.setAdapter(mAdapter);
LinePageIndicator mLoggedOutWidgetIndicator = (LinePageIndicator)view.findViewById(R.id.homewidgetLoggedOutIndicator);
mLoggedOutWidgetIndicator.setViewPager(mPager);
}
// MSM - 214
private void setWeeklyAdThumbNail() {
try {
if (LocalDb.getStoreId() != LocalDb.DEFAULT_VAL) {
if (weeklyAdBundle != null && !weeklyAdBundle.isEmpty()) {
//MSM - 155
if (!Utils.isStringNull(weeklyAdBundle.getString("WeeklyAdThumbnail"))) {
Log.e("BANNER ID SET: ", weeklyAdBundle.getString("WeeklyAdThumbnail"));
imgUrl = weeklyAdBundle.getString("WeeklyAdThumbnail");
}
else
imgUrl = weeklyAdBundle.getString("0FirstThumbnail");
}
}
if (urls == null || !urls.contains(imgUrl)) {
Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
}
else
Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void sendRequest() {
if (CheckNetworkConnection.isConnectionAvailable(activity)) {
jsonParser = new CarouselJSONParser(this);
jsonParser.execute();
} else {
setDefaultOfflineImage();
weeklyAdImg.setImageResource(R.drawable.img_ad_default);
// TODO Set OFFLINE message here
}
}
#Override
public void setCarouselData(ArrayList<CarouselImageData> imageDatas) {
Log.v(TAG, "Set Carousel Data hit");
if (imageDatas != null) {
this.advertisements = imageDatas;
runnable(advertisements.size());
handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
viewPager
.setAdapter(new ImageSliderAdapter(activity, imageDatas, this, weeklyAdBundle));
indicator.setViewPager(viewPager);
if (isFirstTimeLaunched) {
fadeInWelcomMsg();
Log.v(TAG, "first time launched, welcome message initaited");
} else {
viewPager.setVisibility(View.VISIBLE);
indicator.setVisibility(View.VISIBLE);
Log.v(TAG, "Returning user, viewpager set visible");
}
} else {
setDefaultOfflineImage();
}
}
#Override
public void onResume() {
if (LocalDb.isLoggedIn()) {
Fragment fragment = new LandingPageFragment();
launchNavigationItemFragment(fragment);
}
getActivity().startService(new Intent(getActivity().getApplicationContext(),
WeeklyAdService.class));
if (viewPager == null) {
viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
}
mAdapter = new LoggedOutWidgetAdapter(getChildFragmentManager());
super.onResume();
if (newItemIsAdded) {
onShoppingListResult();
}
// addShoppingListItemWidget.clearFocus();
}
#Override
void runnable(final int size) {
handler = new Handler();
animateViewPager = new Runnable() {
#Override
public void run() {
if (!pageIsSliding) {
if (viewPager.getCurrentItem() == size - 1) {
viewPager.setCurrentItem(0);
} else {
viewPager.setCurrentItem(
viewPager.getCurrentItem() + 1, true);
}
handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
}
}
};
}
#Override
void toggleStoreTabIndicator(int tab) {
if (storeTabIsClosed) {
storeTabIsClosed = false;
imgArch.setBackgroundResource(R.drawable.img_single_arch_my_store);
} else {
storeTabIsClosed = true;
imgArch.setBackgroundResource(R.drawable.img_arch);
}
}
#Override
protected void setFontsOnTextViews(View view) {
}
#Override
protected void setTabClickListeners() {
}
#Override
public void setViewPagerMotionListeners(ViewPager vPager) {
}
public class LoggedOutWidgetAdapter extends FragmentPagerAdapter {
public LoggedOutWidgetAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ProductLocatorHomeWidgetFragment.init(position);
case 1:
return ProductScanHomeWidgetFragment.init(position);
case 2:
return MyShoppingListHomeWidgetFragment.init(position);
default:
return null;
}
}
#Override
public int getCount() {
return ITEMS;
}
}
}
The three fragments that are tied to the viewpager
ProductLocatorHomeWidgetFragment
public class ProductLocatorHomeWidgetFragment extends Fragment {
int fragVal;
int storeId;
String storeName, storeLat, storeLong, retail_store_id;
TextView mProductLocatorClickZone;
StoreList sList;
public static ProductLocatorHomeWidgetFragment init(int val) {
ProductLocatorHomeWidgetFragment productLocatorFragment = new ProductLocatorHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("prodLocator", val);
productLocatorFragment.setArguments(args);
return productLocatorFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fragVal = getArguments() != null ? getArguments().getInt("prodLocator") : 1;
sList = new StoreList();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.product_locator_search_widget, container, false);
mProductLocatorClickZone = (TextView) layoutView.findViewById(R.id.editSearchItemNotLoggedIn);
mProductLocatorClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sList = LandingPageFragment.storeList;
if(sList.getId() != null){
storeId = Integer.parseInt(sList.getId());
storeLat = sList.getLatitude();
storeLong = sList.getLongitude();
storeName = sList.getName();
Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
FlurryTrackerHelper.onProductLocatorWidget();
mIntent.putExtra("store_id", String.valueOf(storeId));
mIntent.putExtra("store_lat", storeLat);
mIntent.putExtra("store_lng", storeLong);
mIntent.putExtra("retail_id", retail_store_id);
startActivity(mIntent);
}
else if (sList.getId() == null) {
if (LocalDb.getStoreId() > 0) {
storeId = LocalDb.getStoreId();
storeLat = LocalDb.getStoreLat();
storeLong = LocalDb.getStoreLng();
storeName = LocalDb.getMyStoreName();
Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
FlurryTrackerHelper.onProductLocatorWidget();
mIntent.putExtra("store_id", String.valueOf(storeId));
mIntent.putExtra("store_lat", storeLat);
mIntent.putExtra("store_lng", storeLong);
mIntent.putExtra("retail_id", retail_store_id);
startActivity(mIntent);
}
}
else {
StoreLocatorDetailsSearchFragment storeLocatorDetailsSearchFragment = new StoreLocatorDetailsSearchFragment();
Bundle b1 = new Bundle();
b1.putInt("currentFragment", 10);
storeLocatorDetailsSearchFragment.setArguments(b1);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, storeLocatorDetailsSearchFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
});
return layoutView;
}
}
MyShoppingListHomeWidgetFragment
public class MyShoppingListHomeWidgetFragment extends Fragment {
int fragVal;
EditText mShoppingListClickZone;
ImageView mShoppinglistScanClickZone;
public static MyShoppingListHomeWidgetFragment init(int val) {
MyShoppingListHomeWidgetFragment myShoppingListFragment = new MyShoppingListHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("myShoppingList", val);
myShoppingListFragment.setArguments(args);
return myShoppingListFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fragVal = getArguments() != null ? getArguments().getInt("myShoppingList") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.shopping_list_widget, container, false);
mShoppingListClickZone = (EditText) layoutView.findViewById(R.id.editAddItemNotLoggedIn);
mShoppingListClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShoppingListItemsFragment shoppingListItemsFragment = new ShoppingListItemsFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, shoppingListItemsFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
mShoppinglistScanClickZone = (ImageView) layoutView.findViewById(R.id.imgScannerNotLoggedIn);
mShoppinglistScanClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PermissionHandler.openCamera(getActivity());
}
});
return layoutView;
}
}
ProductScanHomeWidgetFragment
public class ProductScanHomeWidgetFragment extends Fragment {
int fragVal;
LinearLayout mCouponSearchClickZone, mRefillPrescriptionClickZone;
View mDivider;
public static ProductScanHomeWidgetFragment init(int val) {
ProductScanHomeWidgetFragment productScanFragment = new ProductScanHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("prodScan", val);
productScanFragment.setArguments(args);
return productScanFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragVal = getArguments() != null ? getArguments().getInt("prodScan") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.product_scan_widget, container, false);
mRefillPrescriptionClickZone = (LinearLayout) layoutView.findViewById(R.id.refillPrescriptionClickZone);
mCouponSearchClickZone = (LinearLayout) layoutView.findViewById(R.id.couponSearchClickZone);
mCouponSearchClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ECouponsViewFragment eCouponsViewFragment = new ECouponsViewFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, eCouponsViewFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
if (LocalDb.getBannerSupportRefillPrescriptions().equalsIgnoreCase(
UtilConstants.KEY_WORD_FALSE)) {
mDivider = layoutView.findViewById(R.id.divider);
mDivider.setVisibility(View.GONE);
mRefillPrescriptionClickZone.setVisibility(View.GONE);
} else {
mRefillPrescriptionClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPharmacyFragment addPharmacyFragment = new AddPharmacyFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, addPharmacyFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
return layoutView;
}
}
I was able to solve this using a FragmentStatePagerAdapter and not the FragmentPagerAdapter.
So I removed the old FragmentPagerAdapter in LadingPageLoggedOut and replaced it with
inal String [] fragmentClasses = {"com.supervalu.mobile.android.HomeScreenWidget.ProductLocatorHomeWidgetFragment",
"com.supervalu.mobile.android.HomeScreenWidget.ProductScanHomeWidgetFragment",
"com.supervalu.mobile.android.HomeScreenWidget.MyShoppingListHomeWidgetFragment"};
mPager = (ViewPager) view.findViewById(R.id.vpHomePageWidget);
mPager.setAdapter(new FragmentStatePagerAdapter(getFragmentManager()) {
#Override
public Fragment getItem(int position) {
Fragment fragmentAtPosition = null;
// Check to make sure that your array is not null, size is greater than 0 ,
// current position is greater than equal to 0, and position is less than length
if((fragmentClasses != null) && (fragmentClasses.length > 0)&&(position >= 0)&& (position < fragmentClasses.length))
{
// Instantiate the Fragment at the current position of the Adapter
fragmentAtPosition = Fragment.instantiate(getContext(), fragmentClasses[position]);
fragmentAtPosition.setRetainInstance(true);
}
return fragmentAtPosition;
}
#Override
public int getCount() {
return fragmentClasses.length;
}
});

Fragment with ViewPager issue

I want to create soemthing like this:
The ViewPager is attached to an adapter which has 2 fragments. One to list the upcoming orders and the other to list the past orders.
So the image shown above has a main fragment which hosts the ViewPager, and the adapter creates 2 fragments as children of the main fragment.
For sake of simplicity I'll call the main fragment as "Parent fragment" and the two fragments supplied by the adapter as "children fragments".
Once the parent fragment is created or resumed it has to fetch a list of data from the server and pass it to the two children fragment(The children fragments will process the list of data and display the necessary data). Both the children fragments have a listView, and each listView row item is clickable.
Now, the data fetched by the parent fragment has to be passed to the children fragments before the ViewPager is attached to the adapter. So I do not attach the adapter to the ViewPager in the onCreate method of the parent fragment, but rather once the list of data is fetched, I attach the adapter to the ViewPager in the onPostExecute method of the async task after the data is fetched.
This works fine the first time, but once I click on a listView row item of the child fragment and then press the back button, the getItem() method of the adapter is not called, but the onResume methods of the children fragments are called even before the data is fetched from the server.
So I guess the android framework remembers that the children fragment have already been created, and does not recreate them again.
How do I ensure that the children fragments are created/called only after the data is fetched from the server in the parent fragment?
I am adding some code for clarity.
BookingHistory.java(Parent Fragment)
public class BookingHistory extends android.support.v4.app.Fragment {
ViewPager mPager;
SlidingTabLayout mTabs;
Toolbar toolBar;
View view;
private ProgressDialog progress;
private OrderTask mOrderTask = null;
UserFunctions userFunctions = null;
OrderFunctions orderFunctions = null;
private BookingHistoryListener mListener;
private List<Order> mOrderList;
PlacedOrders upcomingOrders;
PlacedOrders pastOrders;
public BookingHistory() {
// Required empty public constructor
}
#Override
public void onResume() {
super.onResume();
mOrderList = null;
mPager = null;
mTabs = null;
upcomingOrders = null;
pastOrders = null;
progress = new ProgressDialog(getActivity());
fetchOrders();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_booking_history, container, false);
toolBar = (Toolbar) view.findViewById(R.id.toolbar_s);
if (toolBar != null) {
TextView tv = (TextView) view.findViewById(R.id.toolbar_title);
toolBar.setTitle("");
tv.setText("History");
}
return view;
}
class MyPagerAdapter extends FragmentPagerAdapter {
String tabs[] = {"Upcoming", "Past"};
public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
if (position == 0) {
upcomingOrders = PlacedOrders.newInstance(Constants.DATE_TODAY_FUTURE);
upcomingOrders.getOrderList(mOrderList);
return upcomingOrders;
} else {
pastOrders = PlacedOrders.newInstance(Constants.DATE_PAST);
pastOrders.getOrderList(mOrderList);
return pastOrders;
}
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 2;
}
}
public void fetchOrders() {
if (mOrderTask != null) {
return;
}
progress.show();
mOrderTask = new OrderTask(getActivity());
mOrderTask.execute((Void) null);
}
public class OrderTask extends AsyncTask<Void, Void, Boolean> {
private final Activity mActivity;
OrderTask(Activity activity) {
mActivity = activity;
}
#Override
protected Boolean doInBackground(Void... params) {
userFunctions = new UserFunctions();
orderFunctions = new OrderFunctions();
return orderFunctions.getList(userFunctions.getToken(mActivity));
}
#Override
protected void onPostExecute(final Boolean success) {
mOrderTask = null;
progress.dismiss();
if (success) {
mOrderList = UserProfile.getOrders();
//attaching the view pager to adapter here!
mPager = (ViewPager) view.findViewById(R.id.pager);
mTabs = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mTabs.setDistributeEvenly(true);
mTabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.white);
}
});
mPager.setAdapter(new MyPagerAdapter(getChildFragmentManager()));
mTabs.setViewPager(mPager);
} else {
//Error handling stuff
}
}
}
}
PlacedOrders.java(Children Fragments)
public class PlacedOrders extends android.support.v4.app.Fragment {
private static String flag;
private int dateFlag;
private PlacedOrdersListener mListener;
UserFunctions userFunctions = null;
OrderFunctions orderFunctions = null;
private PlacedOrdersAdapter ordersAdapter;
private ProgressDialog progress;
private List<Order> mOrderList;
private List<Order> mPendingOrderList;
private List<Order> mCompletedOrderList;
public static PlacedOrders newInstance(int date) {
PlacedOrders fragment = new PlacedOrders();
Bundle args = new Bundle();
args.putInt(flag, date);
fragment.setArguments(args);
return fragment;
}
public void getOrderList(List<Order> orderList) {
this.mOrderList = orderList;
}
public PlacedOrders() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
dateFlag = getArguments().getInt(flag);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mPendingOrderList = new ArrayList<Order>();
mCompletedOrderList = new ArrayList<Order>();
return inflater.inflate(R.layout.fragment_placed_orders, container, false);
}
#Override
public void onResume() {
super.onResume();
displayOrders();
}
private void displayOrders() {
if (isVisible() && (mOrderList != null)) {
mPendingOrderList.clear();
mCompletedOrderList.clear();
ListView listViewOrder = (ListView) getView().findViewById(R.id.orderList);
if(dateFlag == Constants.DATE_TODAY_FUTURE) {
for(int i = 0; i < mOrderList.size(); i++) {
String status = mOrderList.get(i).status;
if(status.equals("PENDING") || status.equals("PROCESSING")) {
mPendingOrderList.add(mOrderList.get(i));
ordersAdapter = new PlacedOrdersAdapter(mPendingOrderList, getActivity().getLayoutInflater());
listViewOrder.setAdapter(ordersAdapter);
}
}
}
else if(dateFlag == Constants.DATE_PAST) {
for(int i = 0; i < mOrderList.size(); i++) {
String status = mOrderList.get(i).status;
if(status.equals("COMPLETE")) {
mCompletedOrderList.add(mOrderList.get(i));
ordersAdapter = new PlacedOrdersAdapter(mCompletedOrderList, getActivity().getLayoutInflater());
listViewOrder.setAdapter(ordersAdapter);
}
}
}
listViewOrder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//Display a new fragment on clicking
});
}
}
}
I had same issue and this was my solution :
In container fragment (fragment that contains tabs) in onViewCreated() method I created startFetch() method:
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
mViewPager = (ViewPager) v.findViewById(R.id.home_tab_pager);
mTabsHost= (TabLayout) getActivity().findViewById(R.id.appTabs);
startFetch();
}
Then in startFetch method i use Volley request and in onResponse method i update data and then add tabs :
public void startFetch(){
//Create volley request
String url = BuildConfig.API_GET_CATEGORIES;
final RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// we got the response, now our job is to handle it
try {
updateCategoryData(response);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//something happened, treat the error.
Log.e("ErrorFETCH", error.networkResponse.toString());
}
});
queue.add(request);
}
My udpateCategory() method :
public void updateCategoryData(final String stream) throws RemoteException, OperationApplicationException {
//Update the data to SQLITE
setupTabs();
}
My setupTabs() method :
public void setUpTabs(){
ArrayList<Category> categories = new ArrayList<>();
Cursor data = getActivity().getContentResolver().query(
Category.Entry.CONTENT_URI, // URI
Category.PROJECTION, // Projection
Category.Entry.COLUMN_NAME_PARENT_ID + " = ?", // Selection
new String[]{"0"}, // Selection args
null);
if (data != null) {
while(data.moveToNext()){
categories.add(new Category(data));
}
}
TabsPagerAdapter mAdapter = new TabsPagerAdapter(getActivity().getSupportFragmentManager(), this.getActivity(), categories);
mViewPager.setAdapter(mAdapter);
mTabsHost.setupWithViewPager(mViewPager);
}

Categories

Resources