1

So I have this code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.favourites);
    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    SharedPreferences prefs = getSharedPreferences("myFavs", 0);
    Map<String, String> m = (Map<String, String>) prefs.getAll();
    List<String> list = new ArrayList<>(m.values());

    ListView listView = (ListView) findViewById(R.id.favsList);
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this,R.layout.listlayout, android.R.id.text1, list );
    listView.setAdapter(adapter);

And it outputs this error in logcat:

10-08 08:48:44.114  19390-19390/com.example.me1jmo.insult_generator E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.me1jmo.insult_generator, PID: 19390
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:399)
        at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
        at android.widget.AbsListView.obtainView(AbsListView.java:2346)
        at android.widget.ListView.measureHeightOfChildren(ListView.java:1280)
        at android.widget.ListView.onMeasure(ListView.java:1188)
        at android.view.View.measure(View.java:18788)
        ...

I have read the articles on why this happens but I can't figure out what bit of my code I need to change to get it working.

James
  • 129
  • 4
  • 18

3 Answers3

4

The issue is coming because you are referring the Textview which is not in your specified layout.

android.R.id.text1 

is a Textview of Android OS classes which is inbuilt in OS.

You need to use the id of the Textview which you have specified in the

R.layout.listlayout

Change that and your error will be resolved.

0

Try changing android.R.id.text1 to R.id.text1. Also, check if your listlayout has a TextView with id text1.

Raghu Teja
  • 235
  • 1
  • 11
0

Replace this

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,R.layout.listlayout, android.R.id.text1, list ); 

With this

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, android.R.id.text1, list );
cafebabe1991
  • 4,928
  • 2
  • 34
  • 42