Search code examples
androidandroid-fragmentsandroid-tabhostandroid-tabs

Cannot get the position of the tabhost from a fragment to another fragment using bundle


I have two fragments. One is for the tab and one is for the main layout that calls a list view. I am having trouble passing the "position" from my AlarmTab Class to my AlarmActivity Class. The position is being passed but it only gets the length of my array. When i click a list from my position [0] tab, it returns the length of myTabHost and not the clicked tab. I want to get the position of the clicked and below are the codes of what i have done so far. I've been working with this for hours already. Hopefully someone can help me point out what i am missing. Thank you in advance!

from AlarmTab Class

mTabHost = (FragmentTabHost) rootView.findViewById(android.R.id.tabhost);
widget = (TabWidget) rootView.findViewById(android.R.id.tabs);
hs = (HorizontalScrollView) rootView.findViewById(R.id.horizontalScrollView);
mTabHost.setup(getActivity(), getChildFragmentManager(), android.R.id.tabcontent);

for(int i=0; i<SmashDeviceData.get_instance().devices.size(); i++) {

    AlarmActivity alarmActivity = new AlarmActivity();
    Bundle bundle = new Bundle();
    bundle.putInt("position", i);
    alarmActivity.setArguments(bundle);
    mTabHost.addTab(mTabHost.newTabSpec("i").setIndicator(SmashDeviceData.get_instance().devices.get(i).deviceName), AlarmActivity.class, bundle);
    } 

and from AlarmActivity Class

   public void addAlarm(){
        ImageView addAlarmButton = (ImageView) getActivity().findViewById(R.id.add_alarm);
        addAlarmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentActivity mainDrawer = (FragmentActivity) context;
                Fragment fragment;
                Bundle b = getArguments();
                int position = b.getInt("position", 0);
                Toast.makeText(context, String.valueOf(b.getInt("position")), Toast.LENGTH_SHORT ).show();
                fragment = AlarmSetActivity.newInstance(context, position);
                FragmentManager fragmentManager = mainDrawer.getSupportFragmentManager();
                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.replace(R.id.content_frame, fragment);
                ft.addToBackStack(null);
                ft.commit();
            }
        });
    }

Solution

  • Your problem lies on this line

        mTabHost.addTab(mTabHost.newTabSpec("i").setIndicator(SmashDeviceData.get_instance().
        devices.get(i).deviceName), AlarmActivity.class, bundle);
    

    It should be like this

        mTabHost.addTab(mTabHost.newTabSpec(SmashDeviceData.get_instance().
        devices.get(i).deviceName).setIndicator(SmashDeviceData.get_instance().devices.get(i).
        deviceName), AlarmActivity.class, bundle);