'How to convert a arraylist <String> to arrayList <Integer> and Calculate the values of Integers on it?
How i am supposed to calculate ArrayList String from Listview values into ArrayList Integer and back to Listview, Because i've been making a application for Android that calculates the Listview items which is from ArrayList. This is one bugs me out of the most, it shows the last arrayList value to textView, not Calculating them
public class Menu extends AppCompatActivity {
public FloatingActionButton fab1, fab2, fab3;
public Animation fab_open, fab_close, rotate_cw, rotate_ccw;
public EditText editText, editText2, editText3, editText4;
public TextView textView1;
public ListView listView;
public ArrayList<String> arrayList;
public ArrayAdapter<String> arrayAdapter;
public boolean isOpen = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
fab1 = findViewById(R.id.fab_1);
fab2 = findViewById(R.id.fab_2);
fab3 = findViewById(R.id.fab_3);
textView1 = findViewById(R.id.info_text4);
listView = findViewById(R.id.listview_items);
fab_open = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_close);
rotate_cw = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_cw);
rotate_ccw = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_ccw);
loadData();
calculate();
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
fab1.setOnClickListener(view -> {
if (isOpen) {
fab2.startAnimation(fab_close);
fab3.startAnimation(fab_close);
fab1.startAnimation(rotate_cw);
fab2.setClickable(true);
fab3.setClickable(true);
isOpen = false;
} else {
fab2.startAnimation(fab_open);
fab3.startAnimation(fab_open);
fab1.startAnimation(rotate_ccw);
fab2.setClickable(true);
fab3.setClickable(true);
isOpen = true;
}
});
// Budget
fab2.setOnClickListener(view -> {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Budget");
builder.setIcon(R.drawable.ic_wallet_budget);
final View customLayout = getLayoutInflater().inflate(R.layout.add_budget_popup, null);
builder.setView(customLayout);
builder.setPositiveButton("OK", (dialog, which) -> {
// Budget Name
editText = customLayout.findViewById(R.id.editText);
// Budget Input
editText2 = customLayout.findViewById(R.id.editText2);
// Conditional Statements
if(TextUtils.isEmpty(editText.getText().toString()) && TextUtils.isEmpty(editText2.getText().toString())) {
Toast toast = Toast.makeText(getApplicationContext(), "No Budget Name Data and No Budget Data been added", Toast.LENGTH_SHORT);
toast.show();
} else if(TextUtils.isGraphic(editText.getText().toString()) && TextUtils.isEmpty(editText2.getText().toString())){
Toast toast = Toast.makeText(getApplicationContext(), "Budget Name Data has a input, but No Budget Data input", Toast.LENGTH_SHORT);
toast.show();
} else if(TextUtils.isEmpty(editText.getText().toString()) && TextUtils.isDigitsOnly(editText2.getText().toString())){
Toast toast = Toast.makeText(getApplicationContext(), "Budget Data input has a input, but No Budget Name Data input", Toast.LENGTH_SHORT);
toast.show();
} else {
arrayList.add(editText2.getText().toString());
arrayAdapter.notifyDataSetChanged();
Toast toast = Toast.makeText(getApplicationContext(), "Budget Data Added", Toast.LENGTH_SHORT);
toast.show();
saveData();
}
});
AlertDialog dialog = builder.create();
dialog.show();
dialog.setCancelable(false);
});
// Expense
fab3.setOnClickListener(view -> {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Expense");
builder.setIcon(R.drawable.ic_money_exp);
final View customLayout = getLayoutInflater().inflate(R.layout.add_expense_popup, null);
builder.setView(customLayout);
builder.setPositiveButton("OK", (dialog, which) -> {
// Expense Name
editText3 = customLayout.findViewById(R.id.editText3);
// Expense Input
editText4 = customLayout.findViewById(R.id.editText4);
// Conditional Statements
if(TextUtils.isEmpty(editText3.getText().toString()) && TextUtils.isEmpty(editText4.getText().toString())) {
Toast toast = Toast.makeText(getApplicationContext(), "No Expense Name Data and No Expense Data been added", Toast.LENGTH_SHORT);
toast.show();
} else if(TextUtils.isGraphic(editText3.getText().toString()) && TextUtils.isEmpty(editText4.getText().toString())){
Toast toast = Toast.makeText(getApplicationContext(), "Expense Name Data has a input, but No Expense Data input", Toast.LENGTH_SHORT);
toast.show();
} else if(TextUtils.isEmpty(editText3.getText().toString()) && TextUtils.isDigitsOnly(editText4.getText().toString())){
Toast toast = Toast.makeText(getApplicationContext(), "Expense Data input has a input, but No Expense Name Data input", Toast.LENGTH_SHORT);
toast.show();
} else {
arrayList.add(editText4.getText().toString());
arrayAdapter.notifyDataSetChanged();
Toast toast = Toast.makeText(getApplicationContext(), "Expense Data Added", Toast.LENGTH_SHORT);
toast.show();
saveData();
}
});
AlertDialog dialog = builder.create();
dialog.show();
dialog.setCancelable(false);
});
}
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("SHAREDPREFS", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString("Test", json);
editor.apply();
}
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("SHAREDPREFS", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("Test", null);
Type type = new TypeToken<ArrayList<String>>(){}.getType();
arrayList = gson.fromJson(json, type);
if(arrayList == null){
arrayList = new ArrayList<>();
}
}
private void calculate(){
for (int i = 0; i < arrayList.size(); i++) {
textView1.setText(String.valueOf(arrayList.get(i)));
}
}
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu){
getMenuInflater().inflate(R.menu.list, menu);
return true;
}
@SuppressLint("NonConstantResourceId")
@Override
public boolean onOptionsItemSelected(MenuItem items){
switch (items.getItemId()){
case R.id.items:
// Email Feedback System
Intent intent=new Intent(Intent.ACTION_SEND);
String[] recipients={"[email protected]"};
intent.putExtra(Intent.EXTRA_EMAIL, recipients);
intent.putExtra(Intent.EXTRA_SUBJECT,"Subject text here...");
intent.putExtra(Intent.EXTRA_TEXT,"Body of the content here...");
intent.putExtra(Intent.EXTRA_CC,"[email protected]");
intent.setType("text/html");
intent.setPackage("com.google.android.gm");
startActivity(Intent.createChooser(intent, "Send mail"));
case R.id.items3:
// About App
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About");
builder.setIcon(R.drawable.ic_baseline_info_24);
builder.setMessage("Our app allows you to monitor and categorize your expenses across different bank and investment accounts and credit cards, our app also offer budgeting tools, credit monitoring, mileage tracking, receipt keeping, and advice to grow your net worth.");
builder.setCancelable(false);
builder.setPositiveButton("Close", (dialog, id) -> dialog.cancel());
AlertDialog alert = builder.create();
alert.show();
default:
return super.onOptionsItemSelected(items);
}
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this).
setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage("Are you sure you want to close app?")
.setPositiveButton("Yes", (dialog, which) -> finish())
.setNegativeButton("No", null)
.show();
}
}
That is my problem, is there wrong on my code?
Solution 1:[1]
The problem is in this function
private void calculate(){
for (int i = 0; i < arrayList.size(); i++) {
textView1.setText(String.valueOf(arrayList.get(i)));
}
}
You are looping through the array list and setting the text to each array list entry in sequence. That means it will override whatever text was there before and end up just showing the last entry. If your array list was ["1","2","3"] this would be the same as calling
testView1.setText("1");
testView1.setText("2"); // overrides the "1"
testView1.setText("3"); // overrides the "2"
// ends with it showing "3"
If you want to show the sum of all the array entries you should first calculate the sum, then show it, like this:
private void calculate() {
// first calculate the total
int total = 0;
for (int i = 0; i < arrayList.size(); i++) {
total += Integer.parseInt(arrayList.get(i));
}
// then display it
textView1.setText(String.valueOf(total));
}
If any of the numbers in the array list are not integers, this will throw a NumberFormatException when you call parseInt, so if that is a possibility you should add some exception handling
private void calculate() {
int total = 0;
for (int i = 0; i < arrayList.size(); i++) {
try {
total += Integer.parseInt(arrayList.get(i));
} catch( NumberFormatException e) {
e.printStackTrace();
}
}
textView1.setText(String.valueOf(total));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tyler V |
