I have a table in the database called PrimaryData Which includes fields are PrimaryDataId and PrimaryDataCode .My problem is,When the cursor returns data from database ,Spinner does not set the values of the cursor.
xml spinner file
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="14sp"
android:textColor= "#000000"
android:spinnerMode="dialog" />
PrimaryData class in which to put PrimaryDataId and PrimaryDataCode. This class is the equivalent of a database table.
package com.example.proposaldashborad;
public class PrimeryData {
private int primeryDataId;
private String primeryDataCode;
#Override
public String toString() {
return this.primeryDataCode; // What to display in the Spinner list.
}
public int getPrimaryDataId() {
return primeryDataId;
}
public void setPrimaryDataId(int value) {
this.primeryDataId = value;
}
public int getPrimaryDataCode() {
return primeryDataId;
}
public void setPrimaryDataCode(String value) {
this.primeryDataCode = value;
}
}
this code fill Spinner
private void GetPrimaryDataForSpinner(String primaryDataName, Cursor cr) {
cr.moveToFirst();
//array_spinner = new String[cr.getCount()];
ArrayList<PrimeryData> pds = new ArrayList<PrimeryData>() ;
do {
//array_spinner[i] = cr.getString(cr.getColumnIndex("PrimeryDataCode"));
PrimeryData pd = new PrimeryData() ;
pd.setPrimaryDataId(cr.getInt(cr.getColumnIndex("PrimeryDataId")));
pd.setPrimaryDataCode(cr.getString(cr.getColumnIndex("PrimeryDataCode")));
pds.add(pd) ;
} while (cr.moveToNext());
cr.close();
if (primaryDataName == "Admin") {
adapterAdmin = new ArrayAdapter<PrimeryData>(this,R.layout.spinner, pds);
sAdmin = (Spinner) findViewById(R.id.spinnerAdmin);
sAdmin.setAdapter(adapterAdmin);
}
}
And this is my code when data is returned from the database.
private Spinner sAdmin;
private ArrayAdapter<PrimeryData> adapterAdmin;
db = new DBAdapter(getApplicationContext());
db.open();
cr = db.getViewMT26(entityID);
cr.moveToFirst();
if(cr.getCount()>0) {
PrimeryData pd = new PrimeryData();
pd.setPrimaryDataId(cr.getInt(cr.getColumnIndex("AdminId")));
pd.setPrimaryDataCode(cr.getString(cr.getColumnIndex("Admin")));
sAdmin.setSelection(adapterAdmin.getPosition(pd));
}
cr.close();
db.close();
My main question is why
adapterAdmin.getPosition (pd));
Returns -1?
You have to initialize your adapterAdmin, and set this to your spinner by setAdapter method.
Furthermore, if you only using a list of PrimeryData, then the text which is displayed on each spinner item will be PrimeryData (instance) toString().
Follow this code to set value in Spinner
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity implements OnItemSelectedListener {
Spinner spinnerOsversions;
TextView selVersion;
private String[] state = { "Cupcake", "Donut", "Eclair", "Froyo",
"Gingerbread", "HoneyComb", "IceCream Sandwich", "Jellybean",
"kitkat" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println(state.length);
selVersion = (TextView) findViewById(R.id.selVersion);
spinnerOsversions = (Spinner) findViewById(R.id.osversions);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, state);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOsversions.setAdapter(adapter_state);
spinnerOsversions.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
spinnerOsversions.setSelection(position);
String selState = (String) spinnerOsversions.getSelectedItem();
selVersion.setText("Selected Android OS:" + selState);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Related
How to get spinner selected item's text?
I have to get the text on the item selected in my spinner when i click on the save button.
i need the text not the Index.
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();
You have to use the index and the Adapter to find out the text you have
See this example of Spinner
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext()), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
Spinner returns you the integer value for the array. You have to retrieve the string value based of the index.
Spinner MySpinner = (Spinner)findViewById(R.id.spinner);
Integer indexValue = MySpinner.getSelectedItemPosition();
use this
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class dynamic_spinner_main extends Activity {
private Spinner m_myDynamicSpinner;
private EditText m_addItemText;
private ArrayAdapter<CharSequence> m_adapterForSpinner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_spinner);
///////////////////////////////////////////////////////////////
//grab our UI elements so we can manipulate them (in the case of the Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);
////////////////////////////////////////////////////////////////
//create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
m_adapterForSpinner.add("gr");
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
Intent mIntent=new Intent(dynamic_spinner_main.this,sampleLocalization.class);
mIntent.putExtra("lang", m_myDynamicSpinner.getItemIdAtPosition(position));
System.out.println("Spinner value...."+m_myDynamicSpinner.getSelectedItem().toString());
startActivity(mIntent);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
addButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
clearButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
private void addNewSpinnerItem() {
CharSequence textHolder = "" + m_addItemText.getText();
m_adapterForSpinner.add(textHolder);
}
private void clearSpinnerItems() {
m_adapterForSpinner.clear();
m_adapterForSpinner.add("dummy item");
}
}
main_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_height="wrap_content"
android:layout_margin="4px"
android:id="#+id/newSpinnerItemText"
android:layout_width="fill_parent"></EditText>
<Button android:layout_height="wrap_content"
android:id="#+id/AddBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Add To Spinner"></Button>
<Button android:layout_height="wrap_content"
android:id="#+id/ClearBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Clear Spinner Items"></Button>
<Spinner android:layout_height="wrap_content"
android:id="#+id/dynamicSpinner"
android:layout_margin="4px"
android:layout_width="fill_parent"></Spinner>
</LinearLayout>
spinner_button.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?>arg0, View view, int arg2, long arg3) {
String selected_val=spinner_button.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), selected_val ,
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
After set the spinner adapter this code will help
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "This is " +
adapterView.getItemAtPosition(i).toString(), Toast.LENGTH_LONG).show();
try {
//Your task here
}catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
One line version:
String text = ((Spinner)findViewById(R.id.spinner)).getSelectedItem().toString();
UPDATE:
You can remove casting if you use SDK 26 (or newer) to compile your project.
String text = findViewById(R.id.spinner).getSelectedItem().toString();
TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);
String subItem = textView.getText().toString();
It also can be achieved in a little safer way using String.valueOf() like so
Spinner sp = (Spinner) findViewById(R.id.sp_id);
String selectedText = String.valueOf(sp.getSelectedItem());
without crashing the app when all hell breaks loose.
The reason behind its safeness is having the capability of dealing with null objects as the argument. The documentation says
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So, some insurance there in case of having an empty Spinner for example, which the currently selected item has to be converted to String.
For spinners based on a CursorAdapter:
get the selected item id: spinner.getSelectedItemId()
fetch the item name from your database, for example:
public String getCountryName(int pId){
Cursor cur = mDb.query(TABLE, new String[]{COL_NAME}, COL_ID+"=?", new String[]{pId+""}, null, null, null);
String ret = null;
if(cur.moveToFirst()){
ret = cur.getString(0);
}
cur.close();
return ret;
}
For those have HashMap based spinner :
((HashMap)((Spinner)findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
If you are in a Fragment, an Adaptor or a Class other than main activities , use this:
((HashMap)((Spinner)YourInflatedLayoutOrView.findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
It's just for guidance; you should find your view's id before onClick method.
Spinner spinner = (Spinner) findViewById(R.id.yourspinnerid);
String text = spinner.getSelectedItem().toString();
This is my first app and i'm having some problem whit ListView
How can I get the ID in the database after clicking on a Item?
I can't use position because the Id may not be continuous and even if it is in order sometimes does not return the correct Id any.
this is my code, Thank you for your help:
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class livello1 extends AppCompatActivity {
DatabaseHelper myDb;
Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDb = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.livello1);
populateListView();
registerClick();
}
private void registerClick(){
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
i.putExtra("id", position);
//i.putExtra("id", id);
startActivity(i);
}
});
}
private void populateListView(){
Cursor res = myDb.getAllData();
String[] myItems = new String[myDb.numRow()];
int cont = 0;
if(res.getCount() == 0){
// show message
return;
}
while( res. moveToNext()){
myItems[cont] = res.getString(1);
cont ++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.da_item, myItems);
ListView list =(ListView)findViewById(R.id.listViewMain);}
There are a lot of solution approaches.
For example, you can store of Id's if ArrayList before ListView initialization.
That is, execute "SELECT id FROM mytable"
Then store in arraylist and use while click method.
Example:
//in class declaration
private ArrayList<Long> ar_ids = new ArrayList<Long>;
//
String sql = "SELECT id FROM table";
Cursor cur = db.rawQuery(sql, null);
String out = "";
ArrayList<Long> ar_ids = new ArrayList<Long>;
if (cur.moveToFirst()) {
do {
ar.add(cur.getString(0));
} while (cur.moveToNext());
}else{
}
}
cur.close();
for click event:
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
i.putExtra("id", ar_id.get(position));
//this is awsome!
startActivity(i);
}
and initialize this something like:
private void myfunc() {
String sql = "SELECT id FROM table";
Cursor cur = myDb.rawQuery(sql, null);
String out = "";
ArrayList<Long> ar_ids = new ArrayList<Long>;
if (cur.moveToFirst()) {
do {
ar.add(cur.getString(0));
} while (cur.moveToNext());
}else{
throw new NullPointerException();
}
}
cur.close();
}
private void populateListView(){
myfunc();
Cursor res = myDb.getAllData();
String[] myItems = new String[myDb.numRow()];
int cont = 0;
if(res.getCount() == 0){
// show message
return;
}
while( res. moveToNext()){
myItems[cont] = res.getString(1);
cont ++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.da_item, myItems);
ListView list =(ListView)findViewById(R.id.listViewMain);}
well instead of using the ArrayAdapter you can extend a BaseAdapter or ListAdapter or even the ArrayAdapter to make your custom adapter. First of all make a plain java class to map your database data including id to an object. Then make a custom BaseAdapter instead of using the ArrayAdapter. In your BaseAdapter class you have to override various methods including getItem and getItemId methods. Now you can return the whole mapped object from the getItem method and simply obtain the object of selected item of the ListView by using listView.getSelectedItem() method in the Activity or Fragment class. Once you get the object you can access the id easily.
You can find a good example and explanation of a custom adapter here
About mapping the database result to an object, you can get some concept here
Here, you can replace you code class with this one, I have added a cursorAdapter and attached it with your ListView, in adapter I have added a method for getting Id that I call from click listener to retrieve id from cursor, you will have to set column number for _ID in public void getId(int position) from MyCursorAdapter class below.
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class livello1 extends AppCompatActivity {
DatabaseHelper myDb;
Button next;
private MyCursorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDb = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.livello1);
populateListView();
registerClick();
}
private void registerClick(){
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
//retrieve id from cursor
int _id = adapter.getId(position)
i.putExtra("id", _id);
//i.putExtra("id", id);
startActivity(i);
}
});
}
private void populateListView(){
Cursor res = myDb.getAllData();
adapter = new MyCursorAdapter(this, res, 0);
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setAdapter(adapter);
}
//adapter for list view
class MyCursorAdapter extends CursorAdapter {
Cursor cursor;
// Default constructor
public MyCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
this.cursor = cursor;
}
public void bindView(View view, Context context, Cursor cursor) {
String text = cursor.getString(1);
//make sure the TextView id is "#+id/text1" in da_item.xml
TextView tvText = (TextView) view.findViewById(R.id.text1);
tvText.setText(text);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflator inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
return Inflater.inflate(R.layout.da_item, parent, false);
}
public int getId(int position){
cursor.moveToPosition(position);
int colId = //set id column number here
int id = cursor.getLong(colId);
return id;
}
}
Since the code is untested, you might face a build issue in start, but it should give an idea of what's going on in code. feel free to ask any question if you face any problem in compilation
I have a listview on my mainactivity that is showing items from a database. I have an add button up in the action bar. When the add button is clicked on a dialog pops up and the user fills out fields for the new item and then they click "add" and it adds the item to the database. The only problem is that the listview on the mainactivity doesn't update to show the new item. I can close the app and reopen it and I see the new item. It just doesn't update immediatly. (Same problem with deleting an item, only the delete happens onLongPress)
Mainactivity.java
package blah.blah.blah
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public class InitActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Gets the data repository in write mode
PlayersDBHelper mDbHelper = new PlayersDBHelper(getBaseContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_init);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}//End onCreate()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.init, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_add:
showAddPlayerDialog();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void showAddPlayerDialog() {
// Create an instance of the dialog fragment and show it
DialogFragment dialog = new addPlayerDialog();
dialog.show(this.getFragmentManager(), "addPlayerFragment");
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
Fragment playersFragment = new PlayersFragment();
return playersFragment;
} else if(position == 1){
Fragment otherFragment= new otherFragment();
return otherFragment;
} else {
Fragment otherFragment2 = new otherFragment2();
return otherFragment2;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}//End sectionsPagerAdapter()
public static class PlayersFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public int myFragmentId = 1;
private ListView mylistview;
private String[] values;
public ArrayAdapter<String> adapter;
public PlayersFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_players,
container, false);
mylistview = (ListView) rootView.findViewById(R.id.myListView);
registerForContextMenu(mylistview);
PlayersDBHelper mDbHelper = new PlayersDBHelper(rootView.getContext());
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
PlayerEntry._ID,
PlayerEntry.COLUMN_NAME_ID,
PlayerEntry.COLUMN_NAME_NAME,
PlayerEntry.COLUMN_NAME_POSITION
};
String selection = null; //Null will return all rows for given table
String[] selectionArgs = null; //Null should return all data
// How you want the results sorted in the resulting Cursor
String sortOrder =
PlayerEntry.COLUMN_NAME_NAME + " DESC";
Cursor c = db.query(
PlayerEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
values = new String[] {};
String array[] = new String[c.getCount()];
int i = 0;
c.moveToFirst();
while (c.isAfterLast() == false) {
array[i] = c.getString(c.getColumnIndexOrThrow(PlayerEntry.COLUMN_NAME_NAME));
i++;
c.moveToNext();
}
for(int x = 0; x < array.length ; x++){
Log.d("Logan", "Entry at:" + x + " is " + array[x]);
values = push(values, array[x]);
}
adapter = new ArrayAdapter<String>(this.getActivity(),
android.R.layout.simple_list_item_1, values);
mylistview.setAdapter(adapter);
return rootView;
}
private static String[] push(String[] array, String push) {
String[] longer = new String[array.length + 1];
for (int i = 0; i < array.length; i++)
longer[i] = array[i];
longer[array.length] = push;
return longer;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==R.id.myListView) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(values[info.position]);
String[] menuItems = {"Edit", "Delete"};
for (int i = 0; i<menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
PlayersDBHelper mDbHelper = new PlayersDBHelper(getActivity());
final SQLiteDatabase db = mDbHelper.getWritableDatabase();
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
String[] menuItems = {"Edit", "Delete"};
String menuItemName = menuItems[menuItemIndex];
String listItemName = values[info.position];
if(menuItemName.equalsIgnoreCase("Edit")) {
} else {
//menuItemName === Delete
// Define 'where' part of query.
String selection = PlayerEntry.COLUMN_NAME_NAME + " =? ";
// Specify arguments in placeholder order.
String[] selectionArgs = { listItemName };
// Issue SQL statement.
db.delete(PlayerEntry.TABLE_NAME, selection, selectionArgs);
adapter.notifyDataSetChanged();
}
return true;
}
}
public static class otherFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public otherFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lineup,
container, false);
return rootView;
}
}
public static class otherFragment2 extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public otherFragment2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_position,
container, false);
return rootView;
}
}
}
addPlayerDialog.java
package blah.blah.blah;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
public class addPlayerDialog extends DialogFragment{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Gets the data repository in write mode
PlayersDBHelper mDbHelper = new PlayersDBHelper(getActivity().getBaseContext());
final SQLiteDatabase db = mDbHelper.getWritableDatabase();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
final View view = inflater.inflate(R.layout.addplayerdialog, null);
final ListView list = (ListView)view.findViewById(R.id.myListView);
builder.setView(view)
// Add action buttons
.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
EditText fName = (EditText) view.findViewById(R.id.editFirstName);
Editable firstName = fName.getText();
EditText lName = (EditText) view.findViewById(R.id.editLastName);
Editable lastName = lName.getText();
EditText number = (EditText) view.findViewById(R.id.playerNumber);
int num = Integer.parseInt(number.getText().toString());
Spinner spinner = (Spinner) view.findViewById(R.id.positionSpinner);
String position = spinner.getSelectedItem().toString();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(PlayerEntry.COLUMN_NAME_ID, num);
values.put(PlayerEntry.COLUMN_NAME_NAME, firstName + " " + lastName);
values.put(PlayerEntry.COLUMN_NAME_POSITION, position);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
PlayerEntry.TABLE_NAME,
null,
values);
//**** HERE IS WHERE I THINK THE CHANGE NEEDS TO BE! ****
((ArrayAdapter) list.getAdapter()).notifyDataSetChanged();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
Spinner spinner = (Spinner) view.findViewById(R.id.positionSpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.positions, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
return builder.create();
}
}
addPlayerDialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editFirstName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/fName" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/lName" />
<EditText
android:id="#+id/playerNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/playerNumberHint"
android:inputType="number" />
<Spinner
android:id="#+id/positionSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
I think you inserted the data to the DB but forgot to call yourListViewAdapter.add method before calling notifyDataSetChanged
I have implement Drag-Sort ListView(DSLV) and LazyList together in my Project, I download the Demo LazyList and Drag-Sort ListView from github then integrate and modify as per my requirement ,
I use DSLV for drag and sort the items of ListView and LazyList for Displaying Image from URL,
i just implement "Basic usage playground" from DSLV for drag and sort,
I have implement search in TestBedDSLV.java, but the problem is that when I search the Content from the list, but i can't update the list, i have tried notifyDataSetChanged method but it not works, generally we create new adapter and pass it to listview like lv.setAdapter(adapter) , but here they just set ListAdapter, so we cant do lv.setAdapter(adapter)
TestBedDSLV.java
package com.mobeta.android.demodslv;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.Button;
import android.widget.EditText;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
public class TestBedDSLV extends FragmentActivity {
private int mNumHeaders = 0;
private int mNumFooters = 0;
private int mDragStartMode = DragSortController.ON_DOWN;
private boolean mRemoveEnabled = false;
private int mRemoveMode = DragSortController.FLING_RIGHT_REMOVE;
private boolean mSortEnabled = true;
private boolean mDragEnabled = true;
private String mTag = "dslvTag";
Button search;
EditText search_customer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_bed_main);
search = (Button) findViewById(R.id.btn_search);
search_customer = (EditText) findViewById(R.id.search_product);
search_customer.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// here is logic for refresh the list View
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.test_bed, getNewDslvFragment(), mTag).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mode_menu, menu);
return true;
}
private Fragment getNewDslvFragment() {
DSLVFragmentClicks f = DSLVFragmentClicks.newInstance(mNumHeaders,
mNumFooters);
f.removeMode = mRemoveMode;
f.removeEnabled = mRemoveEnabled;
f.dragStartMode = mDragStartMode;
f.sortEnabled = mSortEnabled;
f.dragEnabled = mDragEnabled;
return f;
}
}
DSLVFragmentClicks.java
package com.mobeta.android.demodslv;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.os.Bundle;
import android.widget.Toast;
public class DSLVFragmentClicks extends DSLVFragment {
public static DSLVFragmentClicks newInstance(int headers, int footers) {
DSLVFragmentClicks f = new DSLVFragmentClicks();
Bundle args = new Bundle();
args.putInt("headers", headers);
args.putInt("footers", footers);
f.setArguments(args);
return f;
}
AdapterView.OnItemLongClickListener mLongClickListener =
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String message = String.format("Long-clicked item %d", arg2);
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
return true;
}
};
#Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String message = String.format("Clicked item %d", arg2);
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String message = String.format("Long-clicked item %d", arg2);
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
DSLVFragment.java
package com.mobeta.android.demodslv;
import java.util.ArrayList;
import java.util.Arrays;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
public class DSLVFragment extends ListFragment {
ArrayAdapter<String> adapter;
private String[] array;
public static ArrayList<String> list;
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener() {
#Override
public void drop(int from, int to) {
if (from != to) {
String item = adapter.getItem(from);
adapter.remove(item);
adapter.insert(item, to);
}
}
};
private DragSortListView.RemoveListener onRemove = new DragSortListView.RemoveListener() {
#Override
public void remove(int which) {
adapter.remove(adapter.getItem(which));
}
};
protected int getLayout() {
return R.layout.dslv_fragment_main;
}
/**
* Return list item layout resource passed to the ArrayAdapter.
*/
protected int getItemLayout() {
return R.layout.list_item_handle_right;
}
private DragSortListView mDslv;
private DragSortController mController;
public int dragStartMode = DragSortController.ON_DOWN;
public boolean removeEnabled = false;
public int removeMode = DragSortController.FLING_RIGHT_REMOVE;
public boolean sortEnabled = true;
public boolean dragEnabled = true;
public static DSLVFragment newInstance(int headers, int footers) {
DSLVFragment f = new DSLVFragment();
Bundle args = new Bundle();
args.putInt("headers", headers);
args.putInt("footers", footers);
f.setArguments(args);
return f;
}
public DragSortController getController() {
return mController;
}
/**
* Called from DSLVFragment.onActivityCreated(). Override to set a different
* adapter.
*/
public void setListAdapter() {
array = getResources().getStringArray(R.array.jazz_artist_names);
list = new ArrayList<String>(Arrays.asList(array));
adapter = new ArrayAdapter<String>(getActivity(), getItemLayout(),
R.id.text, list);
setListAdapter(adapter);
}
/**
* Called in onCreateView. Override this to provide a custom
* DragSortController.
*/
public DragSortController buildController(DragSortListView dslv) {
DragSortController controller = new DragSortController(dslv);
controller.setDragHandleId(R.id.drag_handle);
controller.setClickRemoveId(R.id.click_remove);
controller.setRemoveEnabled(removeEnabled);
controller.setSortEnabled(sortEnabled);
controller.setDragInitMode(dragStartMode);
controller.setRemoveMode(removeMode);
return controller;
}
/** Called when the activity is first created. */
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDslv = (DragSortListView) inflater.inflate(getLayout(), container,
false);
mController = buildController(mDslv);
mDslv.setFloatViewManager(mController);
mDslv.setOnTouchListener(mController);
mDslv.setDragEnabled(dragEnabled);
return mDslv;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mDslv = (DragSortListView) getListView();
mDslv.setDropListener(onDrop);
mDslv.setRemoveListener(onRemove);
Bundle args = getArguments();
int headers = 0;
int footers = 0;
if (args != null) {
headers = args.getInt("headers", 0);
footers = args.getInt("footers", 0);
}
setListAdapter();
}
}
test_bed_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/search_lay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="horizontal" >
<EditText
android:id="#+id/search_product"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp"
android:layout_weight="1"
android:background="#drawable/search_back"
android:hint="Enter Firstname"
android:imeOptions="actionSearch"
android:inputType="text"
android:paddingBottom="2dp"
android:paddingLeft="5dp"
android:paddingTop="2dp"
android:visibility="visible" />
<Button
android:id="#+id/btn_search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_weight="2.5"
android:text="CANCEL"
android:textColor="#155280"
android:textSize="14sp"
android:textStyle="bold"
android:visibility="visible" />
</LinearLayout>
<FrameLayout
android:id="#+id/test_bed"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<!-- We will add the DSLVFragment inside the FrameLayout in code -->
</LinearLayout>
and other require class can be download from github link that i given above.....
Actually if you see your code closly there's a method that you have mention
public void setListAdapter() {
array = getResources().getStringArray(R.array.jazz_artist_names);
list = new ArrayList<String>(Arrays.asList(array));
adapter = new ArrayAdapter<String>(getActivity(), getItemLayout(),
R.id.text, list);
setListAdapter(adapter);
}
So as you said :
"generally we create new adapter and pass it to listview like lv.setAdapter(adapter) , but here they just set ListAdapter, so we cant do lv.setAdapter(adapter)"
Can't you easily do this by easily generating an array based on your search and set it like the code ??
list = new ArrayList<String>(Arrays.asList(array));
adapter = new ArrayAdapter<String>(getActivity(), getItemLayout(),
R.id.text, list);
setListAdapter(adapter);
EDIT: I think you are asking the wrong question. Your main concern should be how to communicate between activity and fragments...since your search functionality is in activity and list is in fragment. So you need to setup an interface that basically passes on the search string to your fragment and there you can make an array and set it the same way you are doing right now.
Read this SO question and answer. In the answer you'll find one similar approach on passing data between activity and fragment.
Edit 2: Your main concern is to communicate from activity to fragment for this..declare an interface in your activity like this:
public interface FragmentCommunicator{
public void passDataToFragment(String someValue);
}
then call the interface at your text change listener..for example
FragmentCommunicator mfragmentCommunicator;
//your onCreate function
{
//your textchangelistenr
{
onTextChanged call
if(mfragmentCommunicator != null)
mfragmentCommunicator.passDataToFragment(Pass your string here)
}
then make your fragement implement this interface like
public class someFragment extends Fragment implements FragmentCommunicator
{
//this is your rest of the fragment
#Override
public void passDataToFragment(String somevalue)
{
//This function will get fired each time your text is changed since in your activity you are calling this same function in your textchange listener. the String somevalue will be the string that you passed from your activity
}
//rest of the code
.
.
.
//Don't forget to initialize your interface in fragment itself. Do this in your onAttach
like this
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
context = getActivity();
((MainActivity)context).fragmentCommunicator = this;
}
}
}
You can refer this link for any further clarifications. Check only the implementation of FragmentCommunicator
If you are using array as the base arraylist for adapter, just update this array and call adapater.notifyDataSetChanged(). This will update DSLV for sure as I have used same approach in one of my project.
How to get spinner selected item's text?
I have to get the text on the item selected in my spinner when i click on the save button.
i need the text not the Index.
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();
You have to use the index and the Adapter to find out the text you have
See this example of Spinner
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext()), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
Spinner returns you the integer value for the array. You have to retrieve the string value based of the index.
Spinner MySpinner = (Spinner)findViewById(R.id.spinner);
Integer indexValue = MySpinner.getSelectedItemPosition();
use this
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class dynamic_spinner_main extends Activity {
private Spinner m_myDynamicSpinner;
private EditText m_addItemText;
private ArrayAdapter<CharSequence> m_adapterForSpinner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_spinner);
///////////////////////////////////////////////////////////////
//grab our UI elements so we can manipulate them (in the case of the Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);
////////////////////////////////////////////////////////////////
//create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
m_adapterForSpinner.add("gr");
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
Intent mIntent=new Intent(dynamic_spinner_main.this,sampleLocalization.class);
mIntent.putExtra("lang", m_myDynamicSpinner.getItemIdAtPosition(position));
System.out.println("Spinner value...."+m_myDynamicSpinner.getSelectedItem().toString());
startActivity(mIntent);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
addButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
clearButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
private void addNewSpinnerItem() {
CharSequence textHolder = "" + m_addItemText.getText();
m_adapterForSpinner.add(textHolder);
}
private void clearSpinnerItems() {
m_adapterForSpinner.clear();
m_adapterForSpinner.add("dummy item");
}
}
main_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_height="wrap_content"
android:layout_margin="4px"
android:id="#+id/newSpinnerItemText"
android:layout_width="fill_parent"></EditText>
<Button android:layout_height="wrap_content"
android:id="#+id/AddBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Add To Spinner"></Button>
<Button android:layout_height="wrap_content"
android:id="#+id/ClearBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Clear Spinner Items"></Button>
<Spinner android:layout_height="wrap_content"
android:id="#+id/dynamicSpinner"
android:layout_margin="4px"
android:layout_width="fill_parent"></Spinner>
</LinearLayout>
spinner_button.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?>arg0, View view, int arg2, long arg3) {
String selected_val=spinner_button.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), selected_val ,
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
After set the spinner adapter this code will help
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "This is " +
adapterView.getItemAtPosition(i).toString(), Toast.LENGTH_LONG).show();
try {
//Your task here
}catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
One line version:
String text = ((Spinner)findViewById(R.id.spinner)).getSelectedItem().toString();
UPDATE:
You can remove casting if you use SDK 26 (or newer) to compile your project.
String text = findViewById(R.id.spinner).getSelectedItem().toString();
TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);
String subItem = textView.getText().toString();
It also can be achieved in a little safer way using String.valueOf() like so
Spinner sp = (Spinner) findViewById(R.id.sp_id);
String selectedText = String.valueOf(sp.getSelectedItem());
without crashing the app when all hell breaks loose.
The reason behind its safeness is having the capability of dealing with null objects as the argument. The documentation says
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So, some insurance there in case of having an empty Spinner for example, which the currently selected item has to be converted to String.
For spinners based on a CursorAdapter:
get the selected item id: spinner.getSelectedItemId()
fetch the item name from your database, for example:
public String getCountryName(int pId){
Cursor cur = mDb.query(TABLE, new String[]{COL_NAME}, COL_ID+"=?", new String[]{pId+""}, null, null, null);
String ret = null;
if(cur.moveToFirst()){
ret = cur.getString(0);
}
cur.close();
return ret;
}
For those have HashMap based spinner :
((HashMap)((Spinner)findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
If you are in a Fragment, an Adaptor or a Class other than main activities , use this:
((HashMap)((Spinner)YourInflatedLayoutOrView.findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
It's just for guidance; you should find your view's id before onClick method.
Spinner spinner = (Spinner) findViewById(R.id.yourspinnerid);
String text = spinner.getSelectedItem().toString();