azuosxela
azuosxela

Reputation: 250

Passing Values to ViewPager Fragment

I want to pass dogruYanlis value which is an integer array to these fragments. If I try to handle this with bundle it it sends anything. The array that I received in fragment class is always null. I think that I can't handle with bundle but I don't know how I can solve this problem...

The Activity that I want to send data

package oztiryaki.my;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;


public class result extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    private Bundle bundle;
    int[] dogruYanlis;

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

        toolbar = (Toolbar) findViewById(R.id.toolbarResult);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        Bundle list = getIntent().getExtras();
        if(list == null){
            return;
        }
        dogruYanlis = list.getIntArray("dogruYanlis");

    }

    @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;

    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        bundle = new Bundle();
        bundle.putIntArray("dogruYanlis", dogruYanlis);

        result2015Fragment f15 = new result2015Fragment();
        f15.setArguments(bundle);

        result2014Fragment f14 = new result2014Fragment();
        f14.setArguments(bundle);

        result2013Fragment f13 = new result2013Fragment();
        f13.setArguments(bundle);

        adapter.addFragment(f15, "2015");
        adapter.addFragment(f14, "2014");
        adapter.addFragment(f13, "2013");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

The one of fragment activity

package oztiryaki.my;

        import android.os.Bundle;
        import android.support.annotation.Nullable;
        import android.support.v4.app.Fragment;
        import android.util.Log;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.TextView;
        import android.widget.Toast;

/**
 * Created by oztir on 21.02.2016.
 */
public class result2015Fragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.result2015,container,false);
        int[] dogruYanlis = getArguments().getIntArray("dogruYanlis");
        if(dogruYanlis == null){
            Toast.makeText(getActivity(),"null sory:(", Toast.LENGTH_LONG).show();
        }
        TextView ygs1hp = (TextView) v.findViewById(R.id.ygs1hp);

        return v;
    }
    public void getArray(int[] dogruYanlis){
        Toast.makeText(getActivity(),Integer.toString(dogruYanlis[0]), Toast.LENGTH_LONG).show();
    }
}

Upvotes: 2

Views: 7136

Answers (2)

B1nd0
B1nd0

Reputation: 110

I had a similar struggle, maybe this will help. In case if your variables in the activity are not changing after it is created, there is one simple way to reach out to the activity's variables from the fragment it creates:

  1. get the context in the fragment
  2. then you can get the value of the variable from the fragment

    Context context;
    
    public void onViewCreated(View v, Bundle savedInstanceState) {
        context = getActivity();
        int i = ((result)context).dogruYanlis[0];
    }
    

Upvotes: 1

pamobo0609
pamobo0609

Reputation: 812

Try to create a Fragment using the wizard that Android studio provides, which gives you a dummy Fragment, with all the Fragment methods you need to pass data and such:

package FRAGMENTS;

import android.app.Fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentLifecycleDemo extends Fragment {
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String TEXT1 = "text1";
    private static final String TEXT2 = "text2";

    // the two strings are going to be used here
    private TextView title;
    private TextView subtitle;

    private String text1;
    private String text2;

    private Context c;

    private OnFragmentInteractionListener mListener;

    public FragmentLifecycleDemo(Context c) {
        // Required empty public constructor
        this.c = c;
    }

    public static FragmentLifecycleDemo newInstance(String title, String subtitle, Context c) {
        FragmentLifecycleDemo fragment = new FragmentLifecycleDemo(c);
        Bundle args = new Bundle();
        args.putString(TEXT1, title);
        args.putString(TEXT2, subtitle);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Toast.makeText(c, "Hi! onCreate has just been called.", Toast.LENGTH_SHORT).show();
        if (getArguments() != null) {
            text1 = getArguments().getString(TEXT1);
            text2 = getArguments().getString(TEXT2);
        }
    }

    private void init(View v) {
        title = (TextView) v.findViewById(R.id.txtTry);
        title.setText(text1);

        subtitle = (TextView) v.findViewById(R.id.txtReal);
        subtitle.setText(text2);
    }

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

        View v = inflater.inflate(R.layout.fragment_lifecycle_demo, container, false);
        init(v);
        Toast.makeText(c, "Greetings from onCreateView!", Toast.LENGTH_SHORT).show();
        return v;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        Toast.makeText(c, "Is it me, or a button has just been pressed?", Toast.LENGTH_SHORT).show();
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Toast.makeText(c, "Howdy! I've just been attached to the activity.", Toast.LENGTH_SHORT).show();
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Toast.makeText(c, "Oh no! I've been detached u.u", Toast.LENGTH_SHORT).show();
        mListener = null;
    }

    /**
     * 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);
    }
}

As you can see, the method where you should get the Bundle is the onCreate one, that receives the data you want to be available on the Fragment, which was send from the constructor named newInstance.

Upvotes: 1

Related Questions