I have a spinner of strings. I want to add support to multi langues so I move the strings into strings.xml file and now I have the following method in consts class:
public static String[] getCars(Activity activity) {
if (activity == null) {
return null;
}
return new String[] {
activity.getString(R.string.car1),
activity.getString(R.string.car2)
// more
};
}
Now I display the cars in the spinner as follows:
Spinner spinner = findViewById(spinnerId);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, spinnerValues);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
Other code to handle changes:
String car = shift.getCar(); // from DB
int carPosition = Arrays.asList(ShiftUtils.getCars(this)).indexOf(car);
Spinner carsSpinner = findViewById(R.id.add_car_spinner);
carsSpinner.setSelection(carPosition);
I keep the car names in English in the DB so getCar() will return the chosen car name in English. But then if my application is currently in other language, carPosition will be -1 because it will not find the string (because car is in English). I want to display the spinner values to be in the locale language but in the background (fetch and push) to be in English. What would be the best way to do it? I prefer not to touch the DB (keep it in English).
Instead of getting the car name from your DB, create a unique ID for each car, and make your spinner item list hold both the ids and the text values.
This way, you'll be able to get the id of the selected car from the DB, and set it as the selected car in your spinner, regardless of the display language
Related
I want to get the position of a item in the list view and use it in a if.
Now i am going through the listview using a for loop, and i want when i find the specfic Product Id equal to the Same Product (if clause), and when i find it i use that position to update my list
for (int i = 0; i < adapterItensDoCarrinho.getCount(); i++) {
Log.d("ENTROU", "ENTROU");
Log.d("ID", String.valueOf(lsvCarrinhoCompras.getId()));
if (produtoSelecionado.getId() == adapterItensDoCarrinho.getItemId(i)) {
Log.d("ENTROU 2", "ENTROU 2");
int novaQte = itemDoCarrinho.getQtdeSelecionada();
novaQte++;
itemDoCarrinho.setNome(produtoSelecionado.getNome());
itemDoCarrinho.setQtdeSelecionada(novaQte);
itemDoCarrinho.setPrecoItemVenda(produtoSelecionado.getPrecoProduto());
adapterItensDoCarrinho.updateItemCarrinho(lsvCarrinhoCompras.getId(), itemDoCarrinho);
break;
}
else {
itemDoCarrinho.setNome(produtoSelecionado.getNome());
itemDoCarrinho.setQtdeSelecionada(qtdeProduto);
itemDoCarrinho.setPrecoItemVenda(produtoSelecionado.getPrecoProduto());
adapterItensDoCarrinho.addItemCarrinho(itemDoCarrinho);
}
}
Hope you understand it!
Your Adapter should be the one to handle this behavior. Write a public method in the Adapter class which allows you to pass in the selected product ID. Whenever the selected product ID changes in your Activity/Fragment/whatever, call the public method in the Adapter to update the product ID value. Then, in the getView() method of the Adapter, if the ID matches, perform whatever special behavior you want to have happen for the product with that ID.
Newbie. I'm coding a quiz app full code on Github that loads an arrayList with four arguments:
question
image (from drawables)
key answer
possible answers presented in a radioGroup (sub-arrayList)
from the strings.xml as below
...
<string name="questionOne">Who is the "Modern Love" rock star singer?</string>
<string name="answerOne">David Bowie</string>
<string-array name="celebrityOne">
<item>Jaimie Hendrix</item>
<item>David Bowie</item>
<item>Jim Morrison</item>
<item>Elvis Presley</item>
</string-array>
...
Below is how the arguments are loaded in MainActivity (The third argument is a sub-arraylist)
ArrayList<Object> arrayList = new ArrayList<>();
loaddata()
...
public void loadData() {
arrayList.add(new Quiz(getResources().getString(R.string.questionOne),
getResources().getDrawable(R.drawable.celebrity_one_image, null),
new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.celebrityOne))),
getResources().getString(R.string.answerOne)));
arrayList.add(new Quiz(getResources().getString(R.string.questionTwo),
getResources().getDrawable(R.drawable.celebrity_two_image, null),
new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.celebrityTwo))),
getResources().getString(R.string.answerTwo)));
...
}
The issue is after N iterations, the sub-arrayList starts repeating itself (See image below).
Also I think maybe the source of the problem is in the Adapter, where for each string in sub-array is assigned to a radioButton;
void createRadioButtons(String[] arrayAnswer) {
if (mRadioGroup.getChildAt(0) != null)
return;
for (int i = 0; i < arrayAnswer.length; i++) {
mRadioGroup.addView(createRadioButtonAnswerAndSetOnClickListener(arrayAnswer[i]));
}
}
RadioButton createRadioButtonAnswerAndSetOnClickListener(String string) {
RadioButton radioButton = new RadioButton(mContext);
radioButton.setText(string);
radioButton.setOnClickListener(this);
return radioButton;
}
My situation might be similar to this but I have no static fields and arrayList is initialized as new so no need to clear().
From Documentation:
The RecyclerView creates only as many view holders as are needed to display the on-screen portion of the dynamic content, plus a few extra. As the user scrolls through the list, the RecyclerView takes the off-screen views and rebinds them to the data which is scrolling onto the screen.
This means RecyclerView reuses already created view holders when you are scrolling it(that is why your data repeats), and you must repopulate views with new data. So, instead of returning from createRadioButtons method, when mRadioGroup.getChildAt(0) != null, you must change RadioButtons texts to your new data from arrayAnswer.
in your adapter just change this:
if (mRadioGroup.getChildAt(0) != null)
return;
To this:
if (mRadioGroup.getChildAt(0) != null)
mRadioGroup.removeAllViews();
At some moment your adapter, began to reuse view holders which were created at the top of the recyclerView, but it was already filled with data, so when you call return, you just leave your old data, while you need to delete it and then add new data...
In the below code, where the item’s position and title is getting saved in list_items works fine if list_items and items are ArrayList. For ex;
ArrayList.add(ArrayList.get(position));
But I am trying to use listview:
ArrayList.add(Listview.get(position));
Below is my code
final Listadapter Adapter =new Listadapter(this,packageList1,packageManager);
items.setAdapter(Adapter);
items.setChoiceMode(apps.CHOICE_MODE_MULTIPLE_MODAL);
items.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener()
{
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked)
{
count = count +1;
mode.setTitle(count + "items selected"); //problem resides in the below line
list_items.add(items.get(position));
}
In the above code, on selecting an item from listview I am trying to save it in an Arraylist i.e list_items which could be used in onActionItemClicked method for further action on that respective item.
Any ideas on how to solve or find a workaround to use a listview in the above situation?
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 7 years ago.
I have a method in a Fragment that takes a value from a quantity Spinner and returns it. Where can I retrieve the value of this variable? If I want to move it to a new Activity altogether, how can I retrieve it there?
public String SetupQuantitySpinner(String[] quantity) {
Spinner spnr2;
spnr2 = (Spinner)view.findViewById(R.id.spinner_quantity);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),
R.layout.custom_spinner,
R.id.text_main_seen,
quantity);
spnr2.setAdapter(adapter);
return quantity[spnr2.getSelectedItemPosition()];
}
Basically the Spinner represents the quantity of the item that a user has decided to purchase, i.e. 1 to 20 shirts. I now have to multiply this value by its cost, but the cost is retrieved in another Activity altogether:
String cost = currentProduct.getCost();
I need to send quantity[spnr2.getSelectedItemPosition()] to this new Activity so that I can multiply it by currentProduct.getCost();
How can I accomplish this?
Edit: This is different and hence not a duplicate because I only want to send and retrieve data associated with the selected Spinner item.
If you want to retrieve only selected item in another activity then you can simply put this code inside onItemSelected method. And retrieve the value of extra in that activity.
String item = mSpinner.getSelectedItem().toString();
Intent intent = new Intent(this,NextActivity.class);
intent.putExtra("item",item);
startActivity(intent);
This is another way to do it. Write a global variable:
public final static String PRODUCT_SIZE_MESSAGE = "com.elgami.customizer.PRODUCT_SIZE";
Start your Intent where you want to in your code:
Intent intent;
intent.putExtra(MainActivity.PRODUCT_QUANTITY_MESSAGE, productQuantity);
startActivity(intent);
You put the variable you want to send along with your Intent in the Extra, and then retrieve it in the new Class as follows:
private int getIntentMessageProductQuantity() {
return getIntent().getIntExtra(MainActivity.PRODUCT_QUANTITY_MESSAGE, 0);
}
Now you have that variable and you can use it as a parameter in any method in the new Class, like so:
public void LaunchPurchaseIntent(MainActivity.ProductType productType, int productSize, int productQuantity, String uuid) throws ParseException {
// Do what you want here
}
I have a main class that holds two array lists of class objects. Long story short, I'm calling an activity via startActivityForResult to get a return of the position of a spinner item selection. I have two boolean variables in the main activity that basically tell the application which list is being worked with: booleans listASelected and listBSelected. If listASelected = true, then listBSelected = false and visa-versa. In the result activity I basically generate the spinner this way:
MainActivity mainAct = new MainAtivity();
Spinner dropdown = (Spinner)findViewById(R.id.mainMenu);
for(int i = 0;i<mainAct.pickThreeNumbers.size(); i++){
optionsPickThree.add(mainAct.pickThreeNumbers.get(i).getNumbers(1)+mainAct.pickThreeNumbers.get(i).getNumbers(2)+mainAct.pickThreeNumbers.get(i).getNumbers(3));
}
for(int r = 0; r<mainAct.pickFourNumbers.size();r++){
optionsPickFour.add(mainAct.pickFourNumbers.get(r).getNumbers(1)+mainAct.pickFourNumbers.get(r).getNumbers(2)+mainAct.pickFourNumbers.get(r).getNumbers(3)+mainAct.pickFourNumbers.get(r).getNumbers(4));
}
if(mainAct.pickThreeSelected){
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, optionsPickThree);
}else{
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, optionsPickFour);
}
dropdown.setAdapter(adapter);
Then, I use this to do my setResult.
Intent output = new Intent();
if(mainAct.pickThreeSelected){
output.putExtra("slot", position);
output.putExtra("list", "PickThree");
}else{
output.putExtra("slot", position);
output.putExtra("list", "PickFour");
}
setResult(1,output);
finish();
}
The issue is that nomatter what it always works as if mainAct.pickThreeSelected = true, even if I know it is false because other sections of the app are functioning properly. What I assume is happening is that the class object is accessing the variable's initialized values instead of their current values at the time of execution. That, or I'm an idiot and there's a different way to accomplish this.
Any help, fellas? Thanks in advance!
Make pickThreeSelected as static. That way you will update the same instance everytime.
What is the default value that you have set to the mainAct.pickThreeSelected??If its true,make it as false.Then if user selects the listA change the value to true.