onback pressed data not showing in fragments
Asked Answered
C

2

0

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();
            }
        }
}
Conny answered 21/8, 2015 at 4:58 Comment(11)
Are you adding these fragments to the backstack? Also please post some screenshots.Softpedal
nvm the problem is with your F2 and F3. Post their code as well.Softpedal
same code i have in fragments of F2 and F3Conny
What's the point of having 3 classes with the same code? O_@Softpedal
in every fragment i am displaying different data with different webservices..like f1 have catagories,f2 have org etc etcConny
Please post your main activity code.Seem
Add all the fragment into stack by using tagAusterlitz
can you give exampleConny
@Johnson have you checked my code github.com/rathodchintan/Fragment-Back-StackNortheasterly
@ChintanRathod but i am using json parsing..and listivew becoms null.Conny
its becoming null coz you are adding fragment over others.Northeasterly
S
7

Please call addToBackStack(null) when you perform fragment transaction.

fragmentManager.beginTransaction()
            .replace(R.id.mainContent, fragment)
            .addToBackStack(null)
            .commit();
Seem answered 21/8, 2015 at 5:56 Comment(6)
its alraedy there..can you see?Conny
It's not there in selectItemFromDrawer() function in your MainActivitySeem
there is no call to addToBackStack(null). Please see the code in my answerSeem
yes i got it..so need to remove that code after switch case and paste it to in selectitem from drawer() function??Conny
as I see it is already inside that function, just add ".addToBackStack()" thereSeem
Let us continue this discussion in chat.Conny
E
0

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

Elkin answered 17/12, 2018 at 10:38 Comment(1)
can you at least complete it ? what's view? on the line -> if (view != null) { confusing.Tecu

© 2022 - 2024 — McMap. All rights reserved.