0

I have a list in an array, which is displayed in a spinner. Depending on the item selected I want to change the text in a dialog I have but setText crashes the app

    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // On selecting a spinner item
        String item = parent.getItemAtPosition(position).toString();
        switch(item) {
            case "Bárbaro":
                text_dialog.setText("Text i want to display");
                List<String>  categories2 = new ArrayList<String>();
                categories2.add("Berserker");
                categories2.add("Guerrero tótem");
                Toast.makeText(parent.getContext(), "Seleccionado: " + item, Toast.LENGTH_LONG).show();
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories2);
                // Drop down layout style - list view with radio button
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                // attaching data adapter to spinner
                spn_subclases.setAdapter(dataAdapter);
                break;

The error is as follows:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.creador_pj.AniadirPj.onItemSelected(AniadirPj.java:221) at android.widget.AdapterView.fireOnSelected(AdapterView.java:957) at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:946) at android.widget.AdapterView.access$300(AdapterView.java:55) at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:910) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Sisay
  • 681
  • 7
  • 16
  • 31
  • Please add the logs to the question – null_override May 27 '22 at 20:20
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it). `text_dialog` is null - it is probably in another XML or not initialized. If the code you posted is in a Fragment or Activity and that textview is in a dialog, you can't simply reference the view. You would have to pass the value you want to show to the dialog when you create it. – Tyler V May 27 '22 at 21:36

0 Answers0