Reputation: 21
I am loading an array into a listview and when I click on the list item, I want to display the item in a textview within the same activity. The list is currently loading, but the program crashes when an item is clicked. Any thoughts why?
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class WordList extends ListActivity {
/**
* @see android.app.Activity#onCreate(Bundle)
*
*/
//public final static String TERM_EXTRA="com.myapp._word";
//public final static String DEF_EXTRA="com.myapp._pic";
TextView selection;
ArrayList<String> words=new ArrayList<String>();
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection=(TextView)findViewById(R.id.selection);
Resources res=getResources();
String[] words = res.getStringArray(R.array.words);
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,words));
}
public void onListItemClick(ListView parent, View v, int position,long id) {
selection.setText(words.get(position).toString());
}
}
Upvotes: 2
Views: 638
Reputation: 740
Because words.get(position).toString()
returns null if you did not append any object to "words" which is an ArrayList as declared this way:
ArrayList<String> words=new ArrayList<String>();
"String[] words"
is not what you are using in onListItemClick
, but "ArrayList<String> words"
is.
Edit:
Comment the arraylist, and define "String[] words" outside of onCreate.
//ArrayList<String> words=new ArrayList<String>();
String[] words;
Then in your onListItemClick;
selection.setText(words[position]);
And you are good to go.
Upvotes: 3