I'm creating my first Android app using Java and Android Studio. I've got a main class and layout which (with the help of an adapter) displays a listview of chapter numbers. I've got a clicklistener and when a row is clicked a new activity is loaded. However, what I want to do is to capture a variable which records which row was clicked so that I can load the relevant content in the new activity. What is the best way to do this?
MainActivity:
public class MainActivity extends AppCompatActivity {
String[] nameArray = {"Chapter 1","Chapter 2","Chapter 3","Chapter 4","Chapter 5","Chapter 6", "Chapter 7", "Chapter 8", "Chapter 9", "Chapter 10", "Chapter 11", "Chapter 12", "Chapter 13", "Chapter 14", "Chapter 15", "Chapter 16", "Chapter 17", "Chapter 18", "Chapter 19", "Chapter 20", "Chapter 21" }; //List of chapters to display
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChapterlistAdapter whatever = new ChapterlistAdapter(this, nameArray);
listView = (ListView) findViewById(R.id.chapterListview);
listView.setAdapter(whatever);
// Make the row respond when clicked
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Log.d("dev","Its clicked" );
goToChapter();
}
});
}
/** Called when the user taps the Send button */
public void goToChapter() {
Intent intent = new Intent(this, CardView.class);
intent.putExtra(EXTRA_MESSAGE, "chapter clicked");
startActivity(intent);
}
ChapterlistAdapter:
public class ChapterlistAdapter extends ArrayAdapter {
//to reference the Activity
private final Activity context; //Stores which activity the list listview is on?
//to store the list of countries
private final String[] chapterArray;
public ChapterlistAdapter(Activity context, String[] nameArrayParam){
super(context,R.layout.chapter_listview_row , nameArrayParam);
this.context=context;
this.chapterArray = nameArrayParam;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.chapter_listview_row, null,true);
//this code gets references to objects in the listview_row.xml file
TextView nameTextField = (TextView) rowView.findViewById(R.id.chapterListviewRowText);
//this code sets the values of the objects to values from the arrays
nameTextField.setText(chapterArray[position]);
return rowView;
};
}
My thoughts are to pass a variable in the putExtra method - however I'm not sure how to capture that variable. Can I get it from MainActivity? Or do I have to do it in the adapter class?
The end goal is to know which chapter was clicked so that content for that chapter can be displayed.