behzad razzaqi
behzad razzaqi

Reputation: 93

Android listView adaptor error

I define this String Array:

String[] mCountryList = new String[200];

and fill up the variable with JSON data, and when I use that variable with an ArrayAdapter:

ArrayAdapter<String> myAdaptor = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, mCountryList);

I get this error:

java.lang.NullPointerException

I think the String array mCountryList can have null values. For example:

mCountryList[0]="x";
mCountryList[1]="x";
mCountryList[2]=null;

How can I solve this?

The stacktrace I get is:

2459-2459/com.example.behzad.behmytour E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.behzad.behmytour, PID: 2459 java.lang.NullPointerException at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394) at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362) at android.widget.AbsListView.obtainView(AbsListView.java:2263) at android.widget.ListView.makeAndAddView(ListView.java:1790) at android.widget.ListView.fillDown(ListView.java:691) at android.widget.ListView.fillFromTop(ListView.java:752) at android.widget.ListView.layoutChildren(ListView.java:1630) at android.widget.AbsListView.onLayout(AbsListView.java:2091) at android.view.View.layout(View.java:14817) at android.view.ViewGroup.layout(ViewGroup.java:4631)

Upvotes: 1

Views: 700

Answers (2)

The Original Android
The Original Android

Reputation: 6215

I think your error is in code mCountryList[2]=null; Even though this is allowed, it is not a good idea to initialize a string to null, certainly not common in Java. Only objects can be set to null.

Suggestion: mCountryList[2]= ""; Set to a blank string instead.

Upvotes: 1

ci_
ci_

Reputation: 8774

Looks like one of your items is null, like you probably thought, but didn't express easily understandable in your question. The solution is, make sure it's not.

NullPointerException at android widget ArrayAdapter createViewFromResource

You might want to use a List instead of an array, and then only populate as many items as you have instead of having a static array with 200 items, unless of course you will always have 200 items.

So use:

List<String> mCountryList = new ArrayList<String>();

instead of

String[] mCountryList=new String[200];

and then to populate it, something like this:

mCountryList.add("Your String");

Upvotes: 1

Related Questions