How to store data to array and SUM data from Array - java

I have radio button in radiogroup, which is if i click it i'll get the value and show it as a Toast Message, and then i want to store the value into Array.
Here is my code.
This code has function to get value to text of radiobutton.
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton checkedRadioButton = (RadioButton) view.findViewById(i);
String text = checkedRadioButton.getText().toString();
Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
}
});
After i get the value in Array, i want to sum the data in new variable.

Declare a list outside of the setOnCheckedChangeListener and every time you click the radio button add that element to the list:
ArrayList mArrayList = new ArrayList();
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton checkedRadioButton = (RadioButton) view.findViewById(i);
String text = checkedRadioButton.getText().toString();
mArrayList.add(Integer.parseInt(text));
Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
}
});
And than when you want to get the sum of the list:
If you are using java 8:
int sum = mArrayList .stream().mapToInt(Integer::intValue).sum();
if not:
int sum = 0;
for(Integer iterator: mArrayList){
sum+=iterator
}
//after that your sum is ready
That's all
Edit
Just make sure that all radio buttons are Numbers. If you face empty number or a character your Android app will crash giving a NumberFormatException

To store the values in an array, use ArrayList
ArrayList<Integer> myList = new ArrayList<Integer>();
Every time you want to store an int value, use:
myList.add(the int value);
In your case, substitute the int value with Integer.parseInt(text)
For the summing process: iterate the array with a simple for as follows
int total = 0;
for (int i=0; i<myList.size(); i++){
total += myList.get(i);
}

Related

how to get and compare the index value from onItemSelected in multi select spinner

I am suing multi select spinner to update languages to the server using retrofit. but when i select multi options from spinner it returns a boolean array and the selected value returns as true and the others as false. now i need to get the value against each title using the index and store them into an array and send that array to server to update my record. here is the image that explain it.
This image is showing the boolean array which returns true against each selected value and the other array is my data i have to show the user the title and on the back end i have to send the value against each title .
this is the code i which i have to not able to get the array of values against each selected title. please help
Call<List<EnglishLevel>> call_english = RetrofitClient.getInstance().getApi().getenglishlist("english_levels");
call_english.enqueue(new Callback<List<EnglishLevel>>() {
#Override
public void onResponse(Call<List<EnglishLevel>> call, Response<List<EnglishLevel>> response) {
arrayList_english =response.body();
for (EnglishLevel C:arrayList_english){
if (C.getTitle() != null){
Log.d("English level" , C.getTitle());
final String[] levelName = new String[arrayList_english.size()];
for (int i=0 ; i<arrayList_english.size() ; i++){
levelName[i]= arrayList_english.get(i).getTitle();
}
ArrayAdapter<String> adapter= new ArrayAdapter <String>(SearchActivity.this,
android.R.layout.simple_list_item_multiple_choice,
levelName);
english.setListAdapter(adapter).setListener(new MultiSelectSpinner.MultiSpinnerListener() {
#Override
public void onItemsSelected(boolean[] selected) {
ArrayList<String> toSend = new ArrayList<>();
for(int j = 0; j < arrayList_english.size(); j++){
if(selected[j]) {
toSend.add(arrayList_english.get(j).getValue());
}
}
//
}
})
.setSelectAll(false).setMinSelectedItems(0);
}
}
}
#Override
public void onFailure(Call<List<EnglishLevel>> call, Throwable t) {
Toast.makeText(SearchActivity.this , t.getMessage() , Toast.LENGTH_SHORT).show();
}
});
In the above code that i have issue with some part of it...
english.setListAdapter(adapter).setListener(new MultiSelectSpinner.MultiSpinnerListener() {
#Override
public void onItemsSelected(boolean[] selected) {
ArrayList<String> toSend = new ArrayList<>();
for(int j = 0; j < arrayList_english.size(); j++){
if(selected[j]) {
toSend.add(arrayList_english.get(j).getValue());
}
}
//
}
in onItemSelected i have to get array of each selected title's value.
in this problem you need to define your ArrayList toSend = new ArrayList<>(); as a globally in existing scenario you are creating new array list every time when you select one language from spinner

Going through array element OnClickListener android studio

I am struggling to go through each element of an Array at each button click, I can make a counter increase or decrease at each button click but I want to use for loop or while loop to do count or to go through each element of array.
Here is my code:
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (j = 0; j < 3; j++) {
d = String.valueOf(amp[j]);
Toast.makeText(MainActivity.this, d, Toast.LENGTH_LONG).show();
}//outer
}
});
I also declared a global array variable int[] amp = {4,8,7};
The problem is the loop prints each element at button click but what I want is on first click print first element of array, and if I click button again then print second element of array and so on.
You could use something like:
int counter = 0;
b.setOnClickListener(new View.OnClickListener() {
# Override public void onClick(View v) {
d = String.valueOf(amp[counter]);
Toast.makeText(MainActivity.this, d, Toast.LENGTH_LONG).show();
counter++;
if(counter>amp.length)
counter=0;
}
});
You might not need a for loop or while loop to do this. It can be accomplished simply by using an index variable and an if/else statement. Here, index is a member variable initialized to 0.
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index < amp.length){
d = String.valueOf(amp[j]);
Toast.makeText(MainActivity.this, d, Toast.LENGTH_LONG).show();
// Increment index until we hit the last element
index++;
}else {
// You can reset the index here so it starts at 0 once again
index = 0;
}
}
});

Getting checked radio buttons values

I'm having a small problem trying to get the checked values from a radio group.
I've used a for loop to create my questions and radiogroups.
LinearLayout a = (LinearLayout) findViewById(R.id.aLayout);
for (int k = 1; k < 11; k++){
//CREATE QUESTIONS
TextView q = new TextView(this);
q.setText(k + ")" + " " + pssQ[k]);
a.addView(q);
//CREATE RADIO BUTTONS
final RadioButton[] rB = new RadioButton[5];
RadioGroup rg = new RadioGroup(this);
rg.setOrientation(LinearLayout.VERTICAL);
for(int i = 0; i < 5; i++){
rB[i] = new RadioButton(this);
rg.addView(rB[i]);
rB[i].setText(a1[i]);
}
a.addView(rg);
//get values here??
}
The code works how I intended it to.
The problem is that I don't know how to get the checked radio-button from each iteration. There is ten in total that I want to collect.
Any guidance would be appreciated. And if there's an easier alternative I'd be open to suggestions.
Thanks in advance. :)
You need to attach a check change listener to each of your RadioGroup within the loop:
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// your logic here
}
});
A way will be to use an additional variable (for example) isChecked as a boolean variable ,so when isChecked is true you will can spot which radio button is checked by the user on any iteration.

How to retrieve value changes made from a For Loop within it's own method in Android Studio?

I have a for loop within my main activity that is used to randomly shuffle/reassign the values within an array at the beginning of every time the application is opened.
I was told that for loops in Android Studio could only exist within a method (after getting errors when it was placed without one), but by doing so the random shuffling of the array is not carried over to the rest of the click events that are outside of the method and it just continues to output the same originally assigned values of in the array.
int[] money = {1,10,5,2,20,500,50,100,1000000,5000,1000,50000,100000,500000,250000,10000};
int swap1;
int swap2;
int temp;
Random random = new Random();
void what(){
for (int j=0;j<16;j+=1)
{
swap1 = random.nextInt(16);
swap2 = random.nextInt(16);
temp = money[swap1];
money[swap1] = money[swap2];
money[swap2] = temp;
}
}
The click events that are using the values from this array are like this one:
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View b) {
one.setVisibility(View.INVISIBLE);
counter++;
money[0] = 0;
Context one = getApplicationContext();
CharSequence message1 = "$1";
int duration = Toast.LENGTH_LONG; //this could also be a number
final Toast one1 = Toast.makeText(one, message1, duration);
one1.show();
for (int x = 0; x < 16; x++) {
sum += money[x];
}
banker = sum / 16;
Context oney = getApplicationContext();
CharSequence message1y = "The Banker offers you $" + banker + " for your case.";
int durationy = Toast.LENGTH_LONG; //this could also be a number
final Toast one1y = Toast.makeText(oney, message1y, durationy);
one1y.show();
}
});
The aim was that if I were to click this button this time the money output was something like $500, and the next time I opened the application it would randomly shuffle and I might get a new value like $1.
You might want to check out Collections.shuffle() instead of implementing it (don't reinvent the wheel etc).
Sounds like what you want to do is call the shuffle method from inside onCreate() and onResume()
You should do the shuffle inside of the "onCreate" method.
public void onCreate(Bundle savedInstanceState){
...
int[] money = {1,10,5,2,20,500,50,100,1000000,5000,1000,50000,100000,500000,250000,10000};
int swap1;
int swap2;
int temp;
Random random = new Random();
void what(){
for (int j=0;j<16;j+=1)
{
swap1 = random.nextInt(16);
swap2 = random.nextInt(16);
temp = money[swap1];
money[swap1] = money[swap2];
money[swap2] = temp;
}
}
}

Getting text from a Textview and adding it to an ArrayList?

So here's my problem its been bugging me for a while but when I try to get the text from a textview (custom number picker) and add it as an array value, the array won't let me input the textview value (sonyR).
Custom number picker widget :
#Override
public void onClick(View v) {
String getString = String.valueOf(tvSony.getText());
int current1 = Integer.parseInt(getString);
if (v == btnUp1) {
if (current1 < nEnd) {
current1++;
tvSony.setText(String.valueOf(current1));
}
}
if (v == btnDown1) {
if (current1 > nStart) {
current1--;
tvSony.setText(String.valueOf(current1));
}
}
sonyR = current1;
Log.i("sonyR ouput =", String.valueOf(sonyR));
Array, if value has been entered before, find the value and display it. if not make a new array value
private void sun32() {
ArrayList<Integer> sun32A = new ArrayList<Integer>();
if (sun32A.contains(sonyR)) {
sun32A.get(Integer.valueOf(sonyR));
tvSony.setText(sonyR);
} else {
tvSony.getText(Integer.valueOf(sonyR));<-----here is the error
sun32A.add(sonyR);
}
return;
}
EDIT : Just to confirm here is an image of the UI layout
One problem in your posted code is that getText() shouldn't take any arguments.
Also, TextView.getText() returns a CharSequence, not a String. You should convert it by doing toString() before calling Integer.valueOf(). Try this code and see if it works:
ArrayList<Integer> sun32A = new ArrayList<Integer>(); <---- Variable moved to outside of method.
private void sun32() {
if (sun32A.contains(sonyR)) {
// removed irrelevant code line
tvSony.setText(String.valueOf(sonyR)); <----- Convert the int to String before setting text.
} else {
int myInt = Integer.valueOf(tvSony.getText().toString()); <----- fixed code
sun32A.add(myInt);
}
return;
}

Categories

Resources