I am a newcomer to Android Programming. I am trying to populate a Spinner with league_names
from the leagues
table from an SQLite Database. I want to then pass the value of the id
of the selected item in the spinner to another method addTeam
that adds that value to into a column in another table. Currently I have been able to view the league_names
in the spinner but I am unsure how get the id
of the selected item. I have been able to set the items as the id value i.e 1,2,3,4
and pass that value to the addTeam
method but the user would not know which league they are selecting.
leagues Table example:
id | league_names
--------------------
1 | Division 1
2 | Division 2
3 | Premier League
4 | UK League
Below is my code:
public class add_team extends AppCompatActivity {
//Calls DatabaseHelper Class
DatabaseHelper myDb;
EditText team_name, image;
Button add_team, get_teams;
Spinner league;
ArrayList < String > leagues = new ArrayList < String > ();
ArrayAdapter < String > adapter;
int leagueIdParse = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_team);
myDb = new DatabaseHelper(this);
team_name = (EditText) findViewById(R.id.edit_team_name);
image = (EditText) findViewById(R.id.edit_image);
add_team = (Button) findViewById(R.id.insertTeams);
get_teams = (Button) findViewById(R.id.view_teams);
league = (Spinner) findViewById(R.id.edit_league_id);
adapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, leagues);
addTeam();
if (leagues == null) {
leagues = new ArrayList < String > ();
}
leagues.clear();
Cursor cursor = myDb.getAllLeagues();
while (cursor.moveToNext()) {
//Extract the data
int leagueId = cursor.getInt(0);
String leagueName = cursor.getString(1);
leagues.add(leagueName);
}
league.setAdapter(adapter);
league.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView < ? > parent, View view, int position, long id) {
try {
leagueIdParse = Integer.parseInt(parent.getItemAtPosition(position).toString());
} catch (NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}
@Override
public void onNothingSelected(AdapterView < ? > parent) {
}
});
}
public void addTeam() {
add_team.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Team team = new Team();
team.setTeamName(team_name.getText().toString());
team.setPath(image.getText().toString());
team.setLeague_id(leagueIdParse);
myDb.createTeam(team);
}
}
);
}
}
getAllLeagues method
public Cursor getAllLeagues() {
//Create SQLiteDatabase instance
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = {
ID,
LEAGUE_NAME
};
//Return query to return cursor object
return db.query(LEAGUES_TABLE, columns, null, null, null, null, null);
}