简体   繁体   中英

Passing variables from Dialog to Listview fragment

I am making a fragment with a Listview consisting of IP adresses that the user will be prompted to input via a Dialog, which will pop up upon the press of a + button.

I would like to extract the value of the edittext introduced by the user on the Dialog, and use it to populate the Listview of the "main" fragment.

Problem is, I am either having scope problems or Logcat errors like :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int) on a null object reference

I have 2 classes :

UserSettings.java

Containing a listview with hard-coded test strings, two buttons (one of which calls the method openDialog)

public class UserSettings extends Fragment implements SettingsIPDialog.IPDialogListener {
private static final String TAG = "UserSettings";
Context context;


UserSettings(Context ctx) {
    context = ctx;
}

private ImageButton addIP_button;
private ImageButton notification_button;
SwipeMenuListView listView;
ArrayList<String> list;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_settings, container, false);
     listView = v.findViewById(R.id.listView);
    addIP_button = v.findViewById(R.id.imageButton_AddIP);
    notification_button = v.findViewById(R.id.imageButton_modifySettings);
    String IPnumber ="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    if(settingsIPDialog != null) {
         IPnumber = ((EditText) settingsIPDialog.getView().findViewById(R.id.edit_ip_address)).getText().toString();
    }
    System.out.println(IPnumber);
   list = new ArrayList<>();
    list.add("IP1");
    list.add("IP2");
    list.add("IP3");
    list.add("IP4");
    list.add("IP6");
    list.add("IP7");
    list.add("IP8");


    final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, list);
    listView.setAdapter(adapter);

    SwipeMenuCreator creator = new SwipeMenuCreator() {
        @Override
        public void create(SwipeMenu menu) {
            //Open :
            SwipeMenuItem openItem = new SwipeMenuItem(context);

            //Set item background
            openItem.setBackground(new ColorDrawable(Color.GRAY));
            //Set item width
            openItem.setWidth(200);

            //Set item title
            openItem.setTitle("Modifier");

            //Set item titlesize
            openItem.setTitleSize(18);

            //Set item titlecolour
            openItem.setTitleColor(Color.BLACK);

            //Add to menu :
            menu.addMenuItem(openItem);

            //Create "delete" item

            SwipeMenuItem deleteItem = new SwipeMenuItem(context);

            //set item background
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
            //set item width
            deleteItem.setWidth(200);

            deleteItem.setIcon(R.drawable.ic_delete);

            //Add to menu :
            menu.addMenuItem(deleteItem);

        }
    };
    listView.setMenuCreator(creator);
    listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
            switch (index) {
                case 0:
                    Log.d(TAG, "onMenuItemClick: clicked item " + index);
                    break;
                case 1:
                    Log.d(TAG, "onMenuItemClick: clicked item " + index);
                    break;
            }
            // false : close the menu; true : not close the menu
            return false;
        }
    });

    addIP_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openDialog();
        }
    });
    notification_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDialog2();
        }
    });



    return v;


}
SettingsIPDialog settingsIPDialog;
public void openDialog() {
     settingsIPDialog = new SettingsIPDialog();
    settingsIPDialog.show(getFragmentManager(), "Ajouter un serveur");
    String IPnumber ="bbbbbbbbbbbbbbbbbbbbb";
    if(settingsIPDialog != null) {
        System.out.println(IPnumber);
        IPnumber = ((EditText) settingsIPDialog.getView().findViewById(R.id.edit_ip_address)).getText().toString(); //ERROR ORIGINATING FRO
        settingsIPDialog.getDialog().findViewById(R.id.edit_ip_address);
    }
     ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, list);
    listView.setAdapter(adapter);

}

public void openDialog2() {
    SettingsIPDialog2 settingsIPDialog2 = new SettingsIPDialog2();
    settingsIPDialog2.show(getFragmentManager(), "Paramètres");
}


@Override
public void applyIP(String IPnumber, String IPname) {

}}

Another one containing the Dialog itself :

SettingsIPDialog.java

public class SettingsIPDialog extends AppCompatDialogFragment {
    private EditText editTextIPNum;
    private EditText editTextIPname;
    private SettingsIPDialog listener;


    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.layout_dialog_ip, null);
        builder.setView(view).setTitle("Ajouter une adresse IP").setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        })
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        String IPnumber = editTextIPNum.getText().toString();
                        String IPname = editTextIPname.getText().toString();


                    }
                });

        editTextIPNum = view.findViewById(R.id.edit_ip_address);
        editTextIPname = view.findViewById(R.id.edit_ip_name);
        return builder.create();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            //listener = (IPDialogListener)context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + "Il faut implémenter IPDialogListener");
        }
    }


    public interface IPDialogListener {
        void applyIP(String IPnumber, String IPname);
    }
}

Just so you know, I am a complete beginner in Java, this is something I've done by piecing together 3 different examples I found on the internet.

Thank you very much for reading and for any help you'd be willing to give me.

EDIT :

layout_dialog_ip

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:padding="16dp">

<EditText
    android:id="@+id/edit_ip_address"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Adresse IP" />

<EditText
    android:id="@+id/edit_ip_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/edit_ip_address"
    android:hint="Nom du serveur"
    android:inputType="text" />

</RelativeLayout>

layout_fragment_settings

   <?xml version="1.0" encoding="utf-8"?>
   <android.support.constraint.ConstraintLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/frameLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".UserSettings">



   <ImageButton
    android:id="@+id/imageButton_modifySettings"
    android:layout_width="46dp"
    android:layout_height="49dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:src="@drawable/ic_settings_ip"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/imageButton_AddIP"
    app:layout_constraintHorizontal_bias="0.03"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="1.0" />

   <ImageButton
    android:id="@+id/imageButton_AddIP"
    android:layout_width="46dp"
    android:layout_height="49dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:src="@android:drawable/ic_input_add"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="1.0" />

   <com.baoyz.swipemenulistview.SwipeMenuListView
    android:id="@+id/listView"
    android:layout_width="392dp"
    android:layout_height="514dp"
    app:layout_constraintDimensionRatio="1:1"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="0dp">

</com.baoyz.swipemenulistview.SwipeMenuListView>
</android.support.constraint.ConstraintLayout>

AppCompatDialogFragment inherits from Fragment , so this is basically a nested fragment, in form of a DialogFragment . You could had an Interface, and implement it on the "parent" fragment. I won't enter in much details, because it's all explained here . This is often refered as event callbacks. Props to the linked answer :)

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