'How to display the last 5 calculations of calculator app?
I am developing calculation app in android. I want to display the last 5 calculation operations of my calculator in other activity on TextViews.
I can display the first one successfully by using Shared Preferences. But when I want display the second calculation operation it's displayed the same as the first one although the second operation is different.
How can I save every calculation operation when the button equals clicked?
the activity of last calculator operations
This method that I am used to display the first one.
private void setNumbersToSP(int times, String firstNum, String OP, String secondNum, String total) {
sp = this.getSharedPreferences("LastCalc", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("num1", firstNum).apply();
editor.putString("SecondNumber", secondNum).apply();
editor.putString("OP", OP).apply();
editor.putString("Total", total).apply();
}
The full code of LastCalc Activity
tvFirstNum = (TextView) findViewById(R.id.txtFirstNumber);
tvSecondNum = (TextView) findViewById(R.id.txtSecondNumber);
OP = (TextView) findViewById(R.id.txtOP);
Result = (TextView) findViewById(R.id.txtResult);
tvFirstNum2 = (TextView) findViewById(R.id.txtFirstNumber2);
tvSecondNum2 = (TextView) findViewById(R.id.txtSecondNumber2);
tvOP2 = (TextView) findViewById(R.id.txtOP2);
tvResult2 = (TextView) findViewById(R.id.txtResult2);
tvFirstNum.setText(sp.getString("num1", "0"));
OP.setText(sp.getString("OP", "+"));
tvSecondNum.setText(sp.getString("SecondNumber", "0"));
Result.setText(sp.getString("Total", "0"));
int times = sp.getInt("times", 0);
Toast.makeText(this, String.valueOf(times), Toast.LENGTH_LONG).show();
tvFirstNum2.setText(sp.getString("num1", "0"));
tvOP2.setText(sp.getString("OP", "+"));
tvSecondNum2.setText(sp.getString("SecondNumber", "0"));
tvResult2.setText(sp.getString("Total", "0"));
The main Activity full code.
// متغير لحغظ حالة مربع النص 0 = فارغ و 1 = يحتوي على قيمة
int clear_flag = 0;
// متفير لخفظ قيمة العلامة
String sign_flag = "";
// متغير لحفظ قيمة التوتال ليتم عرضها في كل مرة
Double total = 0.0;
// متغير لحفظ اخر زر تم الضغط عليه
int lastbutton = 0;
SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// تمهيد قيمة المربع النص
Textdisplay = (EditText) findViewById(R.id.edittext);
//تنظيف المربع النص
Textdisplay.setText("");
//حدث الضعط على مربع النص
Textdisplay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// دالة اخفاء لوحة المفاتيح ليتم ادخال الارقام من خلال الازار المخصصة لها
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(Textdisplay.getWindowToken(), 0);
}
});
// تمهيد قيمة الازرار
Button btn = (Button) findViewById(R.id.btnDot);
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
Button btn3 = (Button) findViewById(R.id.btn3);
Button btn4 = (Button) findViewById(R.id.btn4);
Button btn5 = (Button) findViewById(R.id.btn5);
Button btn6 = (Button) findViewById(R.id.btn6);
Button btn7 = (Button) findViewById(R.id.btn7);
Button btn8 = (Button) findViewById(R.id.btn8);
Button btn9 = (Button) findViewById(R.id.btn9);
Button btn0 = (Button) findViewById(R.id.btn0);
Button btnequal = (Button) findViewById(R.id.btnequal);
Button btnsubstraction = (Button) findViewById(R.id.btnsubstract);
Button btnmultiplction = (Button) findViewById(R.id.btnmulti);
Button btndivition = (Button) findViewById(R.id.btndiv);
Button btnaddtion = (Button) findViewById(R.id.btnaddtion);
Button btnclear = (Button) findViewById(R.id.btnclear);
//وضع احداث الازرار
btn.setOnClickListener(this);
btn0.setOnClickListener(this);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btnequal.setOnClickListener(this);
btnsubstraction.setOnClickListener(this);
btnmultiplction.setOnClickListener(this);
btndivition.setOnClickListener(this);
btnaddtion.setOnClickListener(this);
btnclear.setOnClickListener(this);
}
// دالة اظهار الرقم على مربع النص
public void showNum(String num) {
sp = this.getSharedPreferences("LastCalc", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
// اختبار قيمة مربع النص اذا قيمته 1 يجب تنظيفه قبل اظهار الرقم عليه ووضعه بصفر ليتم الكتابة عليه
if (clear_flag == 1) {
Textdisplay.setText("");
clear_flag = 0;
}
//اذا كان المدخل الرقم صفر اظهاره على مربع النص بصفر
else if (num.equals("0")) {
if (Textdisplay.getText().toString().equals("0")
|| Textdisplay.getText().toString().equals("")) {
Textdisplay.setText("0");
}
}
String num_current = Textdisplay.getText().toString() + num;
// دالة اظهار مربع النص ووضع قيمته القيمة الموجودة به + الرقم الذي تم ضغطه
Textdisplay.setText(num_current);
editor.putString("num1", Textdisplay.getText().toString()).apply();
}
// هنا تم عمل كائن من كلاس العمليات الحسابية
CalculatorOP cop = new CalculatorOP(MainActivity.this);
// دالة تحديد العلامة الحسابية
public void showSign(String sign) {
// اذا تم ضغط ازرار العمليات في البداية لا ينفذ شئ
if (lastbutton == R.id.btnmulti ||
lastbutton == R.id.btnsubstract ||
lastbutton == R.id.btndiv ||
lastbutton == R.id.btnaddtion) {
}
// يتم تنفيذ هذا الجزء اذا تم ضغط عملية حسابية بعد ضغط رقم معين
else {
// وضع المتغير بالرقم 1 يدل على ان مربع النص فيه محتوى حاليا
clear_flag = 1;
// تمهيد قيمة الرقم المدخل
Double newNumber = 0.0;
// ادخال الرقم الى حلقة try catch لتفادي حدوث اي استثناء -- غالبا ما يقع استثناء المربع الفارغ
try {
// دالة تحويل مربع النص الى رقم من النوع double
newNumber = Double.parseDouble(Textdisplay.getText().toString());
} catch (Exception e) {
// اظهار رسالة بان المربع فارغ اذا وقع الاستثناء
Toast.makeText(this, "Field is empty !!" + e, Toast.LENGTH_LONG).show();
}
// فحص قيمة الرقم المحول اذا كان قيمته فراغ يتم اظهار رسالة تخبره بذلك
if (String.valueOf(newNumber).equals("")) {
// الرسالة
Toast.makeText(this, "Field is empty !!", Toast.LENGTH_LONG).show();
}
// يتم تنفيذ هذا الجزء اذا تم الضغط على احد العمليات الحسابية
else {
if (sign_flag.equals("") || sign_flag.equals("=")) {
// اذا كانت العلامة زر يساوي يتم جعل الرقم المدخل هو التوتال
total = newNumber;
// هنا يتم عرض التوتال
Textdisplay.setText(total.toString());
} else if (sign_flag.equals("+")) {
// اذا كانت العلامة زر زائد يتم جمع التوتال عن طريق الدالة من كلاس العمليات وعرضه في مربع النص
Textdisplay.setText(String.valueOf(cop.getSum(total, newNumber)));
} else if (sign_flag.equals("-")) {
// اذا كانت العلامة زر ناقص يتم طرح الرقم المدخل من التوتال عن طريق الدالة من كلاس العمليات وعرضه في مربع النص
Textdisplay.setText(String.valueOf(cop.getSub(total, newNumber)));
} else if (sign_flag.equals("*")) {
// اذا كانت العلامة زر الضرب يتم ضرب التوتال في الرقم المدخل عن طريق الدالة من كلاس العمليات وعرضه في مربع النص
Textdisplay.setText(String.valueOf(cop.getMul(total, newNumber)));
} else if (sign_flag.equals("/")) {
// اذا كانت العلامة زر القسمة يتم قسمة التوتال على الرقم المخل عن طريق الدالة من كلاس العمليات وعرضه في مربع النص
Textdisplay.setText(String.valueOf(cop.getDiv(total, newNumber)));
}
}
}
// تغير قيمة العلامة الحسابية الى العلامة التي تم ضغطها
sign_flag = sign;
}
int times = 1;
// دالة تنفيذ احداث الازرار
@Override
public void onClick(View v) {
sp = this.getSharedPreferences("LastCalc", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
// يتم تنفيذ هذا القسم اذا تم الضغط على زر الفاصلة العشرية
if (v.getId() == R.id.btnDot) {
// يتم فحص قيمة مربع النص
if (clear_flag == 1) {
// تنظيفه اذا كانت القيمة 1
Textdisplay.setText("");
// ووضعه في حالة الفراغ
clear_flag = 0;
}
// يتم اختبار موفع الفاصلة العشرية
else if (Textdisplay.getText().toString().indexOf(".") <= 0) {
// اذا تحقق الشرط يتم جلب الرقم
// اذا كان موقعها ال index الخاص به اكبر من او يساوي الصفر يتم جلب الرقم ووضع الفاصلة في اقصلا يمينه
Textdisplay.setText(Textdisplay.getText() + ".");
}
} else if (v.getId() == R.id.btn0) {
// اذا تم الضغط على الزر صفر يتم ارساله الى الدالة showNum لتظهره في مربع النص
showNum("0");
} else if (v.getId() == R.id.btn1) {
// اذا تم الضغط على الزر 1 يتم ارساله الى الدالة showNum لتظهره في مربع النص
showNum("1");
} else if (v.getId() == R.id.btn2) {
// اذا تم الضغط على الزر 2 يتم ارساله الى الدالة showNum لتظهره في مربع النص
showNum("2");
} else if (v.getId() == R.id.btn3) {
// اذا تم الضغط على الزر 3 يتم ارساله الى الدالة showNum لتظهره في مربع النص
showNum("3");
} else if (v.getId() == R.id.btn4) {
// اذا تم الضغط على الزر 4 يتم ارساله الى الدالة showNum لتظهره في مربع النص
showNum("4");
} else if (v.getId() == R.id.btn5) {
// اذا تم الضغط على الزر 5 يتم ارساله الى الدالة showNum لتظهره في مربع النص
showNum("5");
} else if (v.getId() == R.id.btn6) {
// اذا تم الضغط على الزر 6 يتم ارساله الى الدالة showNum لتظهره في مربع النص
showNum("6");
} else if (v.getId() == R.id.btn7) {
// اذا تم الضغط على الزر 7 يتم ارساله الى الدالة showNum لتظهره في مربع النص
showNum("7");
} else if (v.getId() == R.id.btn8) {
// اذا تم الضغط على الزر 8 يتم ارساله الى الدالة showNum لتظهره في مربع النص
showNum("8");
} else if (v.getId() == R.id.btn9) {
// اذا تم الضغط على الزر 9 يتم ارساله الى الدالة showNum لتظهره في مربع النص
showNum("9");
} else if (v.getId() == R.id.btnaddtion) {
// اذا تم الضغط على زر الجمع يتم ارساله الى الدالة showSign لتنفيذ عملية الجمع
showSign("+");
} else if (v.getId() == R.id.btnsubstract) {
// اذا تم الضغط على زر الطرخ يتم ارساله الى الدالة showSign لتنفيذ عملية الطرح
showSign("-");
} else if (v.getId() == R.id.btndiv) {
// اذا تم الضغط على زر القسمة يتم ارساله الى الدالة showSign لتنفيذ عملية القسمة
showSign("/");
} else if (v.getId() == R.id.btnmulti) {
// اذا تم الضغط على زر الضرب يتم ارساله الى الدالة showSign لتنفيذ عملية الضرب
showSign("*");
} else if (v.getId() == R.id.btnequal) {
// اذا تم الضغط على زر يساوي يتم حساب العملية واظهار الناتجٍ
// تم تعريف متغير newNumber ليتم تخزين قيمة الرقم المدخل
Double newNumber = 0.0;
// تم تعريف متغير currentValue ليتم تخزين قيمة الرقم الموجود مسبقا على مربع النص
String currentValue = Textdisplay.getText().toString();
if (currentValue.trim().equals("")) {
// اذا كان الرقم الموجود مسبقا على مربع النص فراغ يتم وضع الرقم المدخل بصفر
newNumber = Double.parseDouble("0");
// اضافة الرقم المدخل الى التوتال
total = total + newNumber;
// عرض التوتال في مربع النص
Textdisplay.setText(total.toString());
}
try {
// ادخال الرقم المدخل الى حلقة try catch لتفادي حدوث اي استثناء -- غالبا ما يقع استثناء المربع الفارغ
newNumber = Double.parseDouble(currentValue.toString());
} catch (Exception e) {
}
if (String.valueOf(newNumber).equals("")) {
// اذا كان الرقم المدخل يساوي فراغ لا يتم تنفيذ شئ
} else {
if (sign_flag.equals("+")) {
editor.putInt("times", times).apply();
// في حالة الضفط على يساوي وكانت العملية جمع يتم جمع الناتج هنا
String stTotalBeforeOP = String.valueOf(total);
total = total + newNumber;
String stSecondNumber = String.valueOf(newNumber);
String stTotalAfterOP = String.valueOf(total);
setNumbersToSP(times, stTotalBeforeOP, "+", stSecondNumber, stTotalAfterOP);
times++;
//وهنا يتم عرضه على مربع النص
Textdisplay.setText(total.toString());
}
if (sign_flag.equals("-")) {
// في حالة الضفط على يساوي وكانت العملية طرح يتم طرح الناتج هنا
String stFirstNumber = String.valueOf(newNumber);
total = total - newNumber;
String stTotal = String.valueOf(total);
editor.putString("Total", stTotal).apply();
editor.putString("OP", "-").apply();
editor.putString("FirstNumber", stFirstNumber).apply();
//وهنا يتم عرضه على مربع النص
Textdisplay.setText(total.toString());
}
if (sign_flag.equals("*")) {
// في حالة الضفط على يساوي وكانت العملية ضرب يتم ضرب الناتج هنا
total = total * newNumber;
String stFirstNumber = String.valueOf(newNumber);
String stTotal = String.valueOf(total);
editor.putString("Total", stTotal).apply();
editor.putString("OP", "*").apply();
editor.putString("FirstNumber", stFirstNumber).apply();
//وهنا يتم عرضه على مربع النص
Textdisplay.setText(total.toString());
}
if (sign_flag.equals("/")) {
// في حالة الضفط على يساوي وكانت العملية قسمة يتم قسمة الناتج هنا
// يتم التحقق من عدم وجود الصفر كمقسوم عليه
if (newNumber == 0) {
// اظهار رسالة توضح ذلك
Toast.makeText(this, "Cannot Div by Zero !!", Toast.LENGTH_LONG).show();
// وضع مربع النص فراغ
Textdisplay.setText("");
} else {
// اذا الرقم لا يساوي الصفر تتم عملية القسمة هنا
total = total / newNumber;
//وهنا يتم عرض ناتج القسمة على مربع النص
editor.putString("OP", "/").apply();
Textdisplay.setText(total.toString());
}
}
}
// هنا يتم تغيير قيمة العلامة الى علامة يساوي
sign_flag = "=";
} else if (v.getId() == R.id.btnclear) {
//اذا تم الضغط على زر التنظيف يتم مسح كل المحتوى
Textdisplay.setText("");
}
// هنا يتم تغيرر قيمة lastbutton الى الزر الذي تم ضغطه في الاخر
lastbutton = v.getId();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemID = item.getItemId();
if (itemID == R.id.last) {
startActivity(new Intent(MainActivity.this, Last5Calc.class));
}
return super.onOptionsItemSelected(item);
}
private void setNumbersToSP(int times, String firstNum, String OP, String secondNum, String total) {
sp = this.getSharedPreferences("LastCalc", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("num1", firstNum).apply();
editor.putString("SecondNumber", secondNum).apply();
editor.putString("OP", OP).apply();
editor.putString("Total", total).apply();
}
}
Solution 1:[1]
It is clear now,
editor.putString("num1", firstNum).apply();
editor.putString("SecondNumber", secondNum).apply();
editor.putString("OP", OP).apply();
editor.putString("Total", total).apply();`
As you can see above in your code, you only have one "Total" but you are expecting two different results. It doesn't work like that, as you are updating "num1", "SecondNumber", "OP", and "Total" with the last result by overriding the previous result.
You need to have separate key-value for each different result or use different ways of sharing values between activities like intents.
Solution 2:[2]
Each time you write to num1 with editor.putString("num1", firstNum).apply();, you actually overwrite a previous value. That's why when you read from num1 like this tvFirstNum2.setText(sp.getString("num1", "0"));, you get only the last value. Same apply to other fields OP, SecondNumber, Total.
If you don't have a requirement to save previous calculation between app runs, you can use some static or singleton class to store them:
public class Calculation
{
public String FirstNumber;
public String Operation;
public String SecondNumber;
public String Total;
}
public class CalculationHistory
{
public final static CalculationHistory Instance = new CalculationHistory();
public final ArrayList<Calculation> History = new ArrayList<Calculation>();
}
To save latest calculation use
Calculation latestCalculation = new Calculation();
latestCalculation.FirstNumber = firstNum;
latestCalculation.Operation = OP;
latestCalculation.SecondNumber = secondNum;
latestCalculation.Total = total;
CalculationHistory.Instance.History.add(0, latestCalculation);
And to read it later use
Calculation latestCalculation = CalculationHistory.Instance.History.get(0);
This data won't survive if the app was closed and reopened. If you need to persist data between app runs, you have to save calculations history to a database.
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 | MoGa |
| Solution 2 |
