1

I'm trying to restore my App with Navigation Drawer Activity, but in the old version with simple activity I've some Dialog that take data from the user and manage it inside activity.

Now I've fragments and I get some problem by getting back the data from user.

My first problem: The MainActivity contain 4 Fragments, one of them have a lot of Buttons that use an onClick method in the XML. With Activity all work without problem but with Fragments I can't declare the method of the onClick xml!

The second problem is that the method of the onClick call a DialogActivity with startActivityForResult and take back data with onActivityResult. I move the method of the onClick inside the MainActivity that contain the Fragment, but when it start the Dialog with startActivityForResult the onActivityResult inside Fragments it's not called.

I try to move it inside the Activity and pass the received data to the Fragment with interface but i get error to function Drawable style = setButtonColor(color);inside the onActivityResult

What is the best way to perform this? Better to remove the DialogActivity and use DialogFragment for take data back without startActivityForResult and onActivityResult?

Here the code that I need to adapt with the new Fragment graphics

<Button
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_weight="1"
         android:text="@string/new_button"
         android:id="@+id/m12"
         android:onClick="addMateria"
         android:background="@drawable/buttons"
         android:singleLine="true"
         android:textSize="12sp"
         android:layout_column="2" />

The method of the onClick

public void addMateria(View v){

        /* Prendo il nome della risorsa cosi nel ricompilare il progetto non perdo *
         * tutti i riferimenti ai bottoni salvati nel database                     */

        clickedButtonViewId = getResources().getResourceEntryName(v.getId());

        //StartActivityForResult perche mi aspetto la materia inserita dall'altra activity
        Intent myIntent = new Intent(MainActivity.this, DialogAddMateria.class);
        startActivityForResult(myIntent, 1);
        //onStop();
    }

And how i take back data

//Take back data from ActivityAddMateria
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(requestCode == 1) {
            if (resultCode == Activity.RESULT_OK) {

                MySQLiteHelper db = new MySQLiteHelper(getActivity());


                Toast.makeText(getContext(), "DENTRO ACTIVITYRESULT",
                        Toast.LENGTH_LONG).show();

                //Cambio subito il Button
                int resId = getResources().getIdentifier(clickedButtonViewId, "id", getActivity().getPackageName());
                final Button clickedtextView = (Button) getActivity().findViewById(resId);

                String result = data.getStringExtra("result"); //Take the materia from Dialog
                int color = data.getIntExtra("color", 1); //Take the color from Dialog

                //Controllo se il Button è già presente nel db se presente aggiorno se non presente inserisco
                boolean modifica = db.Exists(clickedButtonViewId);

                //Se voglio ripristinare il bottone di default
                if (color == getResources().getColor(R.color.blue_orario)) {

                    //Ripristino la grafica di Default
                    Drawable style = setButtonColor(color);
                    clickedtextView.setBackground(style);
                    clickedtextView.setText("New");

                    //Se la materia è nel database la cancello
                    if (modifica) {

                        db.deleteSingleMateria(clickedButtonViewId);

                    }

                } else {
                    //Quando inserisco un normale bottone colorato
                    if (!modifica) {

                        //Materia da inserire in un nuovo spazio
                        db.addMateriaToDb(new Materia(clickedButtonViewId, result, color));

                    } else {

                        //Materia già presente nel Button quindi aggiorno la materia
                        db.updateMateria(new Materia(clickedButtonViewId, result, color));
                        Toast.makeText(getContext(), "Materia modificata!",
                                Toast.LENGTH_LONG).show();
                    }

                    //Inserisco la materia nel DB dei voti_media
                    db.addMateriaVotiFromOrario(new MaterieVoti(result, 0.0));

                    clickedtextView.setText(result);
                    //clickedtextView.setBackgroundColor(color);
                    //clickedtextView.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
                    Drawable style = setButtonColor(color);
                    clickedtextView.setBackground(style);
                }
            }

            if (resultCode == Activity.RESULT_CANCELED) {
                //Nessuna materia inserita
            }

        }
    }//onActivityResult

I am unfamiliar with Fragments and i have some difficult to do what i need, if someone can tell me how do that, or suggest to change the communication between the onClick and method, Fragment and method, i'm here!

PriyankaChauhan
  • 953
  • 11
  • 26
Dario
  • 732
  • 7
  • 30

2 Answers2

1

This question is asked many times, Communication between activity and fragment can be done in many ways like passing data in bundle, Making Singleton pattern explained as per here and using EventBus also, see this answer, I have explained every aspect how you can do it and if you want more understanding then comment it.

Official docs are here

Community
  • 1
  • 1
TapanHP
  • 5,969
  • 6
  • 37
  • 66
  • Yes but the problem with the method? In post i explain my situation not only passing data between activity and fragment :D. The main problem is that i can't declare the method inside Fragment (addMateria()) and if i declare it inside MainActivity the onAcitivityResult inside fragment don't take back data from the called DialogAcitivity – Dario Sep 20 '16 at 14:23
  • Inside your fragments you can get activity context all you have to do is call onActivityResult() in your fragment and you also have to implement it in your activity and then refer it in fragment by calling super.onActivityResult() and you can solve this issue – TapanHP Sep 20 '16 at 14:59
  • i Solved with this solution....all declared inside MainActivity...the method addMateria() ...so the startActivityForResult and the onAcitivityResult too...and still working...it's correct how i do? Or it work but it's illegal :D – Dario Sep 20 '16 at 15:06
  • Accept answer if helpful so others can get solution – TapanHP Sep 20 '16 at 17:20
  • this is not the solution because you answere only a part of the problem – Dario Sep 20 '16 at 17:21
  • Edit it as per your solution – TapanHP Sep 20 '16 at 17:23
1

Added all to the MainActivity:

The method called in the xml of the Fragment that if the button is pressed startActivityForResult for take data from User.

After that i write the onActivityResult inside the MainActivity that when take data back save it into DB and modify the style of the button inside the Fragment.

MainAcitivty that contain the Fragments

public void addMateria(View v){

        /* Prendo il nome della risorsa cosi nel ricompilare il progetto non perdo *
         * tutti i riferimenti ai bottoni salvati nel database                     */

        clickedButtonViewId = getResources().getResourceEntryName(v.getId());

        //StartActivityForResult perche mi aspetto la materia inserita dall'altra activity
        Intent myIntent = new Intent(MainActivity.this, DialogAddMateria.class);
        startActivityForResult(myIntent, 1);
        //onStop();
    }

    //Take back data from ActivityAddMateria
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(requestCode == 1) {
            if (resultCode == Activity.RESULT_OK) {

                MySQLiteHelper db = new MySQLiteHelper(this);

                //Cambio subito il Button
                int resId = getResources().getIdentifier(clickedButtonViewId, "id", getPackageName());
                final Button clickedtextView = (Button) findViewById(resId);

                String result = data.getStringExtra("result"); //Take the materia from Dialog
                int color = data.getIntExtra("color", 1); //Take the color from Dialog

                //Controllo se il Button è già presente nel db se presente aggiorno se non presente inserisco
                boolean modifica = db.Exists(clickedButtonViewId);

                //Se voglio ripristinare il bottone di default
                if (color == getResources().getColor(R.color.blue_orario)) {

                    //Ripristino la grafica di Default
                    Drawable style = setButtonColor(color);
                    clickedtextView.setBackground(style);
                    clickedtextView.setText("...");

                    //Se la materia è nel database la cancello
                    if (modifica) {

                        db.deleteSingleMateria(clickedButtonViewId);

                    }

                } else {
                    //Quando inserisco un normale bottone colorato
                    if (!modifica) {

                        //Materia da inserire in un nuovo spazio
                        db.addMateriaToDb(new Materia(clickedButtonViewId, result, color));

                    } else {

                        //Materia già presente nel Button quindi aggiorno la materia
                        db.updateMateria(new Materia(clickedButtonViewId, result, color));
                        Toast.makeText(MainActivity.this, "Materia modificata!",
                                Toast.LENGTH_LONG).show();
                    }

                    //Inserisco la materia nel DB dei voti_media
                    db.addMateriaVotiFromOrario(new MaterieVoti(result, 0.0));

                    clickedtextView.setText(result);
                    //clickedtextView.setBackgroundColor(color);
                    //clickedtextView.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
                    Drawable style = setButtonColor(color);
                    clickedtextView.setBackground(style);
                }
            }

            if (resultCode == Activity.RESULT_CANCELED) {
                //Nessuna materia inserita
            }

        }
    }//onActivityResult

The Fragment simple check if data is in the DB and update the view

    List<Materia> materia;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.orario_view, container, false);

       MySQLiteHelper db = new MySQLiteHelper(getActivity());

        //Get all materie inside database
        materia = db.getAllMaterie();
        //change all TextView inputed from user
        if(materia.isEmpty()){
            //do nothing
        }else {
            for (Materia mat : materia) {
                //Change all the Button with values stored inside the database
                int resId = getResources().getIdentifier(mat.getID(), "id", getActivity().getPackageName());
                Button changedButton = (Button) view.findViewById(resId);
                changedButton.setText(mat.getMateria());
                changedButton.setTypeface(null, Typeface.BOLD);

                Drawable style = setButtonColor(mat.getColor());
                changedButton.setBackground(style);
            }
        }

        return view;
    }
Dario
  • 732
  • 7
  • 30