Why does onBackPressed kill my app? - android

When I started working on this, I was using the mapbox android api instead of the google maps api. I don't think that that has much bearing on what is going wrong but, I did have the backstack working fine at some point.
As it is now, I can get all the way up to my video player fragment. (3rd on the backstack). If I hit the back button from there, the recycler view will show and then the app will disappear from the screen. If I go to the recycler view from the map, and hit backpress - the map will show and then immediately disappear from the screen.
Please let me know if there's anything else I can post to clear things up.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, FragmentManager.OnBackStackChangedListener {
FragmentManager fragmentManager = getFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
fragmentManager.addOnBackStackChangedListener(this);
FragmentTransaction ft = fragmentManager.beginTransaction();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
ft.addToBackStack("Main Fragment");
ft.commit();
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng sydney = new LatLng(-33.867, 151.206);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(sydney));
}
#Override
public void onBackPressed() {
if (fragmentManager.getBackStackEntryCount() != 0) {
fragmentManager.popBackStackImmediate();
}else {
super.onBackPressed();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
String title = item.getTitle().toString();
if (title.equals("Topic One")) {
FragmentTransaction ft = fragmentManager.beginTransaction();
RecyclerViewFragment rvs = new RecyclerViewFragment().newInstance(0);
ft.setCustomAnimations(R.animator.top_to_bottom_fragment, android.R.animator.fade_out);
ft.replace(R.id.map, rvs, "subject_cards");
ft.addToBackStack("Topic One");
ft.commit();
} else if (title.equals("Topic Two")) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
RecyclerViewFragment rvs = new RecyclerViewFragment().newInstance(1);
ft.replace(R.id.map, rvs, "subject_cards");
ft.addToBackStack("Topic Two");
ft.commit();
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onBackStackChanged() {
FragmentManager fm = getFragmentManager();
int bsCOunt = fm.getBackStackEntryCount();
for(int i = 0; i < bsCOunt; i++){
System.out.println( "Fragment name: " + fm.getBackStackEntryAt(i).getName() +"\n");
System.out.println("");
}
}
}
RecyclerViewFragment:
public class RecyclerViewFragment extends Fragment {
private List<Subject> subjects;
static RecyclerView rv;
static int cardViewPosition;
View rootView;
private static final String TAG = "RECYCLER_VIEW_FRAGMENT";
public static RecyclerViewFragment newInstance(int some_Int) {
RecyclerViewFragment frag = new RecyclerViewFragment();
Bundle args = new Bundle();
args.putInt("card_int", some_Int);
frag.setArguments(args);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cardViewPosition = getArguments().getInt("card_int", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.recyclerview_activity, container, false);
rootView.setTag(TAG);
rv = (RecyclerView) rootView.findViewById(R.id.rv);
final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
rv.scrollToPosition(cardViewPosition);
initializeData();
initializeAdapter();
return rootView;
}
private void initializeData() {
subjects = new ArrayList<>();
JSONObject obj;
JSONArray jArray = null;
try {
obj = new JSONObject(loadJsonFromAsset());
jArray = obj.getJSONArray("people");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = null;
try {
json_data = jArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
subjects.add(new Subject(json_data.getInt("id"), json_data.getString("name"), null,
null, getResources().getIdentifier(json_data.getString("photoId"), "drawable",
this.getActivity().getPackageName()), json_data.getString("subjectText"),json_data.getString("expandedSubjectText")));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void initializeAdapter() {
RVAdapter adapter = new RVAdapter(subjects,rootView.getContext());
adapter.setOnClickListener(new RVAdapter.MyListener() {
#Override
public void onClick(View v, int i, CharSequence subjectName) {
if (v.equals(v.findViewById(R.id.card_button_left))) {
rv.scrollToPosition(i);
FragmentTransaction ft = getFragmentManager().beginTransaction();
VideoPlayerFragment vFrag = new VideoPlayerFragment().newInstance(subjectName);
ft.setCustomAnimations(R.animator.top_to_bottom_fragment, android.R.animator.fade_out);
ft.replace(android.R.id.content, vFrag);
ft.addToBackStack(null);
ft.commit();
FragmentManager fragmentManager = getFragmentManager();
}else if(v.equals(v.findViewById(R.id.card_button_right))){
rv.scrollToPosition(i);
}
}
});
rv.setAdapter(adapter);
}
public String loadJsonFromAsset() {
String json = null;
InputStream is = getResources().openRawResource(R.raw.people);
try {
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
}
Video player frag:
public class VideoPlayerFragment extends Fragment {
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
WebView videoDisplay = null;
static CharSequence subjectName;
static String htmlPageForSubject;
CharSequence title;
CharSequence openingText;
CharSequence mainText;
CharSequence[] text;
public static VideoPlayerFragment newInstance(CharSequence subjectName) {
VideoPlayerFragment vFrag = new VideoPlayerFragment();
Bundle arg = new Bundle();
arg.putCharSequence("subject_name", subjectName);
vFrag.setArguments(arg);
return vFrag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.subjectName = getArguments().getCharSequence("subject_name");
htmlPageForSubject = subjectName.toString().replace(' ', '_');
PeopleReader peopleReader = new PeopleReader(subjectName);
text = peopleReader.fetchText();
title = text[0];
openingText = text[1];
mainText = text[2];
}
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = layoutInflater.inflate(R.layout.webview_layout, container, false);
videoDisplay = (WebView) rootView.findViewById(R.id.webView);
TextView firstTextBox = (TextView) rootView.findViewById(R.id.titleText);
TextView secondTextBox = (TextView) rootView.findViewById(R.id.openingText);
TextView thirdTextBox = (TextView) rootView.findViewById(R.id.mainText);
firstTextBox.setText(title);
secondTextBox.setText(openingText);
thirdTextBox.setText(mainText);
videoDisplay.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings webSettings = videoDisplay.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
videoDisplay.loadUrl("file:///android_asset/www/" + htmlPageForSubject + ".html");
videoDisplay.setWebChromeClient(new MyWebChromeClient());
return rootView;
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
class MyWebChromeClient extends WebChromeClient {
private int mOriginalSystemUiVisibility;
private int mOriginalOrientation;
#Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
if (mCustomView != null) {
onHideCustomView();
return;
}
mCustomView = view;
mOriginalSystemUiVisibility = getActivity().getWindow().getDecorView().getSystemUiVisibility();
mOriginalOrientation = getActivity().getRequestedOrientation();
mCustomViewCallback = callback;
FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
decor.addView(mCustomView, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
getActivity().getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_IMMERSIVE);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
#Override
public void onHideCustomView() {
// 1. Remove the custom view
FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
decor.removeView(mCustomView);
mCustomView = null;
getActivity().getWindow().getDecorView()
.setSystemUiVisibility(mOriginalSystemUiVisibility);
getActivity().setRequestedOrientation(mOriginalOrientation);
mCustomViewCallback.onCustomViewHidden();
mCustomViewCallback = null;
}
}
class PeopleReader {
CharSequence topicName;
CharSequence[] textArray = new String[3];
public PeopleReader(CharSequence topicName){
this.topicName = topicName;
}
public CharSequence[] fetchText() {
JSONObject obj;
JSONArray jArray = null;
try {
obj = new JSONObject(loadJsonFromAsset());
jArray = obj.getJSONArray("people");
} catch (JSONException e1) {
e1.printStackTrace();
}
for(int i = 0;i<jArray.length();i++){
JSONObject json_data;
try {
json_data = jArray.getJSONObject(i);
if(json_data.getString("name").equals(topicName.toString())){
textArray[0] = json_data.getString("name");
textArray[1] = json_data.getString("subjectText");
textArray[2] = json_data.getString("expandedSubjectText");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return textArray;
}
public String loadJsonFromAsset() {
String json = null;
InputStream is = getResources().openRawResource(R.raw.people);
try {
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
}
}

Anytime your drawer isn't open, you're using the default super.onBackPressed() behavior. Try this.
#Override
public void onBackPressed() {
if (fragmentManager.getBackStackEntryCount() != 0) {
fragmentManager.popBackStackImmediate();
return;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
return;
}
// Otherwise defer to system default behavior.
super.onBackPressed();
}

The super.onBackPressed(); is going to exit the app if there is nothing to go back to. You can of course consume this behavior by removing that line, but I highly recommend against it.
What you might consider is popping up an AlertDialog to confirm whether the user wants to exit. Alternatively you can print a Toast saying "hitting back one more time will exit the app" and handling that behavior.

Related

Manual Back Press From FragmentA to Homefragment Did Not Work Android Studio,

I Have one Fragment called LatestFragment Code:
public class LatestFragment extends Fragment {
ArrayList<ItemLatest> mListItem;
public RecyclerView recyclerView;
LatestAdapter adapter;
private ProgressBar progressBar;
private LinearLayout lyt_not_found;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_category, container, false);
mListItem = new ArrayList<>();
lyt_not_found = rootView.findViewById(R.id.lyt_not_found);
progressBar = rootView.findViewById(R.id.progressBar);
recyclerView = rootView.findViewById(R.id.vertical_courses_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
recyclerView.setFocusable(false);
recyclerView.setNestedScrollingEnabled(false);
JsonObject jsObj = (JsonObject) new Gson().toJsonTree(new API());
jsObj.addProperty("method_name", "get_latest");
if (JsonUtils.isNetworkAvailable(requireActivity())) {
new getLatest(API.toBase64(jsObj.toString())).execute(Constant.API_URL);
}
setHasOptionsMenu(true);
return rootView;
}
#SuppressLint("StaticFieldLeak")
private class getLatest extends AsyncTask<String, Void, String> {
String base64;
private getLatest(String base64) {
this.base64 = base64;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgress(true);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0], base64);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
showProgress(false);
if (null == result || result.length() == 0) {
lyt_not_found.setVisibility(View.VISIBLE);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.ARRAY_NAME);
JSONObject objJson;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
if(objJson.has("status")){
lyt_not_found.setVisibility(View.VISIBLE);
}else {
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJson.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeName(objJson.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeType(objJson.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipePlayId(objJson.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
objItem.setRecipeImageSmall(objJson.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipeImageBig(objJson.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeViews(objJson.getString(Constant.LATEST_RECIPE_VIEW));
objItem.setRecipeTime(objJson.getString(Constant.LATEST_RECIPE_TIME));
objItem.setRecipeCategoryName(objJson.getString(Constant.LATEST_RECIPE_CAT_NAME));
objItem.setRecipeTotalRate(objJson.getString(Constant.LATEST_RECIPE_TOTAL_RATE));
objItem.setRecipeAvgRate(objJson.getString(Constant.LATEST_RECIPE_AVR_RATE));
objItem.setRecipeDirection(objJson.getString(Constant.LATEST_RECIPE_DIRE));
objItem.setRecipeIngredient(objJson.getString(Constant.LATEST_RECIPE_INGREDIENT));
mListItem.add(objItem);
}}
} catch (JSONException e) {
e.printStackTrace();
}
displayData();
}
}
}
private void displayData() {
if (getActivity() != null) {
adapter = new LatestAdapter(getActivity(), mListItem);
recyclerView.setAdapter(adapter);
if (adapter.getItemCount() == 0) {
lyt_not_found.setVisibility(View.VISIBLE);
} else {
lyt_not_found.setVisibility(View.GONE);
}
}
}
private void showProgress(boolean show) {
if (show) {
progressBar.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
lyt_not_found.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_main, menu);
final SearchView searchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
final MenuItem searchMenuItem = menu.findItem(R.id.search);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (!hasFocus) {
searchMenuItem.collapseActionView();
searchView.setQuery("", false);
}
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
And HomeFragment Code:
package com.example.fragment;
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mCatView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mCatView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
if (Constant.SAVE_ADS_FULL_ON_OFF.equals("true")) {
Constant.AD_COUNT++;
if (Constant.AD_COUNT == Integer.parseInt(Constant.SAVE_ADS_CLICK)) {
Constant.AD_COUNT = 0;
final InterstitialAd mInterstitial = new InterstitialAd(requireActivity());
mInterstitial.setAdUnitId(Constant.SAVE_ADS_FULL_ID);
AdRequest adRequest;
if (JsonUtils.personalization_ad) {
adRequest = new AdRequest.Builder()
.build();
} else {
Bundle extras = new Bundle();
extras.putString("npa", "1");
adRequest = new AdRequest.Builder()
.addNetworkExtrasBundle(AdMobAdapter.class, extras)
.build();
}
mInterstitial.loadAd(adRequest);
mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// TODO Auto-generated method stub
super.onAdLoaded();
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
}
public void onAdClosed() {
String categoryName = mCatList.get(position).getCategoryName();
Bundle bundle = new Bundle();
bundle.putString("name", categoryName);
bundle.putString("Id", mCatList.get(position).getCategoryId());
FragmentManager fm = getFragmentManager();
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
subCategoryFragment.setArguments(bundle);
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.hide(HomeFragment.this);
ft.add(R.id.fragment1, subCategoryFragment, categoryName);
ft.addToBackStack(categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
#Override
public void onAdFailedToLoad(int errorCode) {
String categoryName = mCatList.get(position).getCategoryName();
Bundle bundle = new Bundle();
bundle.putString("name", categoryName);
bundle.putString("Id", mCatList.get(position).getCategoryId());
FragmentManager fm = getFragmentManager();
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
subCategoryFragment.setArguments(bundle);
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.hide(HomeFragment.this);
ft.add(R.id.fragment1, subCategoryFragment, categoryName);
ft.addToBackStack(categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
} else {
String categoryName = mCatList.get(position).getCategoryName();
Bundle bundle = new Bundle();
bundle.putString("name", categoryName);
bundle.putString("Id", mCatList.get(position).getCategoryId());
FragmentManager fm = getFragmentManager();
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
subCategoryFragment.setArguments(bundle);
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.hide(HomeFragment.this);
ft.add(R.id.fragment1, subCategoryFragment, categoryName);
ft.addToBackStack(categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
btnCat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((ActivityMain) requireActivity()).highLightNavigation(2);
String categoryName = getString(R.string.home_category);
FragmentManager fm = getFragmentManager();
CategoryFragment f1 = new CategoryFragment();
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment1, f1, categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
btnLatest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((ActivityMain) requireActivity()).highLightNavigation(1);
String categoryName = getString(R.string.home_latest);
FragmentManager fm = getFragmentManager();
LatestFragment f1 = new LatestFragment();
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment1, f1, categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
btnMost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((ActivityMain) requireActivity()).highLightNavigation(3);
String categoryName = getString(R.string.menu_most);
FragmentManager fm = getFragmentManager();
MostViewFragment f1 = new MostViewFragment();
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment1, f1, categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
edt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//do something
String st_search = edt_search.getText().toString();
Intent intent = new Intent(getActivity(), SearchActivity.class);
intent.putExtra("search", st_search);
startActivity(intent);
edt_search.getText().clear();
}
return false;
}
});
setHasOptionsMenu(true);
return rootView;
}
#SuppressLint("StaticFieldLeak")
private class Home extends AsyncTask<String, Void, String> {
String base64;
private Home(String base64) {
this.base64 = base64;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
mScrollView.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0], base64);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mProgressBar.setVisibility(View.GONE);
mScrollView.setVisibility(View.VISIBLE);
if (null == result || result.length() == 0) {
showToast(getString(R.string.no_data));
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONObject jsonArray = mainJson.getJSONObject(Constant.ARRAY_NAME);
JSONArray jsonSlider = jsonArray.getJSONArray(Constant.HOME_FEATURED_ARRAY);
JSONObject objJsonSlider;
for (int i = 0; i < jsonSlider.length(); i++) {
objJsonSlider = jsonSlider.getJSONObject(i);
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJsonSlider.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeType(objJsonSlider.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipeCategoryName(objJsonSlider.getString(Constant.LATEST_RECIPE_CAT_NAME));
objItem.setRecipeName(objJsonSlider.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeImageBig(objJsonSlider.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeImageSmall(objJsonSlider.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipePlayId(objJsonSlider.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
mSliderList.add(objItem);
}
JSONArray jsonLatest = jsonArray.getJSONArray(Constant.HOME_LATEST_CAT);
JSONObject objJsonCat;
for (int k = 0; k < jsonLatest.length(); k++) {
objJsonCat = jsonLatest.getJSONObject(k);
ItemCategory objItem = new ItemCategory();
objItem.setCategoryId(objJsonCat.getString(Constant.CATEGORY_ID));
objItem.setCategoryName(objJsonCat.getString(Constant.CATEGORY_NAME));
objItem.setCategoryImageBig(objJsonCat.getString(Constant.CATEGORY_IMAGE_BIG));
objItem.setCategoryImageSmall(objJsonCat.getString(Constant.CATEGORY_IMAGE_SMALL));
mCatList.add(objItem);
}
JSONArray jsonPopular = jsonArray.getJSONArray(Constant.HOME_LATEST_ARRAY);
JSONObject objJson;
for (int l = 0; l < jsonPopular.length(); l++) {
objJson = jsonPopular.getJSONObject(l);
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJson.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeName(objJson.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeType(objJson.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipePlayId(objJson.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
objItem.setRecipeImageSmall(objJson.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipeImageBig(objJson.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeViews(objJson.getString(Constant.LATEST_RECIPE_VIEW));
objItem.setRecipeTime(objJson.getString(Constant.LATEST_RECIPE_TIME));
objItem.setRecipeAvgRate(objJson.getString(Constant.LATEST_RECIPE_AVR_RATE));
objItem.setRecipeTotalRate(objJson.getString(Constant.LATEST_RECIPE_TOTAL_RATE));
objItem.setRecipeCategoryName(objJson.getString(Constant.LATEST_RECIPE_CAT_NAME));
mLatestList.add(objItem);
}
JSONArray jsonPopularMost = jsonArray.getJSONArray(Constant.HOME_MOST_ARRAY);
JSONObject objJsonMost;
for (int l = 0; l < jsonPopularMost.length(); l++) {
objJsonMost = jsonPopularMost.getJSONObject(l);
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJsonMost.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeName(objJsonMost.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeType(objJsonMost.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipePlayId(objJsonMost.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
objItem.setRecipeImageSmall(objJsonMost.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipeImageBig(objJsonMost.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeViews(objJsonMost.getString(Constant.LATEST_RECIPE_VIEW));
objItem.setRecipeTime(objJsonMost.getString(Constant.LATEST_RECIPE_TIME));
objItem.setRecipeAvgRate(objJsonMost.getString(Constant.LATEST_RECIPE_AVR_RATE));
objItem.setRecipeTotalRate(objJsonMost.getString(Constant.LATEST_RECIPE_TOTAL_RATE));
objItem.setRecipeCategoryName(objJsonMost.getString(Constant.LATEST_RECIPE_CAT_NAME));
mMostList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setResult();
}
}
}
private void setResult() {
if (getActivity() != null) {
mLatestAdapter = new HomeAdapter(getActivity(), mLatestList);
mLatestView.setAdapter(mLatestAdapter);
homeMostAdapter = new HomeMostAdapter(getActivity(), mMostList);
mMostView.setAdapter(homeMostAdapter);
homeCategoryAdapter = new HomeCategoryAdapter(getActivity(), mCatList);
mCatView.setAdapter(homeCategoryAdapter);
if (!mSliderList.isEmpty()) {
mViewPager.setAdapter(mAdapter);
if (mSliderList.size() >= 3) {
mViewPager.setCurrentItem(1);
}
}
}
}
private class CustomViewPagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
private CustomViewPagerAdapter() {
// TODO Auto-generated constructor stub
inflater = requireActivity().getLayoutInflater();
}
#Override
public int getCount() {
return mSliderList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View imageLayout = inflater.inflate(R.layout.row_slider_item, container, false);
assert imageLayout != null;
ImageView image = imageLayout.findViewById(R.id.image);
TextView text = imageLayout.findViewById(R.id.text_title);
TextView text_cat = imageLayout.findViewById(R.id.text_cat_title);
LinearLayout lytParent = imageLayout.findViewById(R.id.rootLayout);
text.setText(mSliderList.get(position).getRecipeName());
text_cat.setText(mSliderList.get(position).getRecipeCategoryName());
Picasso.get().load(mSliderList.get(position).getRecipeImageBig()).into(image);
imageLayout.setTag(EnchantedViewPager.ENCHANTED_VIEWPAGER_POSITION + position);
lytParent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopUpAds.ShowInterstitialAds(getActivity(), mSliderList.get(position).getRecipeId());
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
(container).removeView((View) object);
}
}
public void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_profile, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
// finish();
return true;
case R.id.menu_profile:
if (MyApp.getIsLogin()) {
Intent intent_edit = new Intent(getActivity(), ProfileEditActivity.class);
startActivity(intent_edit);
} else {
final PrettyDialog dialog = new PrettyDialog(requireActivity());
dialog.setTitle(getString(R.string.dialog_warning))
.setTitleColor(R.color.dialog_text)
.setMessage(getString(R.string.login_require))
.setMessageColor(R.color.dialog_text)
.setAnimationEnabled(false)
.setIcon(R.drawable.pdlg_icon_close, R.color.dialog_color, new PrettyDialogCallback() {
#Override
public void onClick() {
dialog.dismiss();
}
})
.addButton(getString(R.string.dialog_ok), R.color.dialog_white_text, R.color.dialog_color, new PrettyDialogCallback() {
#Override
public void onClick() {
dialog.dismiss();
Intent intent_login = new Intent(getActivity(), SignInActivity.class);
intent_login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent_login);
}
})
.addButton(getString(R.string.dialog_no), R.color.dialog_white_text, R.color.dialog_color, new PrettyDialogCallback() {
#Override
public void onClick() {
dialog.dismiss();
}
});
dialog.setCancelable(false);
dialog.show();
}
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
}
When It load LatestFragment and I press back in android device the app Exit,
how to backpress from LatestFragment to HomeFragment
Thanks
Is there a way in which we can implement onBackPressed() in Android Fragment similar to the way in which we implement in Android Activity?
As the Fragment lifecycle do not have onBackPressed(). Is there any other alternative method to over ride onBackPressed() in Android 3.5 fragments?
PLease change in HomeFragment
ft.replace(R.id.fragment1, f1, categoryName); to
ft.add(R.id.fragment1, f1, categoryName);
It adds LatestFragment in stack so when you will press back button from LatestFragment it shows HomeFragment because HomeFragment is still in stack

How to implements onclick listview in fragment?

I'm trying to give onClick in my listview . I'm using menu drawer here is my mainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
displaySelectedScreen(R.id.nav_item);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
FragmentManager fm = getSupportFragmentManager();
Fragment Fragment = null;
switch (itemId) {
case R.id.nav_item:
Fragment = new Item();
break;
case R.id.nav_do:
Fragment = new Deliveryorder();
break;
}
if (Fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, Fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
then here is one of my fragment
public class Item extends Fragment implements View.OnClickListener {
ListView listView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item, container, false);
listView = (ListView) rootView.findViewById(R.id.listView1);
return rootView;
}
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "TEST", Toast.LENGTH_LONG).show();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Menu Item");
getJSON("http://192.168.3.223:84/fppb/andro_login/fppb");
}
private void loadIntoListView(String json) throws JSONException {
List<Itemadapter> items = new ArrayList<Itemadapter>();
JSONArray jsonArray = new JSONArray(json);
String[] ba = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String code = obj.getString("ItemCode");
String name = obj.getString("ItemName");
String photo = obj.getString("PhotoName");
items.add(new Itemadapter(code, name,photo));
}
//Toast.makeText(getActivity(), items.toString(), Toast.LENGTH_LONG).show();
ArrayAdapter<Itemadapter> mArrayAdapter = new ArrayAdapter<Itemadapter>(getActivity(),android.R.layout.simple_expandable_list_item_1,items);
listView.setAdapter(mArrayAdapter);
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
}
when i run my app and open Item.java the data is showing up, but when i click one row there's nothing happen. I already add this
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "TEST", Toast.LENGTH_LONG).show();
}
How can i fix it ? thanks in advance and sorry for my english.
You need to implement a listener :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getActivity(), "TEST", Toast.LENGTH_LONG).show();
}
});
Hello, Please check out the following link, here you get the complete guidance about how to implement listview in fragment and how to impalement click listener on listview items.

ArrayList of custom objects is overwritten whenever I add to it from another fragment

I'm trying to pass an article object from one fragment to another fragment via the activity that they share. So far the object is being passed over, but the whenever more than one item in the listview of the ArticlesFragment is selected to be saved, the CollectionsFragment doesn't append to the ArrayList, and simply overwrites it. Leaving only one article to be shown in that fragment.
ArticlesFragment.java
package fragments;
/* Imports */
public class ArticlesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private final String urlString = "https://newsapi.org/v1/articles?source=reuters&sortBy=top&apiKey=4b240d3be86c4f69856af11e51432cbc";
private final String progressMsg = "Loading in articles...";
private SwipeRefreshLayout swipe;
private List<Article> articleList;
private ListView lvArticles;
private ArticleAdapter adapter;
private ProgressDialog progressDialog;
public ArticlesFragment() {
}
public static ArticlesFragment newInstance() {
ArticlesFragment fragment = new ArticlesFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new JSONTask().execute(urlString);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_articles, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
swipe.setOnRefreshListener(this);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext()).build();
ImageLoader.getInstance().init(config);
return view;
}
#Override
public void onRefresh() {
new JSONTask().execute(urlString);
swipe.setRefreshing(false);
}
public class JSONTask extends AsyncTask<String, String, List<Article>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getContext());
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.setMessage(progressMsg);
progressDialog.show();
}
#Override
protected List<Article> doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parent = new JSONObject(finalJson);
JSONArray parentArray = parent.getJSONArray("articles");
articleList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
Article article = gson.fromJson(finalObject.toString(), Article.class);
articleList.add(article);
}
return articleList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<Article> s) {
super.onPostExecute(s);
progressDialog.dismiss();
adapter = new ArticleAdapter(getContext(), R.layout.row, s);
lvArticles = (ListView) getActivity().findViewById(R.id.lvArticles);
lvArticles.setAdapter(adapter);
lvArticles.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Article item = articleList.get(position);
Intent intent1 = new Intent(getContext(), WebViewActivity.class);
intent1.putExtra("URL", item.getUrl());
getContext().startActivity(intent1);
}
});
lvArticles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Implement article saves.
Article item = articleList.get(position);
createDialog(view, item);
return true;
}
});
}
private void createDialog(View view, final Article item) {
final Dialog d = new Dialog(getContext());
d.setContentView(R.layout.dialog);
d.setTitle("Add article?");
d.setCancelable(true);
Button b = (Button) d.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), MainActivity.class);
intent.putExtra("Article", item);
getContext().startActivity(intent);
Toast.makeText(getContext(), "YES", Toast.LENGTH_SHORT).show();
}
});
d.show();
}
}
}
MainActivity.java
package com.fyp.chowdud.dynamo;
/* Imports */
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, new ArticlesFragment())
.commit();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_home) {
fragment = new ArticlesFragment();
} else {
fragment = new CollectionsFragment();
passData(fragment);
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void passData(Fragment fragment) {
Intent intent = getIntent();
Article aitem = (Article) intent.getSerializableExtra("Article");
Bundle bundle = new Bundle();
bundle.putSerializable("Article", aitem);
fragment.setArguments(bundle);
}
}
CollectionsFragment.java
package fragments;
/* Imports */
public class CollectionsFragment extends Fragment {
private List<Article> articleList;
private ListView lvArticles;
private ArticleAdapter adapter;
Article v = null;
public CollectionsFragment() {
}
public static CollectionsFragment newInstance() {
Bundle args = new Bundle();
CollectionsFragment fragment = new CollectionsFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_collections, container, false);
if (articleList == null) {
new MyTask().execute();
}
return view;
}
private class MyTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
Bundle bundle = getArguments();
v = (Article) bundle.getSerializable("Article");
articleList = new ArrayList<>();
articleList.add(v);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
lvArticles = (ListView) getActivity().findViewById(R.id.lvArticles);
adapter = new ArticleAdapter(getContext(), R.layout.row, articleList);
lvArticles.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}

onback pressed data not showing in fragments

I am using navigation drawer in my app,I have fragments like F1,F2 and so on..and in every fragment I am parsing data and display in listview,everything is works fine if I go through my app like F1>F2>F3 and so on..but the issue is if I go from F3 to F2,the data which I had in my F2 fragments is not showing,and display only blank page,what is the issue?Can any one help?
My F1
public class Categriesdrawers extends Fragment{
private ImageView drwr;
private SlidingDrawer sldrwr;
private ProgressDialog pDialog;
JSONArray categorylist=null;
private ListView listview;
private ArrayList<HashMap<String,String>> aList;
private static String INTEREST_ACCEPT_URL = "http:.ashx?action=category";
private static final String INTEREST_ACCEPT="categorylist";
private static final String INTERESTACCEPT_USER_ID="Id";
private static final String INTEREST_ACCEPT_NAME="categoryname";
private CustomAdapterCatagory adapter;
private TextView noacpt;
private ListView catlist;
#SuppressWarnings("deprecation")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.tests, container, false);
drwr=(ImageView)v.findViewById(R.id.handle);
sldrwr=(SlidingDrawer)v.findViewById(R.id.bottom);
sldrwr.open();
new LoadAlbums().execute();
sldrwr.setOnDrawerOpenListener(new OnDrawerOpenListener() {
#Override
public void onDrawerOpened() {
new LoadAlbums().execute();
}
});
catlist=(ListView)v.findViewById(R.id.substitute_list);
catlist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Organization tf = new Organization();
Bundle bundle = new Bundle();
tf.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.mainContent, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
return v;
}
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Categriesdrawers.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(INTEREST_ACCEPT_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
categorylist = jsonObj.getJSONArray(INTEREST_ACCEPT);
for (int i = 0; i < categorylist.length(); i++) {
JSONObject c = categorylist.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(INTERESTACCEPT_USER_ID, c.getString(INTERESTACCEPT_USER_ID));
map.put(INTEREST_ACCEPT_NAME,c.getString(INTEREST_ACCEPT_NAME));
// adding HashList to ArrayList
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
if(aList == null){
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterCatagory(getActivity(),result);
catlist.setAdapter(adapter);
}else{
aList.addAll(result);
adapter.notifyDataSetChanged();
}
}
}
MainActivity
public class MainActivity extends Activity {
ListView mDrawerList;
RelativeLayout mDrawerPane;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private CharSequence mTitle;
ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();
private CharSequence mDrawerTitle;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar=getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.argb(255, 235, 139, 36)));
mTitle = mDrawerTitle = getTitle();
mNavItems.add(new NavItem("All Post", R.drawable.allpost));
mNavItems.add(new NavItem("Categories", R.drawable.allpost));
mNavItems.add(new NavItem("All Bloggers", R.drawable.allpost));
mNavItems.add(new NavItem("About Us", R.drawable.about));
mNavItems.add(new NavItem("Rate US", R.drawable.rates));
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Populate the Navigtion Drawer with options
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
selectItemFromDrawer(position);
}
});
getActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_view, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(savedInstanceState==null)
{
selectItemFromDrawer(0);
}
}
#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) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void selectItemFromDrawer(int position) {
Fragment fragment=null;
switch (position) {
case 0:
fragment=new AllPost();
break;
case 1:
fragment=new Categriesdrawers();
break;
case 2:
fragment=new AllBloggerList();
break;
/*case 3:
fragment=new Aboutus();
break;
*/
default:
break;
}
if(fragment!=null)
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mNavItems.get(position).mTitle);
mDrawerLayout.closeDrawer(mDrawerPane);
}
/*Fragment fragment = new PreferencesFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mNavItems.get(position).mTitle);
// Close the drawer
mDrawerLayout.closeDrawer(mDrawerPane);*/
}
class NavItem {
String mTitle;
String mSubtitle;
int mIcon;
public NavItem(String title, int icon) {
mTitle = title;
mIcon = icon;
}
}
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
#Override
public int getCount() {
return mNavItems.size();
}
#Override
public Object getItem(int position) {
return mNavItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, null);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText( mNavItems.get(position).mTitle );
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
Please call addToBackStack(null) when you perform fragment transaction.
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.addToBackStack(null)
.commit();
Please update your OnCreateView() as below:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view != null) {
if (view.getParent() != null) {
((ViewGroup)view.getParent()).removeView(view);
}
return view;
}
View v=inflater.inflate(R.layout.tests, container, false);
I hope this helps

Recursive entry to executePendingTransactions

I have a MainDrawer to Fragment activity which has a layout for a nav drawer my and my main content where I can load new fragments into. One fragment I load in is calle StatisticsTab Fragment. This Fragment holds a tabhost which each tab is its own fragment of listview items. Once I click on a ListView item, which loads another new fragment and am no longer in the tabHost and I try to go back using the navigationdrawer to my StatisticsTab fragment I get this error:
03-03 10:32:06.884 24185-24185/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Recursive entry to executePendingTransactions
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1439)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:283)
at android.view.View.dispatchAttachedToWindow(View.java:12307)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2457)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2464)
at android.view.ViewGroup.addViewInner(ViewGroup.java:3567)
at android.view.ViewGroup.addView(ViewGroup.java:3399)
at android.view.ViewGroup.addView(ViewGroup.java:3344)
at android.view.ViewGroup.addView(ViewGroup.java:3320)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
If I do not click on any of my tabs though on the StatisticsTab fragment and navigate to another fragment via the navdrawer and then back to the StatisticsTab then it will not FC on. ALso none of the other fragments in the NavDrawer force close when I go back to them, just the one with the tabs.
MainDrawer2:
public class MainDrawer2 extends FragmentActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
getActionBar().setDisplayHomeAsUpEnabled(true);
enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
getActionBar().setHomeButtonEnabled(true);
}
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
if(navItem == mCurrentNavItem){
return;
}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
mDrawerLayout.closeDrawer(mDrawerList);
setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
StatisticsTab:
public class StatisticsTab extends Fragment {
private FragmentTabHost mTabHost;
//Mandatory Constructor
public StatisticsTab() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabs,container, false);
mTabHost = (FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("Basic").setIndicator("Basic"),
StatisticsPage.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Brewery").setIndicator("Brewery"),
BreweryStatistics.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Style").setIndicator("Style"),
StyleStatistics.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Taste").setIndicator("Taste"),
TasteStatisticsPage.class, null);
return rootView;
}
}
One of my Fragments for a tab in the tabhost which has a listview:
public class BreweryStatistics extends Fragment implements GetBreweryStatisticsJSON.OnArticleSelectedListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.brewery_statistics_layout, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
String url = "myURL";
//async task to get beer taste tag percents
GetBreweryStatisticsJSON task = new GetBreweryStatisticsJSON(getActivity());
task.setOnArticleSelectedListener(this);
task.execute(url);
// Inflate the layout for this fragment
return v;
}
#Override
public void onArticleSelected(String bID){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new BreweryPage2();
final Bundle bundle = new Bundle();
bundle.putString("breweryIDSent", bID);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
My Async task for the above fragment to load the listview:
public class GetBreweryStatisticsJSON extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public GetBreweryStatisticsJSON(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
//***************************code for on click
OnArticleSelectedListener listener;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listener = listener;
}
//*****************************end code for onClick
protected void onPreExecute() {
Dialog.setMessage("Analyzing breweries");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.yourBreweryStatistics);
//make array list for beer
final List<BreweryInfo> tasteList = new ArrayList<BreweryInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String brewery = jsonArray.getJSONObject(i).getString("brewery");
String rate = jsonArray.getJSONObject(i).getString("rate");
String breweryID = jsonArray.getJSONObject(i).getString("id");
int count = i + 1;
brewery = count + ". " + brewery;
Log.d("brewery stats", brewery);
//create object
BreweryInfo tempTaste = new BreweryInfo(brewery, breweryID, rate);
//add to arraylist
tasteList.add(tempTaste);
//add items to listview
BreweryInfoAdapter adapter1 = new BreweryInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BreweryInfo o=(BreweryInfo)arg0.getItemAtPosition(arg2);
String bID = o.breweryID;
Log.d("breweryID" , bID);
//todo: add brewery page link
//********************* add listener
listener.onArticleSelected(bID);
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
You are attempting to use fragments nested within other fragments, by way of your FragmentTabHost.
In your StatisticsTab fragment, change this:
mTabHost.setup(getActivity(), getFragmentManager(), R.id.realtabcontent);
to this:
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
Then, make sure to use the parent FragmentManager to commit the main fragment change, by changing getFragmentManager() to getActivity().getSupportFragmentManager() inside BreweryStatistics.onArticleSelected().
See:
ViewPager: Recursive entry to executePendingTransactions
Nested Fragments using support library v4 revision 11

Categories

Resources