add item in array list of android [closed] - android

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I want to add value getting from text view of android to an existing array list.e.g. my current array list contain values Cricket,Football and by text view I want to add hockey in array list at last position ..then my array list become Cricket ,football,hockey. My array list of cricket and football is coming from previous activity.
But now it add only cricket and football but does not add hockey
How can I do it?
resultArrGame+=resultArrGame.add(txtGame.getText().toString());

This will definitely work for you...
ArrayList<String> list = new ArrayList<String>();
list.add(textview.getText().toString());
list.add("B");
list.add("C");

You're trying to assign the result of the add operation to resultArrGame, and add can either return true or false, depending on if the operation was successful or not. What you want is probably just:
resultArrGame.add(txt.Game.getText().toString());

you can use this add string to list on a button click
final String a[]={"hello","world"};
final ArrayAdapter<String> at=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a);
final ListView sp=(ListView)findViewById(R.id.listView1);
sp.setAdapter(at);
final EditText et=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
int k=sp.getCount();
String a1[]=new String[k+1];
for(int i=0;i<k;i++)
a1[i]=sp.getItemAtPosition(i).toString();
a1[k]=et.getText().toString();
ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
sp.setAdapter(ats);
}
});
So on a button click it will get string from edittext and store in listitem.
you can change this to your needs.

item=sp.getItemAtPosition(i).toString();
list.add(item);
adapter.notifyDataSetChanged () ;
look up ArrayAdapter.notifyDataSetChanged()

Related

Android: Get Spinner Data from a Recycler view

I creating a feedback screen in an application in which user will have to select their opinion(displayed as Spinner) for each question(TextView).
Multiple questions & options will be displayed in a RecylcerView. On clicking submit button, I need to get all the data(Both Question and Selected spinner value) from recycler view and send to the server.
I saw the many suggesting to implement onItemSelectedListener on the Spinner. It will not suitable for me because Each spinner will have default value. Also user may not select each and every spinner.
How to get the value of each spinner(Opinion) & Textview(Question) inside ViewHolder of a RecyclerView
Step 1: You must have Model class say Question like below
public class Question {
String questionTitle;
List<Answer> answerList;
// getter/setter
}
public class Answer {
boolean isSelected;
boolean isDefault;
// getter/setter
}
Step 2: You must be passing list of Question to your adapter. And on item click simply set the answer as selected using answer.setSelected(true) for the particular question.
Step 3: Create a method in adapter class like below which will give you the selected answers for all the question.
public Map<String,Answer> getSelectedAnswers() {
Map<String,Answer> map = new HashMap();
for(Question question : questionList){
List<Answer> answers = question.getAnswerList();
Answer defaultAnswer;
for (Answer answer: answers){
if(answer.isSelected()){
map.put(question.questionTitle(),answer);
defaultAnswer = null;
break;
}
if(answer.isDefault()) {
defaultAnswer = answer;
}
}
if(defaultAnswer != null) {
map.put(question.questionTitle(),defaultAnswer);
}
}
return map;
}
Note : If step 3 want to avoid then keep a Map<String, Answer> selectionMap in the adapter itself where is key would be question and value would be a selected answer for that question, and keep updating on spinner item selection.
Step 4: At the time of calling API on submit button you need to traverse Map and then wrap into required fields what API expects.

How can I limit the values of MultiAutoCompleteTextView to be only the items from my adapter?

This is the code I'm using:
MultiAutoCompleteTextView selectedCities = (MultiAutoCompleteTextView)findViewById(R.id.citiesSelected);
String[] cities = getResources().getStringArray(R.array.cities);
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,cities);
selectedCities.setAdapter(adapter);
selectedCities.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
but when i want to add items it is possible to add any string not from my list...
I dont want to use Alert Dialog with MultiChoiceItems since I have more than 200 items on my list.
Thanks!!
I know this is an old question but if you still have this problem, you can do this in at least two ways:
You can add an onFocusChangeListener and then perform your
validation inside of that.
You can have your activity implement TextWatcher and
then override:
#Override
public void afterTextChanged(Editable s) {
// validation code goes here
}
About the last one, take a look at this question: Android: How can I validate EditText input?.

Alternative to HIGHLY FLAWED SPINNER CLASS in Android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
in my current project i have dealt with spinner class which has been customized from almost every aspect possible. Thus i have gained some detailed aspects as i deal with it . So i will start with the part it shows why it is flawed.
1_There is no default listener that will be fired on pop up window/layout/dialog created-showed(layout inflated) event. There are some workarounds such as ontouch listener on spinner, then check if on touch finish happened in spinner area, then you know popup will be shown but still not reliable since you can fill popup with async task..
2_On item selected event does not fire when same index is selected again. This is really annoying since i may be updating the adapter depending on other conditions which will change current selection and list order etc... Of course there is a workaround way by creating own spinner class and adding it in xml like com.myproject.customspinner etc.....(Spinner : onItemSelected not called when selected item remains the same)
3_There is no working functional OnClickListener and OnItemLongTouchListener event for spinner.
4_Changing Spinner DropDown list divider element's attributes such as color requires more labor than changing all dropdrown and spinner' background views itself which is very absurd.
5_Spinner the name itself is very absurd =))).
So what can i use instead of Spinner? Which is best way to go?
You can create a custom spinner using ListPopupWindow to a TextView means when a TextView is clicked a ListPopupWindow open like spinner dropdown list and you can choose a element. If you need I will help you in that.
ListPopupWindow numberList;
TextView spDays;
ArrayList<Map<String, String>>() listTrans;
in oncreate() spDays.setonclicklistner(this);spDays.setText("Select");
setNumberListSpinnerView();
in onclick(){
when spDays clicked :- numberList.show();
}
void setNumberListSpinnerView() {
numberList= new ListPopupWindow(this);
numberList.setAnchorView(spDays);
numberList.setOnItemClickListener((new AdapterView.OnItemClickListener() {
#Override
getListItem();
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Map map = listTrans.get(position);
spDays.setText(map.get("circle_name").toString());
circle_name = map.get("circle_name") + "";
circle_id = map.get("circle_id").toString();
circleList.dismiss();
Log.d("Circle id:", circle_id + "");
getRetails();
}
}));
}
void getListItem(){
String[] numbers = {"1","2","3","4","5","6"};
listTrans = new ArrayList<Map<String, String>>();
LinkedHashMap<String, String> tran = new LinkedHashMap<String, String>();
for (String number : numbers) {
tran.put("numbers", number);
listTrans.add(tran);
}
SimpleAdapter adapter = new SimpleAdapter(AddRetailSurvey.this, listTrans,
android.R.layout.simple_spinner_dropdown_item,
new String[]{"numbers"},
new int[]{android.R.id.text1});
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
numberList.setAdapter(adapter);
}
Check this code and modify it according to your requirement. If you found any problem I am here to help you. :)
Putting a simplified kotlin version of the accepted answer here, which may help. At first make a ListPopupWindow member in your Activity or other class-
private val listPopupView by lazy { ListPopupWindow(this) }
Then initialize it in the onCreate() method-
val dataList = arrayOf("item1", "item2", "item3", "item4")
listPopupView.setAdapter(ArrayAdapter(this, android.R.layout.simple_list_item_1, dataList))
listPopupView.setOnItemClickListener { _, _, position, _ ->
selectionTextView.text = dataList[position]
listPopupView.dismiss()
// do other things on selection
}
listPopupView.anchorView = selectionTextView
selectionTextView.setOnClickListener { listPopupView.show() }
And you are done!
This shows you how to replace Spinner with your own implementation. It's pretty simple, the important thing is to use a PopupWindow containing a list view to imitate Spinner's layout behavior.
https://www.androidcode.ninja/show-listview-as-drop-down-android/
This fixes the issues with weird event handlers in Spinner's implementation. It's also much easier to customize.
The only problem with this approach is that like Spinner, it still uses PopupWindow, which causes weird bugs in the system UI when you're in immersive/fullscreen mode. But it's easier to handle those bugs when you don't also have to deal with Spinner's specific issues.

How to achieve nested spinner? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have requirement for filtering category type -> category -> products. For this I have to use nested spinner as we have in eclipse package explorer.
How can I achieve?
Look, I am not sure if you are looking for something like that. I have 2 spinner, when the user select a item from brandspinner, the modelspinner is setted with all the products of this brand.
private Spinner brandSpinner;
private Spinner modelSpinner;
brandSpinner = (Spinner)root.findViewById(R.id.brand_spinner);
modelSpinner = (Spinner)root.findViewById(R.id.model_spinner);
brandsAdapter = new ArrayAdapter<BrandItem>(mContext, android.R.layout.simple_spinner_dropdown_item, ArrayListWithBrands);
//I am not sure if it is needed:
brandsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
brandSpinner.setAdapter(brandsAdapter);
brandSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
//Harcoding Brands:
BrandItem brand = brandsArrHarcode.get(pos);
final ArrayList<String> modelsArr = brand.getModels();
modelsAdapter = new CustomArrayAdapter(mContext, android.R.layout.simple_spinner_dropdown_item, modelsArr);
modelsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
modelSpinner.setAdapter(modelsAdapter);
modelSpinner.setSelection(modelsAdapter.getPosition(camera.getModel()));
}
#Override
public void onNothingSelected(AdapterView<?> a) {}
}
);
Hope to be helpful.

Android - PagerAdapter not saving RadioButton's state

I have a very peculiar problem. I understand that while in the foreground the member variables of an Activity remain untouched (don't need saving to persist). Now, I have a PagerAdapter that represents a quiz with a question and three answers. I've made various objects to represent the question and answers.
A Question always has a list of exactly 3 Answer's. This is how I do it: (note: some code was left out for readability)
public class QuizPagerAdapter
{
List<Question> questionList;
Context context;
public QuizPagerAdapter (List<Question> list, Context ctx) {
questionList = list;
context = ctx;
}
#Override
public Object instantiateItem (View pager, int position) {
// Create various views (ScrollView, LinearLayout, etc)
final Question q = questionList.get(position);
RadioGroup group = new RadioGroup(context);
for (int i = 0; i < 3; i++) {
Answer a = q.getAnswer(i);
RadioButton rb = new RadioButton(context);
rb.setId(i);
rb.setText(a.getText());
rb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton btn = (RadioButton) v;
q.unselectAll(); // unselects all Answer's
q.getAnswer(btn.getId()).setSelected(true);
}
});
if (a.isSelected()) rb.setChecked(true);
}
return view;
}
}
When I use this in my Activity, I get a nice list of Questions with three Answers. Now, when I select one Answer, the RadioButton is checked. OK, now, I scroll to the next Question and check that one, then go back to the previous Question and there the answer I checked in the first place is now not checked.
Now, this doesn't always happen, it happens sometimes, but that sometimes is enough that it can cause a problem. The Activity is never placed in the background.
I understand that Android will destroy Views in the PagerAdapter to conserve memory, thus destroying the RadioButton, this is why I have this snippet:
if (a.isSelected()) rb.setChecked(true);
But it is still happening. I've tried logging everything, debugging but I cant seem to get to the source of the problem. Maybe someone here has come across a similar problem.
Any help is appreciated,
Thank you in advance!
In the OnClick event, make sure that your reference to Question is the correct object. You might want to reference the question by the list index, because if you have two Questions on the screen at the same time, the reference of q could be the second question, but you have clicked the first questions answer.
** Added **
The issue is that q is a reference to a question, and each time through the instantiateItem function, this reference is set to a new instance of a question from the list. So when you execute the OnClick event, the value q might be pointing to the incorrect instance of question than what you expect. You would be better off getting the question out of the original list by the views index in the activity.
Something like the following:
public void onClick(View v) {
RadioButton btn = (RadioButton) v;
Question question = questionList.get(position);
question.unselectAll(); // unselects all Answer's
question.getAnswer(btn.getId()).setSelected(true);
}

Categories

Resources