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.
Related
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
I am trying to save the state of checkboxes in my main activity rather than in my custom adapter. I have checked that the correct data is being stored in the sharedprefs and can retrieve the information successfully but when I try and mark the checkboxes on opening the app the viewholder is null. In theory I understand what the problem is but I have no clue how to fix it.
Here is the part of code from the main activity I am having issues with:
for (int i= 0; i<results.size(); i++) {
result = (Results) customAdapter.getItem(i);
if (result != null) {
String RESULT = result.getTitle();
if (sharedPref.getBoolean(result.getTitle(), false)){
Log.i("Saved", result.getTitle());
CustomAdapter.ViewHolder viewHolder = (CustomAdapter.ViewHolder) listView.getTag(i);
Log.i("viewHolder", String.valueOf(viewHolder));
viewHolder.getCheckBox().setChecked(sharedPref.getBoolean(RESULT, false));
}
}
}
You are preparing a List<Results> to pass to adapter right? First add a extra boolean variable in Results model class to represent the state of checkbox. Now at the time you prepare the list in activity, set the value of this new boolean for each item from the preference. So that your List<Results> contain state of the checkbox.
Make an AdapterArray become an IntArray because I can't send to another activity an adapter array.
I'm creating a racing timer in Android Studio Java and I have saved my data about the race (example: time of all turns) in an Array Adapter. But when I try to send it to another Activity the function doesn't accept ArrayAdapter so I created a function to turn ArrayAdapter into an IntArray the problem is that whenever I run that function the program crashes.
I'm looking for an answer to this problem by correcting my code or doing a completely different one if I had to.
public int[] AdapterToInt(ArrayAdapter adapter)
{
int[] a = new int[adapter.getCount()];
for (int i = 0; i < adapter.getCount(); i++)
{
a[i] = Integer.valueOf(adapter.getItem(i));
}
return a;
}
public void onButtonClickSaveTimes(View view) {
int[] array;
array = AdapterToInt(adapter1);
TextView textoexemplo = (TextView) findViewById(R.id.textViewhorario);
Intent myIntent = new Intent(getBaseContext(), Main5Activity.class);
myIntent.putExtra("car1", AdapterToInt(adapter1));
myIntent.putExtra("car2", AdapterToInt(adapter2));
myIntent.putExtra("car3", AdapterToInt(adapter3));
myIntent.putExtra("car4", AdapterToInt(adapter4));
myIntent.putExtra("car5", AdapterToInt(adapter5));
startActivity(myIntent);
}
I expect it to send the ArrayAdapter to another activity or at least making my function work and turn ArrayAdapter into ArrayInt so i can send it through myIntent.putExtra, but the actual output is a app crash.
The problem is likely here:
a[i] = Integer.valueOf(adapter.getItem(i));
Since adapater.getItem(i) returns an object that you likely will not be able to convert into an integer, you are probably going to have issues here.
You could instead use adapter.getItemId(i) which would return a long as opposed to an object.
However, that idea also doesn't seem to great so I would try to see if anything from here works for you.
And if none of that works it probably makes more sense to just send over all the data you need to reconstruct your ArrayAdapter to the other activity.
This link may also help:
How do I pass custom ArrayAdapter Object between Intents with serialization
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 ListView that is populated by a news server rundown (just a list of story slugs) and an arrayAdapter to modify that ListView.
I can remove items by the 'remove(Object)' function but what if there are multiple instances of 'Object'? remove() only removed the first instance of 'Object'. I cannot remove, for example, the second 'Object' in my array adapter without removing the first one. So my question is how can i work around this?
ex : Rundown A
story 1
story 2
Break
story 3
story 4
Break
story 5
etc...
so in this example i cannot delete the Second 'Break' because remove('Break') will remove the first one. if i could removeByIndex(5), that would be perfect but....
Ive tried writing my own remove function that creates a whole new adapter with all members but the specified index. here is what i was messing around with.
public ArrayAdapter<String> removeIndex(ArrayAdapter<String> arr, int index) {
ArrayAdapter<String> temp = new ArrayAdapter<String>(arr.getContext(),R.layout.list_item);
for(int i =0 ; i<arr.getCount();i++){
if(i != index) temp.add(arr.getItem(i));
}
return temp;
}
Help or suggestions are appriciated.
Handle the collection of strings yourself with a List and pass the object into the constructor of the ArrayAdapter. This leaves you with a reference to the List so you can alter the data while allowing the adapter to manage and display as needed.
Note: When modifying the data object you must call
myAdapter.notifyDataSetChanged()
afterwards - which must also be on the UI thread. Obviously the changes to the list don't have to take place on the UI thread and should most likely not happen on the UI thread.
private ArrayList<String> mData = new ArrayList<String>();
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
// Code that adds the strings
// Create the list adapter
mAdapter = new ArrayAdapter<String>(myActivity.this, android.R.layout.simple_list_item_1, mData);
}
private void removeItem(int index) {
mData.removeAt(index);
myActivity.this.runOnUiThread(new Runnable() {
public void run() {
mAdapter.notifyDataSetChanged();
}
}
}