Search code examples
androidandroid-fragmentsandroid-activitydialogfragment

Acitivity and Fragment communication by a method inside xml Button


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!


Solution

  • 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;
        }