Android Dynamic Spinner - android

private void createSpinner() {
ll.addView(s);
SQLiteDatabase db = dbs.getReadableDatabase();
String SQL = "SELECT * FROM Test where password = 'S'";
final Cursor cursor = db.rawQuery(SQL, null);
startManagingCursor(cursor);
final int l = cursor.getCount();
array_spinner = new String[l];
int i = 0;
while (cursor.moveToNext()) {
array_spinner[i]= cursor.getString(1);
i ++;
}
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, array_spinner);
s.setAdapter(adapter);
cursor.close();
ll.addView(submit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for(int i = 0; i < l; i++) {
}
}});
}
In this code i want the user to select the value in the spinner which is sent from the database. And then when the user clicks on the submit button i want that value selected to be saved to the database...i am wondering what the selected spinner option function is...is there a adapter.selected() r checked or a spinner.selected function available? hope i am explaining it correctly thanks

Its spinner.getSelectedItem().toString()

Related

Set initial value of Spinner based upon selected rows column value in SQLite table

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);

Search in Android depends on value of spinner

I created an app that shows a list of places and i created a search dialog wherein the user will type in edittext so he/she will find the desired place. First, search is working when its only place and I try to add spinner with values which are the region of the places and I got problem on the line which i will post below.
GetSearchPlace = dbhelper.getPlaceSearch(placeLocationEditText.getText().toString(),dbhelper.getPlaceSearch(placeRegion.getSelectedItem().toString()));
It says getPlaceSearch (String, string) in DatabaseHelper cannot be applied to (String)
This is my database helper
public List<PlaceModel> getPlaceSearch(String location, String region) {
List<PlaceModel> search = new ArrayList<PlaceModel>();
String selectQuery = "SELECT * FROM listing_place where province_name like '" + location + "' and region = '"+region+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
PlaceModel pm = new PlaceModel();
pm.setlisting_title(cursor.getString(cursor.getColumnIndex(KEY_PLACE)));
search.add(pm);
}
while (cursor.moveToNext());
}
cursor.close();
return search;
}
This is my main activity
final Spinner placeRegion = (Spinner) dialog.findViewById(R.id.spinnerregion);
ArrayAdapter<String> RegionAdapter = new ArrayAdapter<String>(MainActivity.this,R.layout.spinner_layout, db.getAllRegion());
RegionAdapter.setDropDownViewResource(R.layout.spinner_layout);
placeRegion.setAdapter(RegionAdapter);
placeLocationEditText = (EditText)dialog.findViewById(R.id.placelocation);
Button button = (Button) dialog.findViewById(R.id.btnplacesearch);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
PlaceListView = findViewById(R.id.placelayout);
ViewGroup parent = (ViewGroup) PlaceListView.getParent();
parent.removeView(PlaceListView);
PlaceSearchView = getLayoutInflater().inflate(R.layout.searchresult_place, parent, false);
parent.addView(PlaceSearchView);
GetSearchPlace = dbhelper.getPlaceSearch(placeLocationEditText.getText().toString(),dbhelper.getPlaceSearch(placeRegion.getSelectedItem().toString()));
lv2 = (ListView) findViewById(R.id.searchplace_list);
lv2.setAdapter(new ViewAdapterSearchPlace());
ok replace your code to below..
GetSearchPlace = dbhelper.getPlaceSearch(placeLocationEditText.getText().toString(),placeRegion.getSelectedItem().toString());

For Loop array is not working in listview in android

I want to display array items in listview but when I used simple array then it works properly and when I create array using loop it does not working. here is my code
public class MainActivity extends Activity {
String nm;
int number=0;
int ttl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv=(TextView) findViewById(R.id.textView1);
ListView listView = (ListView) findViewById(R.id.list);
//String[] values =new String[]{"val1","val2"};
ContentResolver cr=getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
ttl=cur.getCount()+1;
String[] myString = new String[ttl];
List<String> values = new ArrayList<String>();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query phone here. Covered next
nm=nm + name;
number++;
// myString[number] = "image" + number;
values.add(myString[number]);
}
}
}
String[] myString1 = new String[12];
for (int number1 = 0; number1 <= 11; number1++) {
myString1[number1] = "image1" + number1;
}
ArrayAdapter<String> adapter=new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,android.R.id.text1,values) ;
listView.setAdapter(adapter);
}
Replace this
values.add(myString[number]);
by
values.add(nm);
You are adding myString[number] to ArrayList. Where as the myString doesn't contain any elements, it is just an empty array with size ttl. If you had not initialized like String[] myString = new String[ttl] then at values.add(myString[number]) you would have got ArrayIndexOutOfBounds exception. And you don't need to use nm=nm + name, it is unnecessary.
Assuming you want to add the names into the list. If you want to add "image" + number; into the list then just uncomment that line.
Replace your code by this.
Use Array list instead of string array. It gives add method to add String in it.
ArrayList<String> ar=new ArrayList<String>();
for (int number1 = 0; number1 <= 11; number1++) {
ar.add("image1" + number1);
}

Spinner: How to set default selection in spinner from database for a particular row

I have a spinner of countries. When I am performing the update functionality I want that whatever data is saved in database should save in edittext and spinner. For spinner I am getting an error resource not found.
I have done like this for setting the default selection data from a database to spinner,
// local country is added in arraylist
ArrayList<String> arraylist_country = new ArrayList<String>();
arraylist_country.add(memberPersonalDetailsScreenActivityController.getMemberMasterData().get(0).getL_country().toString());
for(int i=0 ; i<length ; i++){
if(select_member_id == member_id[i]){
spinner_country.setSelection(arraylist_country.indexOf(local_country[i]));
}
Is there any other solution to set default selection data to spinner?
I have solved my issue. I have given my code over here.This way we can set defult selection to spinner from database for a particular row.
In onCreate-
//Declared spinner and used ArrayAdapter
spinner_country = (Spinner) findViewById(R.id.spinner_country_susa);
spinner_country.setOnItemSelectedListener(this);
country_adapter = ArrayAdapter.createFromResource(this, R.array.country_array, android.R.layout.simple_spinner_item);
country_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_country.setAdapter(country_adapter);
in edit()-
//user defined function called in onCreate()
String[] local_country = memberPersonalDetailsScreenActivityController.getMemberMasterData().get(0).getL_country();
for(int i=0 ; i<length ; i++){
if(select_member_id == member_id[i]){
spinner_country.setSelection(country_adapter.getPosition(local_country[i]));
}
}
What i do in my code is when i open the activity and its about to load the values from the spinner, i first read from the database the table i want. In my table i have set boolean values, and only 1 value from the whole table is true. Firstly i set a default value to be true. If the user wants to change it then when you open the activity and the default value comes in, set to the spinner the new value you want to save, press save or what ever you have, and change in the db table the boolean value from the default value to the new one. Also when you open the activity set the value that is true to be the value in the spinner aswell.
Hope this helps and i wasnt confusing:P
Here is my code, Maybe not the best written code but it works fine:
db.open();
Cursor c1 = db.getAllCurrencies();
currentCurrencyList = new ArrayList<String>();
if (c1.moveToFirst()) {
do {
currentCurrencyList.add(c1.getString(c1
.getColumnIndex(DBAdapter.MY_CURRENT_CURRENCY_NAMES)));
} while (c1.moveToNext());
}
db.close();
dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, currentCurrencyList);
dataAdapter1
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
currencySpinner.setAdapter(dataAdapter1);
currencySpinner.setSelection(0);
db.open();
Cursor c2 = db.getCurrentCurrency();
currentCurrencyList2 = new ArrayList<String>();
String currencySymbol = "";
if (c2.getCount() == 1) {
currencySymbol = c2.getString(c2
.getColumnIndex(DBAdapter.MY_CURRENT_CURRENCY_NAMES));
}
currentCurrency.setText(currencySymbol);
db.close();
setNewCurrencyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String spinnerSelection = "";
spinnerSelection = currencySpinner.getSelectedItem().toString();
db.open();
db.updateOldCurrency();
db.updateCurrentCurrency(spinnerSelection);
Cursor c3 = db.getCurrentCurrency();
currentCurrencyList3 = new ArrayList<String>();
String currencySymbol2 = "";
if (c3.moveToFirst()) {
do {
currentCurrencyList3.add(c3.getString(c3
.getColumnIndex(DBAdapter.MY_CURRENT_CURRENCY_NAMES)));
} while (c3.moveToNext());
for (int i = 0; i <= currentCurrencyList3.size() - 1; i++) {
currencySymbol2 = currentCurrencyList3.get(i);
}
}
currentCurrency.setText(currencySymbol2);
db.close();
}
});
dpAdapter class
public boolean updateOldCurrency() {
ContentValues args = new ContentValues();
args.put(MY_CURRENT_CURRENCY_BOOLEAN, 0);
return db.update(MY_CURRENT_CURRENCY_TABLE, args,
MY_CURRENT_CURRENCY_BOOLEAN + "='" + 1 + "'", null) > 0;
}
public boolean updateCurrentCurrency(String rowId) {
ContentValues args = new ContentValues();
args.put(MY_CURRENT_CURRENCY_BOOLEAN, 1);
return db.update(MY_CURRENT_CURRENCY_TABLE, args,
MY_CURRENT_CURRENCY_NAMES + "='" + rowId + "'", null) > 0;
}

How to see database values inside the spinner?

I have a spinner and a database so when i click the spinner i want to show the value(name) of the contacts in it but in a simple code. so they are separetated javas and xml layouts the spinner is in the (Novamensagem.java novamensagem.xml) and the contacs database is in the (Adicionarcontato.java adicionarcontato.xml) if you can specify and simply the code is better, thanks
final TextView spinnerContato = (TextView) findViewById(R.id.spinner);
String[] campos = new String[] {"nome", "telefone"};
Cursor c = db.query("contatos", campos, null, null, null, null, null);
c.moveToFirst();
String lista = "";
if(c.getCount() > 0) {
while(true) {
lista = lista + c.getString(c.getColumnIndex("nome")).toString() + "";
if(!c.moveToNext()) break;
}
spinnerContato.setText(lista);
}
thats the code but it gives the erros (more explained in comments)
//
the entire code:
ArrayList<String>() list = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.novamensagem);
db = openOrCreateDatabase("banco.db", Context.MODE_WORLD_WRITEABLE, null);
SalvaMensagem();
//Data e Hora
setCurrentDateOnView();
addListenerOnButton();
setCurrentTimeOnView();
addListenerOnButton2();
//Spinner
DadosSpinner();
}
private void DadosSpinner() {
// TODO Auto-generated method stub
final TextView spinnerContato = (TextView) findViewById(R.id.spinner);
String[] campos = new String[] {"nome", "telefone"};
list = new ArrayList<String>();
Cursor c = db.query("contatos", campos, null, null, null, null, null);
c.moveToFirst();
String lista = "";
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
if(!c.moveToNext()) break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}`
there is.
Check this
list = new ArrayList<String>();
Cursor c = db.query("contatos", campos, null, null, null, null, null);
c.moveToFirst();
String lista = "";
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
if(!c.moveToNext()) break;
}
}
This helps you to get an arrayList of items.
Next do this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Be back if you have any issues
To load the spinner data from SQLite database you have to:
Read the contacts from database and save it into the list (for example)
Create an adapter for the spinner
Method would look like this:
private void loadSpinnerData()
{
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> contacts = db.getAllContacts();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, contacts);
// 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);
}
And getAllContacts() method will return all the contacts:
public List<String> getAllConatcts(){
List<String> contacts = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
contacts.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning contatcs
return contacts;
}
For more information check this tutorial: http://www.androidhive.info/2012/06/android-populating-spinner-data-from-sqlite-database/

Categories

Resources