-1
@Override
protected void onCreate(Bundle savedInstanceState) {    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    NoteTaking_Activity noteTaking_activity = new NoteTaking_Activity();

    arrayList = noteTaking_activity.getHeadlineArray();

    ListView listView = (ListView) findViewById(R.id.List_Of_notes);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, arrayList );

    listView.setAdapter( adapter );

Executing the code shown above results in the error message

Attempt to invoke interface method 'int java.util.List.size()' on a null object reference.

The array list is empty at first, but then users may fill it.

What can I do to resolve this error?

Seth
  • 1,545
  • 1
  • 16
  • 30
Hossein
  • 37
  • 6

1 Answers1

0

Here is the code:

    @Override
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        NoteTaking_Activity noteTaking_activity = new NoteTaking_Activity();

        arrayList = noteTaking_activity.getHeadlineArray();

        ListView listView = (ListView) findViewById(R.id.List_Of_notes);
if(arrayList!=null){
        ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, arrayList );

        listView.setAdapter( adapter );
}
Sunny
  • 3,134
  • 1
  • 17
  • 31
  • Would work if OP was using a custom adapter, but a default [`ArrayAdapter`](https://developer.android.com/reference/android/widget/ArrayAdapter) is being used in this case. – Michael Dodd Sep 26 '18 at 12:53
  • if its' default adapter then you can add `arrayList!=null` and show the error message `No data found`. – Sunny Sep 26 '18 at 13:01
  • when I do that, the app will no more crash, but it won't carry out reading other statements in the onCreate method. – Hossein Sep 26 '18 at 13:07
  • I have updated the answer, check it. – Sunny Sep 26 '18 at 13:19
  • @Hossein If it resolves your issue can you please accept the answer... – Sunny Sep 26 '18 at 13:25