I have a fragment in which I am trying to call a new activity on a button click.
btnLoadLimit.setOnClickListener(v -> {
Intent intent = new Intent(getActivity(), DataActivity.class);
startActivity(intent);
});
Data Activity
public class DataActivity extends AppCompatActivity {
Context mContext;
@BindView(R.id.smart_msn_spinner)
Spinner msnSpinner;
ArrayList<String> msnArrayList = new ArrayList<>(Arrays.asList("Select MSN","002998002010" )); //"002999002020"
ArrayAdapter<String> msnAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
msnAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_dropdown_item, msnArrayList);
msnSpinner.setAdapter(msnAdapter);
msnSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedMeterNo = msnArrayList.get(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
When I click on btnLoadLimit
button my app is closing with the following error
Unable to start activity ComponentInfo{com.thumbsol.accuratemobileassetsmanagament/com.thumbsol.accuratemobileassetsmanagament.fragment.DataActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at com.thumbsol.accuratemobileassetsmanagament.fragment.DataActivity.onCreate(DataActivity.java:122)
The line 122
is msnAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_dropdown_item, msnArrayList);
The same method I have applied in my fragment and it's working but in my new activity it's not.
Note: The activity is displaying if none of the methods are invoked.
Looks like you don't initialize your mContext
. meaning you're passing null to your ArrayAdapter().
You shouldn't be storing your context anyway, since your context is your activity.. You can just use this
:
msnAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, msnArrayList);
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.