简体   繁体   中英

How to use bundle to share data from adapter to a fragment in viewpager

I need to take the data that my adapter returns from my activity in order to send it to a fragment who works inside a viewpager.

This is my adapter, it inflates some cards with titles and descriptions for news

public class FeedAdapter extends CursorAdapter {

/*
Etiqueta de Depuración
 */
private static final String TAG = FeedAdapter.class.getSimpleName();

/**
 * View holder para evitar multiples llamadas de findViewById()
 */
static class ViewHolder {
    TextView titulo;
    TextView descripcion;

    int tituloI;
    int descripcionI;
}

public FeedAdapter(Context context, Cursor c, int flags) {
    super(context, c, flags);

}

public View newView(Context context, Cursor cursor, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());

    View view = inflater.inflate(R.layout.item_layout, null, false);

    ViewHolder vh = new ViewHolder();

    // Almacenar referencias
    vh.titulo = (TextView) view.findViewById(R.id.titulo);
    vh.descripcion = (TextView) view.findViewById(R.id.descripcion);

    // Setear indices
    vh.tituloI = cursor.getColumnIndex(ScriptDatabase.ColumnEntradas.TITULO);
    vh.descripcionI = cursor.getColumnIndex(ScriptDatabase.ColumnEntradas.DESCRIPCION);

    view.setTag(vh);

    return view;
}

public void bindView(View view, Context context, Cursor cursor) {

    final ViewHolder vh = (ViewHolder) view.getTag();

    // Setear el texto al titulo
    vh.titulo.setText(cursor.getString(vh.tituloI));

    // Obtener acceso a la descripción y su longitud
    int ln = cursor.getString(vh.descripcionI).length();
    String descripcion = cursor.getString(vh.descripcionI);

    // Acortar descripción a 77 caracteres
     vh.descripcion.setText(descripcion);


}
}

And this is the fuction in my Activity where I want to create the viewpager at the same time I'm sending a bundle with the adapter's return

public class LoadData extends AsyncTask<Void, Void, Cursor> {

        @Override
        protected Cursor doInBackground(Void... params) {
            // Carga inicial de registros
            return FeedDatabase.getInstance(MainActivity.this).obtenerEntradas();

        }

        @Override
        protected void onPostExecute(Cursor cursor) {
            super.onPostExecute(cursor);

            // Crear el adaptador
            adapter = new FeedAdapter(
                    MainActivity.this,
                    cursor,
                    SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

            // Relacionar la lista con el adaptador
            Bundle arguments = new Bundle();
            arguments.putString(adapter);

            viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), arguments);
            viewPager.setAdapter(viewPagerAdapter);
        }
    }

}

But everytime a I use "arguments.putString" it returns me an error. I'm confused because I don't know what kind of ".put" I should use with the data I receive from the adapter and how Bundle really works.

Could you help me ? Thanks

将其发送到Activity并在片段中使用getIntent()。getStringExtra(“ Name”)。

Solution:

First the adapter must implements Serializable

public class FeedAdapter extends CursorAdapter implements Serializable{

The bundle that works is

Bundle arguments = new Bundle();
arguments.putSerializable("datos",adapter);

And I send it to my viewpager like this

viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), arguments);
viewPager.setAdapter(viewPagerAdapter);

My viewPager takes the data like this

public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Bundle data;

public ViewPagerAdapter(FragmentManager fm, Bundle data) {
    super(fm);
    this.data = data;
}

@Override
public Fragment getItem(int position) {

    TabFragment tab1 = new TabFragment();
    tab1.setArguments(data);

    return tab1;    // Which Fragment should be displayed by the viewpager for the given position
    // In my case we are showing up only one fragment in all the three tabs so we are
    // not worrying about the position and just returning the TabFragment
}

@Override
public int getCount() {
    return 3;           // As there are only 3 Tabs
}

}

And finally my fragment get the arguments and implements the adapter like this

public class TabFragment extends ListFragment {

private Bundle bundle;
private FeedAdapter adapter;


@Override
public void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    bundle = getArguments();
    adapter = (FeedAdapter) bundle.getSerializable("datos");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View root = inflater.inflate(R.layout.tabs, container, false);

    ListView LV = (ListView) root.findViewById(R.id.lista);
    LV.setAdapter(adapter);
    return root;
}

}

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM