user3055923
user3055923

Reputation: 195

Android: getArguments() always gets null value

I am new to android and i've been stucked in this problem for 2 days. My fragment cannot get the argument from my activity. here is my code in activity.

private void CountUnreadNotifications() {
        Cursor unread = db.getUnread();
        Bundle bundle = new Bundle();
        String number = Integer.toString(unread.getCount());
        bundle.putString("noOfNotif", number);
        BottomFragment fragment = new BottomFragment();
        fragment.setArguments(bundle);
    }

I am sure that the variable number is not null. And here is my code in the fragment.

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        String i = null;
        Bundle bundle = this.getArguments();
        if(bundle != null){
            i = bundle.getString("noOfNotif");
        }
        else {
             i = "0";
        }

        View view = inflater.inflate(R.layout.fragment_menu_page, container,
                false);

        txtnoNotif = (TextView) view.findViewById(R.id.txtnoNotif);     
        txtnoNotif.setText(i);

Please can somebody help me to answer this question. Thanks. Here is my code in Activity Oncreate

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu_page);

        mDB.Open();
        CountUnreadNotifications();
        viewFragment();

    }

View Fragment method.

private void viewFragment() {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        BottomFragment myFragment = new BottomFragment();
        ft.add(R.id.linearLayout, myFragment);
        ft.commit();
    }

Upvotes: 3

Views: 940

Answers (1)

Lazy Ninja
Lazy Ninja

Reputation: 22537

Your CountUnreadNotifications() method is not complete.
Change it as below and comment out viewFragment()

private void CountUnreadNotifications() {
    Cursor unread = db.getUnread();
    Bundle bundle = new Bundle();
    String number = Integer.toString(unread.getCount());
    bundle.putString("noOfNotif", number);
    BottomFragment fragment = new BottomFragment();
    fragment.setArguments(bundle);
    FragmentTransaction trans = mManager.beginTransaction();
    trans.replace(R.id.fragment_container, fragment ); // change fragment_container to your container
    trans.commit(); 

    }

My guess is your trying to transit to BottomFragment in your method viewFragment() where you have to initialize BottomFragment fragment = new BottomFragment(); againg thus loosing your arguments.
Please post viewFragment();

Upvotes: 2

Related Questions