I have a spinner in my code and I want to get position of element in the array when selected. Here is my code which is running perfectly. In selection I am storing the string value of element but I also want the position count of element
public class MainActivity extends Activity implements OnItemSelectedListener {
final Context context = this;
private Button button;
private String selection;
private String[] states = new String[]{
"Gujrat","Jammu and Kashmir","Kerala","Karnataka","Lakshadweep","Maharashtra","Manipur","Mizoram",
"Nagaland","New Delhi","Rajasthan","Tami Nadu","West Bengal"
};
ArrayList<String> categoryList = new ArrayList<String>();
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH)+1;
//make it fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//fix portrait orientation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
ImageView img = (ImageView)findViewById(R.id.imageView1);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.menu);
Button dialogButton = (Button) dialog.findViewById(R.id.btncross);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
Spinner spin = (Spinner)dialog.findViewById(R.id.spinState);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, states);
adapter_state.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter_state);
spin.setOnItemSelectedListener(MainActivity.this);
}
});
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView tv = (TextView)arg1;
selection = tv.getText().toString();
Log.v(TAG, "index=" + selection);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
In the code:
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView tv = (TextView)arg1;
selection = tv.getText().toString();
Log.v(TAG, "index=" + selection);
}
arg2 is the position of spinner
int arg2 of `onItemSelected()` is the position of selected items.
So you can use it like
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
selection = states[arg2];
Log.v(TAG, "index=" + arg2);
Log.v(TAG, "selction=" + selection);
}
spin.getSelectedItemPosition();
Here in your setOnItemSelectedListener(new OnItemSelectedListener()
public abstract void onItemSelected (AdapterView<?> parent, View view, int position, long id)
Parameters
parent The AdapterView where the selection happened
view The view within the AdapterView that was clicked
position The position of the view in the adapter
id The row id of the item that is selected
int arg2 to get Selected Item Id
Update only this method,
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Log.v(TAG, "index=" + spin.getItemIdAtPosition(int2));
}
Related
I was looking to filter a listView by an editText.
My ListView is populate by an ArrayString, and when I filter it everything goes right. But I have a problem to recognize the element clicked. When I filter the listView and I click on the item filtered I want to have the number of the row in the original arrayString in order to make an Intent. Whit my code when I click the item in the filtered arrayString the row is 0 and it's not correct. If I search "Anche Se Pesa" I want to return the row 2 like the position in the original ArrayString.
<string-array name="titoli">
<item>An Val Dondona</item>
<item>Anche Mio Padre</item>
<item>Anche Se Pesa</item>
<item>Andremo In Francia</item>
<item>Aprite Le Porte</item>
<item>Arda Berghem</item>
<item>Ascoltate Amici Cari</item>
<item>Ave, O Vergine</item>
<item>Aver na Figlia Sola Soletta</item>
<item>Ancora sti quatro</item>
<item>Andouma Prou</item>
</string-array>
Here Is the code
public class activity_titoli extends AppCompatActivity {
Button btt_backHome;
ListView lV_titoli;
EditText eT_search;
private ArrayAdapter<CharSequence> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_titoli);
btt_backHome = (Button) findViewById(R.id.btt_backHome);
lV_titoli = (ListView) findViewById(R.id.lV_titoli);
eT_search = (EditText) findViewById(R.id.eT_search);
adapter = ArrayAdapter.createFromResource(this, R.array.titoli, android.R.layout.simple_list_item_1);
lV_titoli.setAdapter(adapter);
final Intent to_Home = new Intent (this , Activity_Main.class);
eT_search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
(activity_titoli.this).adapter.getFilter().filter(arg0);
}
});
btt_backHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(to_Home);
}
});
lV_titoli.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("Element: " , Integer.toString(i));
}
});
}
}
Try this code :
lV_titoli.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Resources res = getResources();
List<CharSequence> list = Arrays.asList(res.getStringArray(R.array.titoli));
Log.e("Element: " , Integer.toString(list.indexOf(adapter.filgetItem(i))));
}
});
Hope this helps
public class AddCourse extends Activity implements OnClickListener {
private Spinner addCourse;
String addedcoursevalue;
TextView AddcourseButton;
StringBuffer sb;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addcourse);
addCourse = (Spinner) findViewById(R.id.spinner1);
AddcourseButton = (TextView) findViewById(R.id.AddcourseButton);
AddcourseButton.setOnClickListener(this);
final String[] coursearray = getResources().getStringArray(
R.array.Course_arrays);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
R.layout.spinner_item, coursearray);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
addCourse.setAdapter(dataAdapter);
addCourse.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
addedcoursevalue = addCourse.getSelectedItem().toString();
sb = new StringBuffer();
sb.append(addedcoursevalue);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(AddCourse.this, sb, 1000).show();
}
}
This is my code i am able to display value in spinner i want what ever i selected that should store in buffer that i want to Print on Button click in toast please check where am doing mistake please help
i want what ever i selected that should store in buffer that i want to
Print on Button click
No need to store Spinner selected value in Buffer inside onItemSelected method. you can directly access selected value in onClick method by calling addCourse.getSelectedItem() :
sb = new StringBuffer();
addCourse.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
addedcoursevalue = addCourse.getSelectedItem().toString();
sb.append(addedcoursevalue);
}
I am new to Android programming and I have a ListView when filtered always return me the first item in the list, so how do I fix this?
For instance, my list contains A.A, A.B, A.C, B.C, B.D.
When I want to search the list for things starting with B, I will get B.C, B.D but when I click B.C, it returns me A.A and B.D, it returns me A.B
public class PatientList extends Activity{
PatientDB patientDB;
Context myContext;
ListView lv_patients;
EditText et_patients;
ArrayAdapter<String> adapter;
ArrayList<HashMap<String, String>> patientList;
static String value;
String[] patientarray = new String[]{"initials"};
ArrayList<String> patientArrayList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_list);
myContext = this;
patientDB = new PatientDB(myContext);
patientDB.open();
Cursor patientCursor;
patientCursor = patientDB.retrieveAllEntriesCursor();
if(patientCursor!=null && patientCursor.getCount()>0)
{
String patientInitials;
patientCursor.moveToFirst();
do
{
patientCursor.getString(patientDB.COLUMN_KEY_ID); // + " " +
patientInitials = patientCursor.getString(patientDB.COLUMN_INITIALS_ID);
Log.i("FromCursor", patientInitials);
patientArrayList.add(patientInitials);
} while (patientCursor.moveToNext());
}
lv_patients = (ListView) findViewById(R.id.lv_patients);
et_patients = (EditText) findViewById(R.id.et_patients);
lv_patients.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String a = patientArrayList.get(position);
Toast.makeText(PatientList.this, a + " selected", Toast.LENGTH_SHORT).show();
Intent returnIntent = new Intent(PatientList.this, PatientInfo.class);
returnIntent.putExtra("value", a);
setResult(RESULT_OK, returnIntent);
finish();
}
});
//Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_patients, R.id.patient_name, patientArrayList);
lv_patients.setAdapter(adapter);
//Enabling search filter
et_patients.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
PatientList.this.adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
}
Because you filter your adapter to have B.C in position 0 and B.D in position 1. But in your implementation of your onClickListener, you use the listview's position to get directly from the source ArrayList.
String a = patientArrayList.get(position);
Instead to get it from the filtered adapter:
String a = parent.getAdapter().getItem(position);
or
String a = parent.getItemAtPosition(position);
I created a custom-dialog in android that contains an EditText and a ListView. The list view onItemClickListener is fired correctly when I select any Item, but it is not the case with the listener of my EditText.
This is my code:
EditText filterEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater factory = LayoutInflater.from(this);
View content = factory.inflate(R.layout.dialog_layout, null);
filterEditText = (EditText) content
.findViewById(R.id.filterEditText);
filterEditText.addTextChangedListener(txtListener);
............
TextWatcher txtListener = new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
filterEditText.setText("text entered");
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
};
I was about to delete the post, but I decided to put the solution in case anybody faces the same problem.
I solved it by moving my code from onCreate into the method in which I created the dialog:
public void createLocationsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Choose a location");
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
View content = factory.inflate(R.layout.dialog_layout, null);
ListView locationsList = (ListView) content
.findViewById(R.id.locationsListView);
filterEditText = (EditText) content
.findViewById(R.id.filterEditText);
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_list_item_1,
data.getName());
locationsList.setAdapter(modeAdapter);
builder.setView(content);
locationsDialog = builder.create();
locationsList.setOnItemClickListener(listItemClicked);
filterEditText.addTextChangedListener(txtListener);
locationsDialog.show();
}
having a little problem getting the information from my spinner, this is how i have it set up in my activity
color = (Spinner)findViewById(R.id.ledColor);
vibrate = (Spinner)findViewById(R.id.vibPattern);
populateSpinners();
color.setOnItemSelectedListener(new colorSelected());
vibrate.setOnItemSelectedListener(new vibrateSelected());
public void populateSpinners(){
ArrayAdapter<CharSequence> cAdapter;
cAdapter = ArrayAdapter.createFromResource(this, R.array.colors,android.R.layout.simple_spinner_item);
int cSpinnerDD = android.R.layout.simple_spinner_dropdown_item;
cAdapter.setDropDownViewResource(cSpinnerDD);
color.setAdapter(cAdapter);
ArrayAdapter<CharSequence> vAdapter;
vAdapter = ArrayAdapter.createFromResource(this, R.array.vibrate, android.R.layout.simple_spinner_item);
int vSpinnerDD = android.R.layout.simple_spinner_dropdown_item;
vAdapter.setDropDownViewResource(vSpinnerDD);
vibrate.setAdapter(vAdapter);
}
public class colorSelected implements OnItemSelectedListener{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
arg0.getItemAtPosition(arg2);
nColor = arg0.toString();
Log.v("EditContact",nColor);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
/********************************************************************************************/
public class vibrateSelected implements OnItemSelectedListener{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
arg0.getItemAtPosition(arg2);
nVibrate = arg0.toString();
Log.v("EditContact",nVibrate);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
but it does not get the selection from the spinner what am i doing wrong?
create a public method like this :
public String returnString(AdapterView<?> parent,int position,long ID){
return parent.getSelectedItem().toString();
}
and put it in your onItemSelected method :
String yourtext = returnString(arg0, arg2, arg3);
Get spinner selected value by using below code..
String value=spinner.getSelectedItem().toString();