0
I’m trying to create a spinner with dynamic values.
It’s making a mistake when I try to set the Adapter in the spinner, follows below the error and my code.
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
Click:
Sqlite sqlite = new Sqlite(getApplicationContext());
final ArrayList<Ocorrencia> arrayList = sqlite.getListaOcorrencia();
sqlite.close();
final Spinner spnocorrencia = view.findViewById(R.id.spnocorrencia);
OcorrenciaAdapter ocoAdapter = new OcorrenciaAdapter(getApplicationContext(), arrayList);
Log.i("getItem", String.valueOf(ocoAdapter.getItem(1)));
spnocorrencia.setAdapter(ocoAdapter); // erro está nessa linha
Adapter:
Context context;
ArrayList<Ocorrencia> arrayList;
public OcorrenciaAdapter(Context context, ArrayList<Ocorrencia> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
The error message says that I am trying to set a null value in Adapter, but my Adapter returns value, in "getCount()
", and also in "getItemId()
".
view.findViewById(R.id.spnocorrencia)
actually exists in theview
?– Valdeir Psr
Yes, there is. <Spinner android:layout_width="match_parent" android:layout_height="100dp" android:id="@+id/spnocorrencia" android:layout_margin="10dp" android:Theme="@style/Base.TextAppearance.Appcompat.Small" android:background="#15444947" />
– Bruno Andrade
When I give a Log. i to see the Count of the Adapter, it returns the correct amount that was to come. I don’t know if it’s a problem in the values, the way you were saved.
– Bruno Andrade
The problem is because
spnocorrencia
is void.– Valdeir Psr
the problem may be here "final Spinner spnocorrencia = view.findViewById(R.id.spnocorrencia);" ?
– Bruno Andrade
Yes. Add
if (spnocorrencia == null) { Log.w("TAG", "Variável nula"); }
afterfinal Spinner spnocorrencia…
.– Valdeir Psr
It’s really null, I just don’t know why I am. Because I created my snipper in my view, I passed the correct id, etc.
– Bruno Andrade
Define a
id
in the elementroot
of hisView
and then useLog.w("ViewId: ".concat(view.getId()))
, so you’ll make sure thatview
is the right one.– Valdeir Psr
Root element, would it be right at the beginning of my view? I’m starting now with android dev, so various doubts.
– Bruno Andrade
Yes. The first element of your XML (
LinearLayout
,FrameLayout
,ConstraintLayout
etc.)– Valdeir Psr
Friend, it worked here. In "view.findViewById(R.id.spnocorrencia)", I substitute "dialogView.findViewById(R.id.spnocorrencia)"
– Bruno Andrade
That’s it. If possible put the - as answer - the problem and which the solution. Even you can mark as solved.
– Valdeir Psr
For I had called my main view this way here "final View dialogView = Inflater.inflate(R.layout.alert_dialog_product ,null);", the variable "view", represented another view of the code emu
– Bruno Andrade
All right, thanks for your help.
– Bruno Andrade