hi i have this spinner dropdown that displays data from my database. In my database, i have this table named area and it has this fields, aid its primary key and location which is a varchar. so far i am successful in displaying the data im my spinner. in my DBHelper this is the code that gets the data from DB
public Set<String> getAllData()
{
Set<String> set = new HashSet<String>();
String selectQuery = "SELECT * FROM " + TABLE_AREA;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
db.close();
return set;
}
then in my addLocation.java here is how i use it to display the data on my spinner
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.addplace);
Spinner spn = (Spinner)findViewById(R.id.areas);
Set<String> aset = db.getAllData();
List<String> aData = new ArrayList<>(aset);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
aData);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(spinnerAdapter);
spn.setOnItemSelectedListener(new SpinnerInfo());
}
private class SpinnerInfo implements AdapterView.OnItemSelectedListener {
private boolean isFirst = true;
String selected;
#Override
public void onItemSelected(AdapterView<?> spinner, View selectedView, int selectedIndex, long id)
{
if (isFirst)
{
isFirst = false;
}
else
{
String selection = spinner.getItemAtPosition(selectedIndex).toString();
selected = selection;
}
Toast tempMessage =
Toast.makeText(addLocation.this,
selected,
Toast.LENGTH_SHORT);
tempMessage.show();
}
#Override
public void onNothingSelected(AdapterView<?> spinner) {
// Won’t be invoked unless you programmatically remove entries
}
}
the thing is i needed to get the id of the selected location not the index in the spinner but it's database id. any idea on how i can do this? thanks so much in advance!
i needed to get the id of the selected location not the index in the
spinner but it's database id. any idea on how i can do this?
Do it as using HashMap:
1. Use HashMap instead of Set with location as a key and location id as value. change getAllData() :
public Map<String, Integer> getAllData()
{
Map<String, Integer> hashMap = new HashMap<String, Integer>();
...
if (cursor.moveToFirst()) {
do {
hashMap.put(cursor.getString(1),cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
return hashMap;
}
2. Pass all keys to Spinner :
Map<String, Integer> hashMap = db.getAllData();
List<String> allLocations = new ArrayList<String>(hashMap.keySet());
3. Now In onItemSelected use selected String to get id of Selected item:
int location_id=hashMap.get(selected);
Related
I want to Show all database contents in a List View in Android Studio, I expect to see 3 rows that each row contains "name, family and ID" , but I see a comlex of package name and some other characters as follws:
com.google.www.hmdbtest01.Person#529e71b4
com.google.www.hmdbtest01.Person#529e7238
com.google.www.hmdbtest01.Person#529e7298
if I have more rows in my database, I will see more lines like above in the output.
my codes are as follow:
public class ListOfData extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_data);
ListView list = findViewById(R.id.list1);
HmDbManager01 db= new HmDbManager01(this);
ArrayList personList = db.getAll();
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, personList);
list.setAdapter(arrayList);
}
}
db.getAll() is as follows:
public ArrayList<Person> getAll(){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM tbl_person", null);
cursor.moveToFirst();
ArrayList<Person> allData = new ArrayList<>();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Person p1 = new Person();
p1.pID=cursor.getString(0);
p1.pName=cursor.getString(1);
p1.pFamily=cursor.getString(2);
allData.add(p1);
cursor.moveToNext();
}
}
cursor.close();
sqLiteDatabase.close();
return allData;
}
and, this is Person:
package com.google.www.hmdbtest01;
public class Person {
public String pID;
public String pName;
public String pFamily;
}
Let me know your comments on this problem.
arrayListAdapter will convert your personList to list of string
change like it:
ArrayList<String> persons = new ArrayList<String>();
personList.forEach(personModel -> {
persons.add(personModel.name + " " + personModel.lastName + " " + personModel.id);
});
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, persons);
Well I have an arraylist from my sqlite data. And I'm setting this arraylist on my arrayadapter of my spinner.
Here's how I do it:
public ArrayList<AttendantModelNames> getAllAttendantNames() {
ArrayList<AttendantModelNames> attendantModelArrayList = new ArrayList<>();
hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT * FROM " + TABLE_ATTENDANTS, null);
res.moveToFirst();
while (!res.isAfterLast()) {
AttendantModelNames l_att = new AttendantModelNames();
l_att.setname(res.getString(res
.getColumnIndex(KEY_NAME)));
attendantModelArrayList.add(l_att);
res.moveToNext();
}
Log.d(TAG, attendantModelArrayList.toString());
res.close();
return attendantModelArrayList;
}
Then my AttendantModelNames POJO:
public class AttendantModelNames {
String name;
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
Then on my spinner:
private void setSpinner() {
spinner = (Spinner) findViewById(com.duka.R.id.spinner_toolbar);
ArrayList<AttendantModelNames> modelArrayList = ah.getAllAttendantNames();
ArrayAdapter<AttendantModelNames> dataAdapter =
new ArrayAdapter<AttendantModelNames>(this, android.R.layout.simple_spinner_item, modelArrayList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
int selectionPosition= dataAdapter.getPosition(modelArrayList.get(position).getname());
spinner.setSelection(selectionPosition);
I tried setting this but doesn't seem to work, says:
get(int) in arraylist cannot be applied to (java.lang.String) on
position
Any suggestions will be appreciated.
This is how i resolved my issue:
I started out by returning an list of type string:
public List<String> getAllAttendantNames() {
List<String> list = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ATTENDANTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);//selectQuery,selectedArguments
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(2));//adding 2nd column data
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
// returning lables
return list;
}
Then set up spinner:
private void loadSpinnerData() {
List<String> labels = ah.getAllAttendantNames();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, labels);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
int spinnerPosition = dataAdapter.getPosition(s_attname);
Log.d("spinner_set_selection", s_attname + spinnerPosition);
spinner.setSelection(spinnerPosition);
}
And ofcourse onCreate():
spinner = (Spinner) findViewById(R.id.spinner);
// Loading spinner data from database
loadSpinnerData();
I am new to android programming so apologies for any misuse of technical jargon. I have a spinner which has a text value of league_name and an id of id from the leagues SQLite table.
Example of leagues table design
id | league_name
-----------------
1 | Northern Premier Division
2 | Southern League 1
3 | Northern Division 2
I also have a teams table storing information on a team and a lookup table joining the id's of the teams and leagues table called teams_vs_leagues. So the selected value of this spinner gets inserted into the league_id column in the teams_vs_leagues table. I have an edit page to edit an individual teams record, which includes selecting a league from the spinner. However it always defaults to first available id in this case 1. Although, I want the initial value of the spinner to be the selected league_id in the teams_vs_leagues which corresponds to the team_id you are currently viewing. So if the selected team_id had a league_id of 3 I want the initial value of the spinner to be Northern Division 2.
UpdateTeam Class
public class UpdateTeam extends AppCompatActivity {
ArrayList < Team > imageArry = new ArrayList < Team > ();
TeamUpdateAdapter adapter;
Button updateButton;
DatabaseHelper myDb;
EditText teamNameEdit;
ImageView teamImage;
Spinner league; //Create Spinner Variables to cast in OnCreate method
ArrayList < String > leagues = new ArrayList < String > (); //Create Array List to bind to Spinner
ArrayAdapter < String > arrayAdapter; //Declare Array Adapter
long leagueId; //Declare global long for league_id
long id; //Declare global long for team_id
String picturePath = ""; //Create String variable for image path to be stored in db table
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_team);
myDb = new DatabaseHelper(this);
updateButton = (Button) findViewById(R.id.btnUpdate);
//Call Spinner Variable and cast spinner id reference
league = (Spinner) findViewById(R.id.edit_league_id);
//Call Array Adapter to Bind Array list data to Spinner
arrayAdapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, leagues);
//get selected teams values from intent
id = getIntent().getLongExtra("TEAM", 0 l);
final String editTeamName = getIntent().getStringExtra("TEAM_NAME");
picturePath = getIntent().getStringExtra("IMAGE");
leagueId = getIntent().getLongExtra("LEAGUE_ID", 01);
//Toast.makeText(getBaseContext(), "Leagueid = " + leagueId, Toast.LENGTH_LONG).show();
teamNameEdit = (EditText) findViewById(R.id.eTeamName);
teamNameEdit.setText(editTeamName, TextView.BufferType.EDITABLE);
// Reading all teams from database
final List < Team > team = myDb.getTeam((int) id);
for (Team tm: team) {
String log = "ID:" + tm.getId() + " Team Name: " + tm.getTeamName() + " ,Image: " + tm.getPath() + " ,Points: " + tm.getPoints() + " ,League Name: " + tm.getLeagueName() + " ,League ID: " + tm.getLeagueId();
// Writing teams to log
Log.d("Result: ", log);
//add teams data in arrayList
imageArry.add(tm);
}
adapter = new TeamUpdateAdapter(this, R.layout.update_team,
imageArry);
ListView dataList = (ListView) findViewById(R.id.main_list_view);
dataList.setAdapter(adapter);
//call loadSpinnerData method
loadSpinnerData();
//call updateTeam
updateTeam();
//call selectLeague
selectLeague();
}
private void loadSpinnerData() {
// Spinner Drop down elements
List < Leagues > leagueList = myDb.getAllLeagues();
// Creating adapter for spinner
ArrayAdapter < Leagues > adapter = new ArrayAdapter < Leagues > (this,
android.R.layout.simple_spinner_item, leagueList);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
league.setAdapter(adapter);
}
public void selectLeague() {
//set onItemSelected Listener for spinner
league.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView < ? > parent, View view, int position, long id) {
//get selected league id
leagueId = Integer.parseInt(String.valueOf(((Leagues) league.getSelectedItem()).getId()));
}
#Override
public void onNothingSelected(AdapterView < ? > parent) {
}
});
}
//Create addTeam method to add new team to db
public void updateTeam() {
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myDb.updateTeam(
id,
teamNameEdit.getText().toString(),
picturePath,
leagueId)) {
Toast.makeText(getBaseContext(), "Update successful.", Toast.LENGTH_LONG).show();
Intent intent =
new Intent(UpdateTeam.this, DisplayTeam.class);
startActivity(intent);
} else
Toast.makeText(getBaseContext(), "Update failed.", Toast.LENGTH_LONG).show();
}
});
}
}
Leagues Class
public class Leagues {
//Declare Global String & int
private int id;
private String leagueName;
/*********** Set Methods ******************/
public Leagues(int id, String leagueName) {
this.id = id;
this.leagueName = leagueName;
}
public void setId(int id) {
this.id = id;
}
public void setLeagueName(String leagueName) {
this.leagueName = leagueName;
}
/*********** Get Methods ****************/
public int getId() {
return this.id;
}
public String getLeagueName() {
return this.leagueName;
}
//Provides string value to display in Spinner
#Override
public String toString() {
return leagueName;
}
}
getAllLeagues method
public List < Leagues > getAllLeagues() {
List < Leagues > labels = new ArrayList < Leagues > ();
// Select All Query
String selectQuery = "SELECT * FROM " + LEAGUES_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(new Leagues(cursor.getInt(0), cursor.getString(1)));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning labels
return labels;
}
If you need any further information, do not hesitate to leave a comment. Any help would be appreciated.
Provide the selected league object to getPosition() method of the array adapter
int index = arrayAdapter.getPosition(SELECTED_LEAGUE_ID);
league.setSelection(index);
Am not familiar with android development,and i came across a situation to cascade a dropdown based on the first spinner selection.i.e.,consider for an example in 1st spinner all states data are loaded from web service using db helper class while selecting the state name in the 1st spinner i need to populate the 2nd spinner based on the 1st spinner selected item's id(stateid not that spinner's selected item id) from db which means i need to select the stateid from the selected state and want to filter the districts based on the states.
State table creation:
CREATE TABLE States( StateID INTEGER , StateName VARCHAR) District table creation: CREATE TABLE Branches(_ID INTEGER PRIMAY KEY,DistrictName VARCHAR,StateID INTEGER)
In this I have used to load data for states by using arraylist and on spinner1.setOnItemSelectedListener function loaded the district values but the values are loading as per the position of the items in the states spinner instead of that i need to filter based on the stateid in the branch table.
This is the code for getting all states:
public ArrayList<HashMap<String, String>> getStatesData() {
ArrayList aList = new ArrayList();
try {
Log.e("getStatesData", "Started");
String selectQuery = "SELECT * FROM States";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("StateID",
cursor.getString(cursor.getColumnIndex("StateID")));
map.put("StateName", cursor.getString(cursor
.getColumnIndex("StateName")));
aList.add(map);
} while (cursor.moveToNext());
}
cursor.close();
return aList;
} catch (Exception e) {
e.printStackTrace();
Log.e("getStatesData", "Ended");
return aList;
}
}
spinner1.setonitemselectedlistner event:
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapt, View v,
int pos, long id) {
// TODO Auto-generated method stub
long spinstate=spinner_state.getSelectedItemId();
branch_values=sDBController.getStateselectidData(spinstate);
branch_name_ary.clear();
for (int i = 0; i < branch_values.size(); i++) {
String name=branch_values.get(i).get("DistrictName");
String id=branch_values.get(i).get("StateID");
branch_name_ary.add(name);
Log.e("branchesbystates", branch_name_ary.toString());
}
ArrayAdapter<String> spinnerArrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, branch_name_ary);
spinnerArrayAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_district.setAdapter(spinnerArrayAdapter1);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Please suggest some solution to get the districts based on the stateid which may help to get an idea solve the issue.
Thanks in advance.
if i were you, i would create a State like so
public class State {
private String id;
private String name;
public State(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
and the getStatesDate method would be like this:
public List<State> getStatesData()
{
List<State> states = new LinkedList<State>();
try {
Log.e("getStatesData", "Started");
String selectQuery = "SELECT * FROM States";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
String stateId = cursor.getString(cursor.getColumnIndex("StateID"));
String stateName = cursor.getString(cursor.getColumnIndex("StateName"));
states.add(new State(stateId, stateName));
} while (cursor.moveToNext());
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("getStatesData", "Ended");
}
return states;
}
and the spinner1 onClicklistener will also be like this:
spinner1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
State state = (State) spinner1.getSelectedItem();
String stateId = state.getId();
String stateName = state.getName();
//you are very assured that the id matches the name selected and you can proceed from there
}
});
I hope it helps. Cheers
Best option is yo use "switch case" like this:
int spinner = 0;
String bereichlink ="";
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
int spinnerId = getView(position, v, parent).getId();
searchstring = sstr.getText().toString();
switch (parent.getId()) {
case R.id.REditText:
if (position > 0) {
spinner = position;
Link = links[position];
spinner2 = (Spinner) findViewById(R.id.sp_bereich);
adapter2 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, Constants.bereich[position - 1]);
spinner2.setAdapter(adapter2);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
new FetchFeedTask().execute((Void) null);
spinner2.setSelection(0);
}
break;
case R.id.sp_bereich:
if (position >= 0) {
bereichlink = Constants.bereich[spinner-1][position];
new FetchFeedTask().execute((Void) null);
}
bereichlink = "";
break;
}
if ((spinner > 0) && (position > 0)) {
...
}
with "Links" and "Bereich" as const enum typs arrays
i have a spinner load data to sqlite
i have field id and field name in database.
private void loadSpinnerDataHama() {
// database handler
DatabaseSpinner db = new DatabaseSpinner(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spin2.setAdapter(dataAdapter);
}
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
and the result is
USA -> value is "USA"
France -> value is "France"
when i change the code labels.add(cursor.getString(1)); to labels.add(cursor.getString(0));
and the result is
1 -> value is "1"
2 -> value is "2"
i try with int position2 = spin2.getSelectedItemPosition()+1; but the value is id/position of spinner , not the id of database.
how to display field name on spinner. but the value is id of name
Example: The spinner display:
USA -> value is "1"
France -> value is "2"
BR
Alex
It is really simple, what you can do is to implement/ represent what you need by a class, in the following manner :
Create the following class : SpinnerObject
public class SpinnerObject {
private int databaseId;
private String databaseValue;
public SpinnerObject ( int databaseId , String databaseValue ) {
this.databaseId = databaseId;
this.databaseValue = databaseValue;
}
public int getId () {
return databaseId;
}
public String getValue () {
return databaseValue;
}
#Override
public String toString () {
return databaseValue;
}
}
Using this class, you can still use the Android implementation of the ArrayAdapter (no need to implement your own, since the toString method provides the string value that you want to display, and you still store the database id that you also need).
Now you will have to create your list as follows :
public List < SpinnerObject> getAllLabels(){
List < SpinnerObject > labels = new ArrayList < SpinnerObject > ();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if ( cursor.moveToFirst () ) {
do {
labels.add ( new SpinnerObject ( cursor.getString(0) , cursor.getString(1) ) );
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning labels
return labels;
}
Now that you have the list of objects with the values and ids, you load the spinner this way :
private void loadSpinnerDataHama() {
// database handler
DatabaseSpinner db = new DatabaseSpinner(getApplicationContext());
// Spinner Drop down elements
List <SpinnerObject> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<SpinnerObject> dataAdapter = new ArrayAdapter<SpinnerObject>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spin2.setAdapter(dataAdapter);
}
And the spinner will display the values, while having their ids (from the database) too.
In order to retrieve the id of the currently selected item, you do this :
int databaseId = Integer.parseInt ( ( (SpinnerObject) spin2.getSelectedItem () ).getId () );
Please try it and let me know what happens.