[:en]Android: many ListViews per app -> Solved “NPE” exception error for listview adapter[:]

[:en]Error: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.ArrayAdapter.add(java.lang.Object)’ on a null object reference

manyLv

Step 1: activity_student.xml


            
 


Step 2: student.java


package com.inventlinks.estaff;

import android.app.ListActivity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;


public class student  extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // **** Don't set the Wrong layout; else, get NPE **************
        setContentView(R.layout.activity_student);

        ListView listView = (ListView)findViewById(R.id.studentlistView);

        String[] cars = {"Honda","Toyota", "Mercedes","Joe"};
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, cars  );
        listView.setAdapter(adapter);
    }
}

[:]

Print Friendly, PDF & Email
Scroll to Top