Programación y Desarrollo para Android Subforo exclusivo para temas de programación de software para PDAs y desarrollo de aplicaciones, interfaces, etc bajo Android

Respuesta
 
Herramientas
  #1  
Viejo 23/04/15, 15:50:19
Array

[xs_avatar]
zabulon zabulon no está en línea
Usuario poco activo
 
Fecha de registro: abr 2015
Localización: Valencia
Mensajes: 1
Modelo de smartphone: Moto G (2013)
Tu operador: Yoigo
rom PROBLEMA ¿Como pasar datos entre distintos fragments?

¡¡¡ Buenas a todos !!! Llevo un tiempo dandole vueltas a un problema que no consigo solucionar y alfinal decidi venir por aqui aver si alguien puede darme algo de soporte.

Comence mi proyecto con un NavegationDrawer que segun la seccion que seleccionas carga el fragment de la seccion seleccionada en un container con un ListFragment donde muestra items de una tabla de sqlite, necesito que al hacer click en uno de los items capture la id del campo y en ese mismo container cargue el FragmentDetail del item seleccionarlo para poder asi editar sus datos. (Consigo que me cambie el fragment pero no que pase el valor id del item seleccionado)

ESTE ES MI MAIN ACTIVITY
Código:
public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {
    TextView student_Id;
    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

    @override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

        //student esta en el codigo

        //termina studentconfig pane


    }


    @override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments

        FragmentManager fragmentManager = getSupportFragmentManager();
        //fragmentManager.beginTransaction()
                //.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                //.commit();
        if (position == 0) {
            fragmentManager.beginTransaction()
                    .replace(R.id.container, Fragment1.newInstance())
                    .commit();
        } else if (position == 1) {
            fragmentManager.beginTransaction()
                    .replace(R.id.container, Fragment2.newInstance())
                    .commit();
        } else if (position == 2) {
            fragmentManager.beginTransaction()
                    .replace(R.id.container, Fragment3.newInstance())
                    .commit();
        }

    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.title_section1);
                break;
            case 2:
                mTitle = getString(R.string.title_section2);
                break;
            case 3:
                mTitle = getString(R.string.title_section3);
                break;
        }
    }


    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }


        @override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }

        @override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }

}
ESTE ES EL FRAGMENT 1 (listfragment)
Código:
public class Fragment1 extends ListFragment implements AdapterView.OnItemClickListener {
    TextView student_Id;

    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static Fragment1 newInstance() {
        Fragment1 fragment = new Fragment1();
        return fragment;
    }

    public Fragment1() {
    }

    @override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fragment1, container,
                false);
        //DBHelper db = new DBHelper(getActivity());
        ImageButton btnAddperfilrs = (ImageButton) view.findViewById(R.id.btnAddperfilrs);
        btnAddperfilrs.setOnClickListener(new View.OnClickListener() {

            @override
            public void onClick(View v) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.container, FragStudentDetail.newInstance())
                        .commit();
            }
        });
        StudentRepo repo = new StudentRepo(getActivity());
        student_Id = (TextView) view.findViewById(R.id.student_Id);
        return view;
    }
    @override
    public void onActivityCreated(Bundle savedInstanceState) {
        StudentRepo repo = new StudentRepo(getActivity());
        super.onActivityCreated(savedInstanceState);
        ListView lv= (ListView) getActivity().findViewById(android.R.id.list);
        ArrayList<HashMap<String, String>> studentList =  repo.getStudentList();
        if(studentList.size()!=0) {
            ListAdapter adapter = new SimpleAdapter(getActivity(), studentList,
                    R.layout.view_student_entry,
                    new String[] { "id","name","apellidos","age","nacionalidad","ciudad","direccion","telefono","email" }, new int[] {
                    R.id.student_Id, R.id.student_name, R.id.student_apellidos, R.id.student_age, R.id.student_nacionalidad, R.id.student_ciudad, R.id.student_direccion, R.id.student_telefono, R.id.student_email });

            setListAdapter(adapter);
            lv.setAdapter(adapter);
            getListView();
            lv.setOnItemClickListener(this);



    }}

        @override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(1);
    }



    @override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //esto es lo que no va
        String studentId = ((TextView) view.findViewById(R.id.student_Id)).getText().toString();
        //student_Id = (TextView) view.findViewById(R.id.student_Id);

        FragStudentDetail fragment = new FragStudentDetail();
        Bundle param = new Bundle();
        param.putString("student_Id", studentId);
        fragment.setArguments(param);
        //TODO:// eSTA ES LA LINEA DE LA CAUSA MIRAR POR AQUI
        final FragmentTransaction ft = getFragmentManager()
                .beginTransaction();
        ft.replace(R.id.container, fragment, "tag");
        ft.commit();
        //esto es lo que no va
    }
}
Y ESTE ES EL FRAGSTUDENTDETAIL (DESDE DONDE BUSCO EDITAR LOS DATOS AL PASAR EL ID DEL STUDENT DESDE FRAGMENT 1)

Código:
public class FragStudentDetail extends Fragment {
    Button btnSave ,  btnDelete;
    Button btnClose;
    EditText editTextName;
    EditText editTextEmail;
    EditText editTextAge;
    EditText editTextApellidos;
    EditText editTextNacionalidad;
    EditText editTextCiudad;
    EditText editTextTelefono;
    EditText editTextDireccion;
    private int _Student_Id=0;
    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static FragStudentDetail newInstance() {
        FragStudentDetail fragment = new FragStudentDetail();

        return fragment;
    }

    public FragStudentDetail() {

    }

    @override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragstudentdetail, container,
                false);

        btnSave = (Button) rootView.findViewById(R.id.btnSave);
        btnDelete = (Button) rootView.findViewById(R.id.btnDelete);
        btnClose = (Button) rootView.findViewById(R.id.btnClose);

        editTextName = (EditText) rootView.findViewById(R.id.editTextName);
        editTextEmail = (EditText) rootView.findViewById(R.id.editTextEmail);
        editTextApellidos = (EditText) rootView.findViewById(R.id.editTextApellidos);
        editTextNacionalidad = (EditText) rootView.findViewById(R.id.editTextNacionalidad);
        editTextCiudad = (EditText) rootView.findViewById(R.id.editTextCiudad);
        editTextTelefono = (EditText) rootView.findViewById(R.id.editTextTelefono);
        editTextDireccion = (EditText) rootView.findViewById(R.id.editTextNotas_tr);
        editTextAge = (EditText) rootView.findViewById(R.id.editTextAge);



        btnSave.setOnClickListener(new View.OnClickListener() {

            @override
            public void onClick(View v) {
                StudentRepo repo = new StudentRepo(getActivity());
                Student student = new Student();
                student.age= Integer.parseInt(editTextAge.getText().toString());
                student.email=editTextEmail.getText().toString();
                student.name=editTextName.getText().toString();

                student.apellidos=editTextApellidos.getText().toString();
                student.direccion=editTextDireccion.getText().toString();
                student.nacionalidad=editTextNacionalidad.getText().toString();
                student.ciudad=editTextCiudad.getText().toString();
                student.telefono=editTextTelefono.getText().toString();
                student.student_ID=_Student_Id;

                if (_Student_Id==0){
                    _Student_Id = repo.insert(student);

                    Toast.makeText(getActivity(), "Perfil Guardado", Toast.LENGTH_SHORT).show();
                    //metodo para refrescar volviendo a la MainActivity
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.container, Fragment1.newInstance())
                            .commit();
                }else{

                    repo.update(student);
                    Toast.makeText(getActivity(),"Perfil Actualizado",Toast.LENGTH_SHORT).show();
                    //metodo para refrescar volviendo a la MainActivity
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.container, Fragment1.newInstance())
                            .commit();
            }
        }});
            btnDelete.setOnClickListener(new View.OnClickListener() {

            @override
            public void onClick(View v) {
                StudentRepo repo = new StudentRepo(getActivity());
                repo.delete(_Student_Id);
                Toast.makeText(getActivity(), "Perfil Borrado", Toast.LENGTH_SHORT);

                //metodo para refrescar volviendo a la MainActivity
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.container, Fragment1.newInstance())
                        .commit();
            }
        });
        btnClose.setOnClickListener(new View.OnClickListener() {

            @override
            public void onClick(View v) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.container, Fragment1.newInstance())
                        .commit();
            }
        });


        Bundle param = new Bundle();

        _Student_Id =param.getInt("student_Id", 0);
        StudentRepo repo = new StudentRepo(getActivity());
        Student student = new Student();
        student = repo.getStudentById(_Student_Id);


        editTextName.setText(student.name);
        editTextEmail.setText(student.email);
        editTextApellidos.setText (student.apellidos);
        editTextNacionalidad.setText (student.nacionalidad);
        editTextCiudad.setText (student.ciudad);
        editTextTelefono.setText (student.telefono);
        editTextDireccion.setText (student.direccion);
        editTextAge.setText(String.valueOf(student.age));
        return rootView;
    }

    @override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(1);
    }

}
Muchas gracias de antemano, estare totalmente agradecido de cualkquier ayuda posible
Un saludo.
Responder Con Cita


  #2  
Viejo 25/04/15, 20:44:51
Array

[xs_avatar]
oxot oxot no está en línea
Usuario muy activo
 
Fecha de registro: may 2010
Localización: Santiago
Mensajes: 741
Modelo de smartphone: Xiaomi RedRice
Tu operador: Pepephone
Es mucho código para evaluarlo todo así que te haré la pregunta directamente, lo has intentado como recomienda google?
http://developer.android.com/guide/c...ngWithActivity
Las comunicaciones entre fragment nunca se hacen directamente sino implementando un Callback en la actividad contenedora. Al callback le metes el parámetro que tu quiera y lo tendrás disponible en la actividad contenedora para enviárselo al fragment que a ti te de la gana.
Un saludo.

PS. No he visto ningún Callback en tu MainActivity así que supongo que no...
Responder Con Cita
  #3  
Viejo 08/05/15, 12:24:22
Array

[xs_avatar]
kohario88 kohario88 no está en línea
Miembro del foro
 
Fecha de registro: abr 2015
Mensajes: 79
Tu operador: Movistar

Yo también tuve ese problema e incluso usando ese método me fallaba. Luego vi que ademas de varios fallos en el manifest, indicaba mal que tipo de informacion queria pasar. Lo digo porque igual te pasa algo asi. Android es muy puntilloso
Responder Con Cita
Respuesta

Estás aquí
Regresar   Portal | Indice > Todo sobre Android > Programación y Desarrollo para Android



Hora actual: 20:36:33 (GMT +1)



User Alert System provided by Advanced User Tagging (Lite) - vBulletin Mods & Addons Copyright © 2025 DragonByte Technologies Ltd.

Contactar por correo / Contact by mail / 邮件联系 /