0

I'm using string array which I'm passing to ArrayAdapter for spinner item. my array size(usually less than 10) and values are variable (I'm taking it from asset file)

if I'm using this :

String[] arr = new String[10];
protected void onCreate(Bundle savedInstanceState) {
        breader = new BufferedReader(new InputStreamReader(getAssets().open(path)));
        int length = Integer.parseInt(breader.readLine());
        for(int i=0; i<length; i++){
            arr[i]=breader.readLine();

        initialize();
....
}

initialize(){    
    spinner1 = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<String> array = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, arr);
    spinner1.setAdapter(array);
}

it shows NullPointerException at spinner1.setAdapter(array); line. can I reassign array length. I think its not possible.

4
  • 1
    Can you show your logcat? Commented Jul 29, 2014 at 12:30
  • 1
    instead of Activity.this use YourActivity.this like MainActivity.this and its better to use ArrayLis<String> instead String[], because you don't know exactly what is the size of your list Commented Jul 29, 2014 at 12:30
  • ArrayAdapter will accept ArrayList<String>? Commented Jul 29, 2014 at 12:40
  • yes ArrayAdapter Accept it. Commented Jul 29, 2014 at 12:40

1 Answer 1

2

because of you add null when no data in last portion of array. I mean there are 7 data in assest file and you move for loop 10 times so after 7 data Add there are null represent. so breader.readLine(); read null and add it to your string array and when you parse StringArray to Array Adapter there are null get on 8th position of array and nullpointer Exception fire.

So just check breader.readLine() != Null then add it to String of Array otherwise add some Temp text.

Or

You Also Use ArrayList instead of String[] Array. ArrayList is dynamically Arraylist you can add data to list useing array.add(yourdata).

Thats it...

Sign up to request clarification or add additional context in comments.

4 Comments

will ArratAdapter Accept ArrayList?
sorry it is not accepting ArrayList<String>. same error occurred.
have you change Activity.this to yourActivityname.this? in arrayAdapter.
sorry it was my mistake of initializing before the setContentView. Thanks for help. Thank you again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.