I’m trying to get the position of a list view in android development. I am wanting to get the position value and save it into a pref file. The code I have is
public class Browse extends Activity {
private ListView mainListView;
private ArrayAdapter<Card> listAdapter;
public static final String userPrefs = "UserPrefs";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
mainListView = (ListView) findViewById( R.id.mainListView);
DatabaseHandler dh = new DatabaseHandler(this);
// Remember to drop existing table if it exists
dh.removeAll();
// Insert 4 Lecturers into the database
Log.d("Database: ", "Inserting values..");
dh.addCard(new Card(1, "Katniss Evergreen", "11", "33", "55", "44", R.drawable.katniss));
dh.addCard(new Card(2, "Peeta Melark", "49", "44", "11", "65", R.drawable.peeta));
dh.addCard(new Card(3, "Gale Hawthrone", "87", "32", "98", "50", R.drawable.gale));
dh.addCard(new Card(4, "Haymitch", "30", "32", "45", "31", R.drawable.haymitch));
dh.addCard(new Card(5, "Effie Trinket", "65", "54", "21", "34", R.drawable.effie));
dh.addCard(new Card(6, "President Snow", "23", "45", "67", "21", R.drawable.snow));
List<Card> list = dh.getAll();
// Create ArrayAdapter using the list of lecturers
listAdapter = new ArrayAdapter<Card>(this, R.layout.simplerow, list);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
String value = mainListView.getItemAtPosition(position).toString();
SharedPreferences sp;
sp = getSharedPreferences(userPrefs, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("name", value);
editor.commit();
}
});
}
}
This works but it saves the actual name, so if I click Katniss Evergreen it will save the name “Katniss Evergreen”. I don’t want this I want the position value so like 1 for Katniss, 2 for Peeta etc. Any one know how I can do this? I have been working all weekend on this and just can’t get my head around it 🙁 i’m fairly new to this.
Do you want get position from list or value from Card object ?
If from list than you had
positionparameter passed toonClick.Otherwise, try get
Cardobject and get value from it.