Display shared preference in textview - java

I'm trying to make a simple calculator app and want the final calculation result to not disappear once the app closes.
I can get the numbers that are inputted by the user to stay in place and the result is calculated correctly, however once the app closes the result disappears?!
Any help would be much appreciated!!
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.calculator);
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
editText3.setText(prefs.getString("autoSave", ""));
editText4.setText(prefs.getString("autoSave1", ""));
editText6.setText(prefs.getString("autoSave2", ""));
editText8.setText(prefs.getString("autoSave3", ""));
editText3.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textViewResult.setText(addNumbers());
}
public void afterTextChanged(Editable s)
{
prefs.edit().putString("autoSave", s.toString()).commit();
}
});
editText4.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textViewResult.setText(addNumbers());
}
public void afterTextChanged(Editable s)
{
prefs.edit().putString("autoSave1", s.toString()).commit();
}
});
editText6.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textViewResult.setText(addNumbers());
}
public void afterTextChanged(Editable s)
{
prefs.edit().putString("autoSave2", s.toString()).commit();
}
});
editText8.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textViewResult.setText(addNumbers());
}
public void afterTextChanged(Editable s)
{
prefs.edit().putString("autoSave3", s.toString()).commit();
}
});
}
private String addNumbers() {
int number1;
int number2;
int number3;
int number4;
if (editText3.getText().toString() != "" && editText3.getText().length() > 0) {
number1 = Integer.parseInt(editText3.getText().toString());
} else {
number1 = 0;
}
if (editText4.getText().toString() != "" && editText4.getText().length() > 0) {
number2 = Integer.parseInt(editText4.getText().toString());
} else {
number2 = 0;
}
if (editText6.getText().toString() != "" && editText6.getText().length() > 0) {
number3 = Integer.parseInt(editText6.getText().toString());
} else {
number3 = 0;
}
if (editText8.getText().toString() != "" && editText8.getText().length() > 0) {
number4 = Integer.parseInt(editText8.getText().toString());
} else {
number4 = 0;
}
int sum = (number1 * 2) + (number2 * 4) + (number3 * 2) + (number4 * 2);
if (sum > 6) sum = 6;
return sum + "";
} }

Try this,
First, save your result to preferences in addNumbers method using
prefs.edit().putString("result", sum.toString()).commit();
See the Changes to your addNumbers method below-:
private String addNumbers() {
int number1;
int number2;
int number3;
int number4;
if (editText3.getText().toString() != "" && editText3.getText().length() > 0) {
number1 = Integer.parseInt(editText3.getText().toString());
} else {
number1 = 0;
}
if (editText4.getText().toString() != "" && editText4.getText().length() > 0) {
number2 = Integer.parseInt(editText4.getText().toString());
} else {
number2 = 0;
}
if (editText6.getText().toString() != "" && editText6.getText().length() > 0) {
number3 = Integer.parseInt(editText6.getText().toString());
} else {
number3 = 0;
}
if (editText8.getText().toString() != "" && editText8.getText().length() > 0) {
number4 = Integer.parseInt(editText8.getText().toString());
} else {
number4 = 0;
}
int sum = (number1 * 2) + (number2 * 4) + (number3 * 2) + (number4 * 2);
if (sum > 6) sum = 6;
prefs.edit().putString("result", sum.toString()).commit();
return sum + "";
}
}
Where result is your key. so to get the value which you have stored you can use prefs with the same key like
prefs.getString("result","");
Get the value from preference in onCreate and set this value to your TextView. See the sample code below
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.calculator);
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
String result= prefs.getString("result",""); //where "" is your default value
if(!result.equals("") && !result.isEmpty()){
textViewResult.setText(addNumbers());
}
/*other code*/

You can save your result where you are showing the calculated result to the text view, then you'll get what you save and what you show to the user

Initialize your SharedPreference as follows,
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);

You can do this like bellow..
Create a method to save SharedPreferences
private void savePreferences(String key, String value) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
Save value to method like
savePreferences("autosave", s.toString());
View data form from SharedPreferences , Create another method like
private void loadSavedPreferences() {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
String autosave = sp.getString("autosave", "");
editText3.setText(autosave);
}
Call loadSavedPreferences method in oncreate mehtod in activity & enjoy it...
Thanks...

Related

EditText cannot delete manually in Android java

I've been confused why my EditText can't delete my text manually.When I tried to scan the image that converts to text and display the text to editText or OCR sometimes I have this bugs, sometimes only 3 numbers will type instead of 23, and sometimes it runs smoothly, why did this happen? I have sample image below which can't delete the whole text displayed on EdiText manually, can anyone help me with this issue? I can't find the error yet since it just rarely appears, thanks in advance.
Java file
private int prevCount = 0;
// to have space after 4 number
private boolean isAtSpaceDelimiter(int currCount) {
return currCount == 4 ||currCount == 9 || currCount == 14 || currCount == 19;
}
//declared on onCreate()
scannedCardNumber(edt_card_number_inputted,til_card_number_inputted);
public void scannedCardNumber(EditText card_number , TextInputLayout tilCard){
card_number.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
String cardNumber = card_number.getText().toString();
if(s.toString().length() != 23){
tilCard.setError(required_field);
}
else if(!cardNumber.matches("[0-9 ]+")) {
tilCard.setError("Invalid Format");
}
else{
tilCard.setError(null);
}
}
#Override
public void afterTextChanged(Editable editable) {
String field = editable.toString();
int currCount = field.length();
if (shouldIncrementOrDecrement(currCount, true)){
appendOrStrip(field, true);
} else if (shouldIncrementOrDecrement(currCount, false)) {
appendOrStrip(field, false);
}
prevCount = card_number.getText().toString().length();
}
});
}
private void appendOrStrip(String field, boolean shouldAppend) {
StringBuilder sb = new StringBuilder(field);
if (shouldAppend) {
sb.append(" ");
} else {
sb.setLength(sb.length() - 1);
}
edt_card_number_inputted.setText(sb.toString());
edt_card_number_inputted.setSelection(sb.length());
}
private boolean shouldIncrementOrDecrement(int currCount, boolean shouldIncrement) {
if (shouldIncrement) {
return prevCount <= currCount && isAtSpaceDelimiter(currCount);
} else {
return prevCount > currCount && isAtSpaceDelimiter(currCount);
}
}

How can I modify the input of multiple EditTexts at the same time, as I only modify one?

I have multiple EditTexts and I want to change the input of all of them at the same time, as I modify only one.(all of them take decimal numbers as input)
I stored the EditTexts in an array named 'editTexts'.
Here's what I tried
//Set the listener for each element
for (int i=0; i<editTexts.length; i++) {
final int finalI = i;
editTexts[i].addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//if the editText which is currently edited is empty, set the input for all the rest to be '0.0'
if (editTexts[finalI].getText().toString().trim().length() == 0) {
for(EditText e : editTexts) {
if (e == editTexts[finalI])
continue;
e.setText("0.0");
}
} else {
float no = Float.parseFloat(s.toString() + "");
//Set the input of all the other editTexts to be the decimal number entered, multiplied by 2
for(EditText e : editTexts){
if(e == editTexts[finalI])
continue;
e.setText(no*2+"");
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
})
}
In this case the multiplication coefficient is just an example, it's not always gonna be 2. I used it just to test it out.
For some reason, when I change the input value, the app freezes.
Any help? Thanks!
Use LiveData to store your user input values.
Once it's value changes you can set value to each EditText. I think it is an easy way to implement.
Try it like this:
// et_x1, et_x2 and et_x3 are ids of EditTexts
//set inputType for all EditTexts as numberDecimal
EditText editText1 = findViewById(R.id.et_x1);
final EditText editText2 = findViewById(R.id.et_x2);
final EditText editText3 = findViewById(R.id.et_x3);
editText1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String value = s.toString();
double x;
if (!value.equals("")) {
x = Double.parseDouble(value);
} else {
x = 0.0;
}
editText2.setText(Editable.Factory.getInstance().newEditable((String.valueOf(Math.pow(x, 2)))));
editText3.setText(
Editable.Factory.getInstance().newEditable((String.valueOf(Math.pow(x, 3)))));
}
#Override
public void afterTextChanged(Editable s) {
}
});
Hope it helps you!

How to delete masked edittext content

for example: "2020/55" I have an edittext shape, put one after 4 numbers, write a number after it and it works well. My problem starts at the time of deleting. When deleting the part after /, it shows"/////" the figures of the part before / as and instead.I add your picture, how can I delete it.
enter image description here
And mask class
public class CaseInputMask implements TextWatcher {
int uzunluk = 0;
EditText girilenMetin;
public CaseInputMask(EditText girilenMetin) {
this.girilenMetin = girilenMetin;
this.girilenMetin.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String metin = girilenMetin.getText().toString();
uzunluk = metin.length();
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
try {
String metin = charSequence.toString();
String girilenDeger = girilenMetin.getText().toString();
if (girilenDeger.length() == 4) {
metin += '/';
girilenMetin.setText(metin);
girilenMetin.setSelection(metin.length());
}
} catch (Exception e) {
}
}
#Override
public void afterTextChanged(Editable editable) {
}
}
You should check deletion like this:
public class CaseInputMask implements TextWatcher {
private boolean running = false;
private boolean deleting = false;
private final String inputMask = "####/##";
public CaseInputMask() {
}
#Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
deleting = count > after;
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable editable) {
if (running || deleting) {
return;
}
running = true;
int length = editable.length();
if (length < inputMask.length()) {
if (inputMask.charAt(length) != '#') {
editable.append(inputMask.charAt(length));
} else if (inputMask.charAt(length-1) != '#') {
editable.insert(length-1, inputMask, length-1, length);
}
}
running = false;
}
}
And
girilenMetin.addTextChangedListener(new CaseInputMask())

Overwrite text in EditText that has only 1 char is not working

I have multiple EditText views , each EditText view can contain only 1 char.
I need to make this rule - if I focus on one EditText , and it already has some text inside - then overwrite it . Also - if I press on delete key - I need the text to be cleared inside that view.
Then - I am checking if the EditText views has 1 empty cell - if not - checking if the EditText views has the correct letters.
I could have managed to make the clear button work, but I can not make the overwrite.
I did tried to use the TextWatcher , but it didn't work for me.
The EditText views are created dynamically .
Here is my code :
Answer.java
public class Answer {
String answer;
int answer_length;
int cell_margin=10;
int cell_size=180;
EditText[] EditTextArray;
public Answer(RelativeLayout rLayout1, Context context , String answer) {
this.answer = answer;
answer_length = answer.length();
if (answer_length>6){
cell_margin = 4;
cell_size = 110;
}
EditTextArray = new EditText[answer_length];
AnswerCell EditTextToSeeFirst = new AnswerCell(context,cell_size);
setListener(EditTextToSeeFirst);
EditTextArray[0] = EditTextToSeeFirst;
RelativeLayout.LayoutParams fparams = new RelativeLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
fparams.setMargins(cell_margin,0,cell_margin,0);
rLayout1.addView(EditTextToSeeFirst, fparams);
for (int i = 1; i<answer_length ; i++){
RelativeLayout.LayoutParams lparams = new RelativeLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lparams.addRule(RelativeLayout.LEFT_OF, EditTextArray[i-1].getId());
lparams.setMargins(cell_margin,0,cell_margin,0);
AnswerCell newEditText = new AnswerCell(context,cell_size);
setListener(newEditText);
EditTextArray[i] = newEditText;
rLayout1.addView(EditTextArray[i], lparams);
}
rLayout1.setGravity(Gravity.CENTER );
}
public void setListener(AnswerCell ac){
ac.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("test","test");
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
goToNextAvailableCell();
}
});
}
public void goToNextAvailableCell(){
for (int i = 0; i<answer_length ; i++) {
if(EditTextArray[i].getText().toString().matches("")){
EditTextArray[i].requestFocus();
return;
}
}
//Did not found empty cell
checkCorrectAnswer();
}
private void checkCorrectAnswer(){
String tryAnswer = "";
for (int i = 0; i<answer_length ; i++) {
tryAnswer += EditTextArray[i].getText().toString();
}
if (tryAnswer.matches(answer)){
Log.d("Correct !!","Correct Answer");
}
}
}
AnswerCell.java
public class AnswerCell extends EditText{
public AnswerCell(final Context context, int cell_size) {
super(context);
this.setId(View.generateViewId());
this.setBackgroundResource(R.color.answerCellBackground);
this.setHeight(cell_size);
this.setWidth(cell_size);
this.setFilters(new InputFilter[] {new InputFilter.LengthFilter(1)});
this.setCursorVisible(false);
this.setGravity(Gravity.CENTER);
this.setOnFocusChangeListener( new View.OnFocusChangeListener(){
public void onFocusChange( View view, boolean hasfocus){
if(hasfocus){
view.setBackgroundResource( R.drawable.answer_cell_has_focus);
}
else{
view.setBackgroundResource( R.drawable.answer_cell_lost_focus);
}
}
});
this.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
//You can identify which key pressed buy checking keyCode value with KeyEvent.KEYCODE_
if(keyCode == KeyEvent.KEYCODE_DEL) {
((EditText)v).setText("");
return true;
}
return false;
}
});
}
}
thanks !
It will work with this code
TextWatcher watcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//YOUR CODE
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//YOUR CODE
}
#Override
public void afterTextChanged(Editable s) {
String outputedText = s.toString();
// mOutputText.setText(outputedText);
}
};
Then add this in oncreate
mInputText.addTextChangedListener(watcher);
e2.addTextChangedListener(watcher);
e3.addTextChangedListener(watcher);
e4.addTextChangedListener(watcher);

Load Error - Java

I used that to limit the editText numbers:
n1.setFilters(new InputFilter[] {
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 3, afterDecimal = 1;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = n1.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
}
else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
And that to load the saved number:
public void car(View v)
{
AlertDialog.Builder car = new AlertDialog.Builder(this);
car.setIcon(R.drawable.ic_launcher);
car.setTitle("Carregar");
car.setMessage(R.string.car);
car.setPositiveButton("Sim", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface p1, int p2)
{
Toast.makeText(getApplicationContext(), "Notas e pesos carregados", Toast.LENGTH_SHORT).show();
prefs = getSharedPreferences("Notas_Salvas", MODE_PRIVATE);
nota1.setText(prefs.getString("NOTA1","."));
nota2.setText(prefs.getString("NOTA2",""));
nota3.setText(prefs.getString("NOTA3",""));
nota4.setText(prefs.getString("NOTA4","."));
nota5.setText(prefs.getString("NOTA5",""));
peso1.setText(prefs.getString("PESO1",""));
peso2.setText(prefs.getString("PESO2",""));
peso3.setText(prefs.getString("PESO3",""));
peso4.setText(prefs.getString("PESO4",""));
peso5.setText(prefs.getString("PESO5",""));
}
});
car.setNegativeButton("Não", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface p1, int p2)
{
Toast.makeText(getApplicationContext(), "Notas carregadas", Toast.LENGTH_SHORT).show();
prefs = getSharedPreferences("Notas_Salvas", MODE_PRIVATE);
nota1.setText(prefs.getString("NOTA1",""));
nota2.setText(prefs.getString("NOTA2",""));
nota3.setText(prefs.getString("NOTA3",""));
nota4.setText(prefs.getString("NOTA4",""));
nota5.setText(prefs.getString("NOTA5",""));
}
});
car.show();
}
But when will load the saved number the editText doesn't load with the first click, he just delete the number existing. Then with the second click he load the numbers.
How to solve this?

Categories