Can't get the position of item of dynamically created spinner - android

Basically i have a method createList() which creates a Spinner and then i add those spinners to an arrayList myList. After adding them i use setOnItemSelectedListener on each Spinner in the array List to get the position but no matter what i select in a spinner i get the position 0. Interestingly, if i don't add spinners to ArrayList and use only one spinner i get the position easily. The problem arises when i put spinner objects in an arrayList.
Here is the code:
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
Spinner spinner1;
int pos;
ArrayList<Spinner> myList = new ArrayList<>();
int length = 0;
int[] numbers;
int show;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = findViewById(R.id.root);
}
public void showPosition(View view) {
numbers = new int[length];
for (int i = 0; i < length; i++) {
myList.get(i).setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
numbers[i] = adapterView.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
public void createList(View view) {
length++;
ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(this, R.array.city, android.R.layout.simple_spinner_item);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1 = new Spinner(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(500, 50);
spinner1.setLayoutParams(params);
spinner1.setAdapter(arrayAdapter);
myList.add(spinner1);
linearLayout.addView(spinner1);
}
}
When i print number in the log all the elements of this array are zero no matter what item i have selected in the spinner.
Please help stuck on it for few days :(

Found the answer:
Directly get the position by mySpinner.get(i).getSelectedItemPosition() and use that position with a switch statement to make it workable.

Related

How to repeat spinner dynamically?

I have RelativeLayout with ScrollView as the root element. In RecyclerView I have spinner and TextView. Now I am getting data from JSON like RollNumber and Marks. Now in TextView, I need to show RollNumber and in Spinner Marks should be displayed. I already got the data in ArrayList<Progress> and what should be the code will look like for this situation;
Do I have to repeat the RelativeLayout in for loop?
OnCreate
for (int i = 0; i < progress.size(); i++) {
progress_addmore_spinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
loadspinner
}
private void loadSpinners()
{
if (progress != null || progress.size() > 0) {
ArrayList<String> progresscard = new ArrayList<>();
for (int i = 0; i < progress.size(); i++) {
progresscard.add(progress.get(i).toString());
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
progresscard);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
progress_addmore_spinner.setAdapter(dataAdapter);
if (progress.get(0).getMarks() != null && !progress.get(0).getMarks().isEmpty()) {
product_addmore_spinner.setSelection(progresscard.indexOf(toppingtypelist.get(0).getMarks()));
}
}
}
You can set the spinner including the adapter, the default value in the onBindViewHolder of the recyclerview adapter. Also set the position as the tag of the spinner in the adapter like: vh.view.setTag(position);
Now implement the OnItemSelectedListener in the activity or the fragment and pass it onto the recyclerview adapter. Since you have already set the position of the spinner as the tag, you can easily extract the index of the progress object in the ArrayList.
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int index = (int) parent.getTag();
parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};

To set text on spinner

I want to implement one code for three spinner where the user will fill there date of birth at register time when he/she will login and want to update there DOB, the DOB will pass on the spinner I have done it with day and month but there is one problem in year i.e adapter. adapter takes the (thisYear-18) year and print it but I want spinYear will take that value which I stored at registered time.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_details_fragment);
Spinner spinDay = (Spinner) findViewById(R.id.spinnerDay);
Spinner spinMonth = (Spinner) findViewById(R.id.spinnerMonth);
Spinner spinYear = (Spinner) findViewById(R.id.spinnerYear);
Button update = (Button)findViewById(R.id.update);
Intent intent =getIntent();
String str_DOB = intent.getStringExtra("dateofbirth");
Log.e("DOB************",str_DOB);
String[] d = str_DOB.split("-");
Log.e("d[0]-------",d[0].toString());
spinYear.setSelection (Integer.parseInt(d[0]));
spinMonth.setSelection (Integer.parseInt(d[1]));
spinDay.setSelection (Integer.parseInt(d[2]));
code for Year Adapter
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
thisYear=thisYear-18;
for (int i = thisYear; i >= 1967; i--) {
years.add(Integer.toString(i));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, years);
spinYear.setAdapter(adapter);
spinYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
final String yearName = adapterView.getItemAtPosition(pos).toString().trim();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
If I understand you correctly you want to set the selection of the year spinner based on your passed in Intent.
setSelection(int position) Takes the index of the item in the spinner you want to select.
After you call setAdapter do as so:
spinYear.setAdapter(adapter);
int index = years.indexOf(d[0]);
if (index != -1) {
spinYear.setSelection(index);
}
you should check the year in onItemSelected() method because this method get the position 0 and set it first.try to use below code:-
spinYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
if((d[2]).equals(adapterView.getItemAtPosition(pos).toString()))
{
final String yearName = adapterView.getItemAtPosition(pos).toString().trim();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});

Creating dynamic spinners and getting value of every spinner, Whenever a spinner item changed, get all spinner values

I'm developing a e-com app. I'm trying to create dynamic spinner. Spinner is dependent upon product attributes. I'm able to create spinners also mapped data on them but I want to get all spinners selected item whenever a spinner change its data so I can match to correct variant of product.
Here is my code snippet
final List<Attribute> attributes = product_.getAttributes();
for (i = 0; i < attributes.size(); i++) {
ArrayList<String> spinnerArray = (ArrayList<String>) attributes.get(i).getOptions();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, spinnerArray);
Spinner spinner = new Spinner(getActivity());
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
dynamicProductProperties.addView(spinner);
}
First, you need to set same instance of OnItemSelectListener to your all spinners. Let your activity or fragment implement OnItemSelectListener then call spinner.setOnItemSelectListener(this);
In onItemSelected method you can run this code to have selecteds.
ArrayList<String> selectedList = new ArrayList();
for (int i = 0; i < dynamicProductProperties.getChildCount(); i++) {
View view = dynamicProductProperties.getChildAt(i);
if (view instanceof Spinner){
String selected = (String) ((Spinner) view).getSelectedItem();
selectedList.add(TextUtils.isEmpty(selected) ? "" : selected);
}
}
Good luck
Emre

Using Checkbox array in android

I am trying to make a listview with checkbox using listview's built in checkbox method. I have gone through a stackoverflow post and i found it is running properly except one problem.
If there are four items in list and assume, i checked the second and third item, onclicking, it is displaying the second and third item as needed..but if i am selecting first and then third and then second item, and then i m unchecking the first, so i must be left with second and third as desired output. But it is providing first second and third item as output.
can anybody guide me on that..?
This is the java code:
public class TailoredtwoActivity extends Activity implements OnItemClickListener, OnClickListener{
Button btn1;
ListView mListView;
String[] array = new String[] {"Ham", "Turkey", "Bread"};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tailoredtwo);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);
mListView = (ListView) findViewById(R.id.listViewcity);
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button button = (Button) findViewById(R.id.btn_tailortwo_submit);
button.setOnClickListener(this);
}
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
int size = positions.size();
for(int index = 0; index < size; index++) {
Toast.makeText(getApplicationContext(), array[positions.keyAt(index)].toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
Change your onClick to
Delcare the below as a class variable
StringBuilder builder;
Then
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
builder = new StringBuilder();
for(int index = 0; index <array.length; index++) {
if(positions.get(index)==true)
{
builder.append(array[index]);
builder.append("\n");
}
}
Toast.makeText(getApplicationContext(),builder, Toast.LENGTH_LONG).show();
}

Select all items using a button in a custom listview

I would like to select and deselect all the items in the listview using "SelectAll" and "DeselectAll" buttons. I wrote the code for SelectAll but it throws a NullPointException. I couldn't find the bug in my code. Can someone point out the error in my code.
final ListView list;
String[] listItems = { "Enabled" };
list = (ListView)findViewById(R.id.list);
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, getResources().getStringArray(R.array.facilities)));
list.setItemsCanFocus(false);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
CheckedTextView ctv = (CheckedTextView)arg1;
//other functionality!
}
});
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View view) {
int itemCount = getListView().getCount();
System.out.print(itemCount);
for (int i = 0; i < itemCount; i++){
list.setItemChecked(i, true);
//getListView().setItemChecked(i, chk.isChecked());
}
}
};
Button button = (Button) findViewById(R.id.selectAll);
button.setOnClickListener(clickListener);
try to use below code...
private OnClickListener checkAllCheckboxes = new OnClickListener()
{
public void onClick(View v)
{
ListView lv = getListView();
int size = getListAdapter().getCount();
if(lv.isItemChecked(0))
{
for(int i = 0; i<=size; i++)
{
lv.setItemChecked(i, false);
}
}
}
}
};
You Can create One ArrayList of data class
class data
{
boolean chekced=false
create setter and getter of this
}
Create ArrayList of Data Class intially Chekced is false in all arraylist items
When select is called set all items to true
Then moify adpater and call notifyDatasetChanged on listView
This is how you can do this

Categories

Resources