"What eh"/"how to resolve" a "null Object Reference" error? What appears on the console?

Asked

Viewed 3,178 times

0

When I try to use the code below, (what alias I managed to get with help from friends of the OS) an error appears on the line:
spinner.setOnItemSelectedListener(this);
With the following console code:

java.lang.Runtimeexception:
Unable to start Activity Componentinfo{ jp.co.e_grid.rakuseki/jp.co.e_grid.rakuseki.Postconfirmationactivity
}:

java.lang.Nullpointerexception:
Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null Object Reference



Here is my code:

public class JSONOAsyncTask extends AsyncTask<String, Void, Boolean> implements  AdapterView.OnItemSelectedListener{

    private Spinner spinner;
    private ArrayAdapter<String> dataAdapter;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Spinner spinner = (Spinner) findViewById( R.id.memo_confirmation_spinner );
        spinner.setOnItemSelectedListener(this);
    }

        @Override
        protected Boolean doInBackground(String... urls) {

            try {
                Log.e("****** MESSAGE ******", " Json Object  = " + JSONParser.getJSONFromUrl( URL ).get("ReportDetailTextList"));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            // TEST: Temporaly list
            List<String> categories = new ArrayList<String>();
            categories.add("aaa");
            categories.add("bbb");
            categories.add("ccc");
            categories.add("ddd");
            categories.add("eee");

            // Adapter Creation

            // ArrayAdapter adapter = ArrayAdapter.createFromResource(getBaseContext(), R.array.confirmation_memo, android.R.layout.simple_spinner_item);
            // adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            dataAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, categories);
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            return false;
        }

    protected void onPostExecute(Boolean result) {
        // putting adapter in to data
        spinner.setAdapter(dataAdapter);

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}



Important detail:
When I call the same "spinner" from within the Oncreate() with that same ID, everything works fine, see code snippet:

Spinner spinner = (Spinner) findViewById(R.id.memo_confirmation_spinner);
spinner.setOnItemSelectedListener(this);

ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.confirmation_memo, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.


I have read other posts about "null Object Reference" in the SO but it seems to me that there are many variations of the same error, so here is my question: What this error message refers to and, how to resolve it?

  • Look, some object you’re calling isn’t being initialized, now just figure it out. The correct would be you "Debug" until you find the object that fires the exception.

  • when you speak thresh, would put "stop in code" points and I would follow step-by-step?

  • 1

    Um... I don’t know much about Java, but when you call the snippet "spinner.setOnItemSelectedListener(this)" maybe the spinner object is null, hence it implies that the above call "(Spinner spinner = (Spinner) findViewById( R.id.memo_confirmation_spinner );" did not find the object by Id (if that’s what the function does)

  • 1

    Yes, Camila. It’s a good start, at least you can see the state of your object and when it will trigger the error.

  • yes!! debugged! (thanks for the tip! ) D The spinner really comes "null", but the same code, inside the "onCreate" works smoothly! what can it be? about it not being able to "open" the spinner? be inside a Asynctask?? (I’ve even corrected the question!)

  • I think it’s unlikely because it’s an asynchronous call. You have to see first if the Id really is the same, it may be going as 0 or null within the preOnExecute, so it does not find an object.

  • got @Wilsonsantos, but it turns out that in Androidstudio, it is not possible to put a wrong id, it already accuses the error at the time you type, and I also confirmed calmly if it is written right, not to mention that I re-wrote the code inside onCreate() to test, and then it works! with the same id , inclusive...

Show 2 more comments

1 answer

3


Briefly the exception Nullpointerexception is launched whenever you try to access a memory object that has not been instantiated, or better initialized, until the moment of your call.

First factor to be noted, is that you are declaring two variables of the type Spinner, globally in its Inner class and inside onPreExecute(). Declare only once so that no error occurs. See how your method would look onPreExecute():

@Override
protected void onPreExecute() {
    super.onPreExecute();
    spinner = (Spinner) findViewById(R.id.memo_confirmation_spinner );
    spinner.setOnItemSelectedListener(this);
}

Second factor is that as you are saying that the error is in this line below:

spinner = (Spinner) findViewById( R.id.memo_confirmation_spinner );

Try to observe in your out class if you’re not calling your JSONOAsyncTask before the setContentView(). If so, just reverse doing so:

setContentView(R.layout.sua_activity);
new JSONOAsyncTask.execute();
  • Interesting! I need to study this more how to declare the variables, Well I have tested but unfortunately, appears the same error... identical... (to ensure that no more errors would appear, I commented the part of the spinner that is inside the "onCreate")

  • I came back! and opened another post! if you have a little time I would love to know your tip/ idea in that problem, por la gave me ideas. well... different! http://answall.com/questions/181026/como-fazer-um-array-criado-dentro-de-um-asynctask-ser-global/181067#181067

Browser other questions tagged

You are not signed in. Login or sign up in order to post.