I have a simple shop activity which uses SharedPreferences to store various data. The problem is that when I click on purchase, I can purchase it multiple times and each time it takes the money from the coins value away. Please help me with this.
This is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getActionBar().hide();
setContentView(R.layout.shop_layout);
ImageButton lives = (ImageButton) findViewById(R.id.lives);
final Button hardmode = (Button) findViewById(R.id.hardmode);
final Button reversedMode = (Button) findViewById(R.id.reversedmode);
final SharedPreferences shop = getSharedPreferences("Shop", Context.MODE_PRIVATE);
final int[] livesPrice = {shop.getInt("livesPrice", 10)};
final int[] hardmodePrice = {shop.getInt("hardmodePrice", 15)};
final int[] reversedModePrice = {shop.getInt("reverseModePrice", 20)};
final int[] coins = {shop.getInt("money", 10000)};
final boolean[] hardmodeBoolean = {shop.getBoolean("hardmode", false)};
final boolean[] reversedModeBoolean = {shop.getBoolean("reversedMode", false)};
if(hardmodeBoolean[0]){
hardmode.setText("Purchased");
}
if(reversedModeBoolean[0]){
reversedMode.setText("Purchased");
}
TextView price1 = (TextView) findViewById(R.id.price1);
final TextView money = (TextView) findViewById(R.id.money);
Typeface tf = Typeface.createFromAsset(getAssets(), "font/cricket.ttf");
price1.setTypeface(tf);
price1.setText("=" + livesPrice[0]);
money.setTypeface(tf);
money.setText("Coins " + String.valueOf(coins[0]));
lives.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (coins[0] >= livesPrice[0]) {
coins[0] = coins[0] - livesPrice[0];
livesPrice[0] = livesPrice[0] + 10;
int numberOfLives = shop.getInt("numberOfLives", 1);
numberOfLives = numberOfLives + 1;
SharedPreferences.Editor editor = shop.edit();
editor.putInt("numberOfLives", numberOfLives);
editor.putInt("money", coins[0]);
editor.commit();
money.setText("Coins " + String.valueOf(coins[0]));
}
}
});
hardmode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = shop.edit();
if (coins[0] >= hardmodePrice[0]) {
coins[0] = coins[0] - hardmodePrice[0];
editor.putBoolean("hardmode", true);
editor.putInt("hardmodePrice", 0);
editor.putInt("money", coins[0]);
editor.apply();
money.setText("Coins " + String.valueOf(coins[0]));
hardmode.setText("Purchased");
hardmodeBoolean[0] = shop.getBoolean("hardmode", true);
}
}
});
reversedMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = shop.edit();
if (coins[0] >= reversedModePrice[0]) {
coins[0] = coins[0] - reversedModePrice[0];
editor.putBoolean("reversedMode", true);
editor.putInt("reversedModePrice", 0);
editor.putInt("money", coins[0]);
editor.apply();
money.setText("Coins " + String.valueOf(coins[0]));
reversedMode.setText("Purchased");
reversedModeBoolean[0] = shop.getBoolean("reversedMode", true);
}
}
});
}
try changing
coins[0] = coins[0] - livesPrice[0];
To
coins[0] -= livesPrice[0] ;
Related
i am creating an app in which different payments modes are there so for card payments and cheque payments i have created two different activities in which i am getting details from user and save the data into shared Preferences and then app returns back to the activities where other details are also there and then user can save the data on a button click.This data gets saved into Sqlite Database.
My problem is when i am selecting card payment its getting stored properly but the same value also getting stored at cheque No aswell into the sqlite database.Inshort the value of card payment is getting copied into cheque no column by default.
below is my code for Card payment Activity :
public class CardNo extends Activity {
String bankname;
String cardno;
int chq;
TextView textView1, textView2;
EditText editText1, editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.creditdebit);
textView1 = (TextView) findViewById(R.id.tv1);
textView2 = (TextView) findViewById(R.id.tv2);
editText1 = (EditText) findViewById(R.id.bankname);
editText2 = (EditText) findViewById(R.id.cardno);
btn = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent card = new Intent(CardNo.this, EnterAmount.class);
startActivity(card);
finish();
}
});
}
private void saveData() {
bankname = editText1.getText().toString();
cardno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname);
editor.putString("Card No", cardno);
editor.apply();
}
}
Now code for cheque payment Activity :
public class Cheque extends Activity {
String bankname1;
String chequeno;
int chq;
TextView textView1,textView2;
EditText editText1,editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cheque);
textView1=(TextView)findViewById(R.id.tv11);
textView2=(TextView)findViewById(R.id.tv12);
editText1=(EditText)findViewById(R.id.bankname1);
editText2=(EditText)findViewById(R.id.chequeno);
btn=(Button)findViewById(R.id.btn11);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent cheque = new Intent(Cheque.this, EnterAmount.class);
startActivity(cheque);
finish();
}
});
}
private void saveData() {
bankname1 = editText1.getText().toString();
chequeno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname1);
editor.putString("Cheque No", chequeno);
editor.apply();
}
}
Now the code of the activity where i am retrieving the data from shared preferences and storing the data into sqlite.
public class EnterAmount extends Activity implements OnClickListener {
Intent intent;
Button save;
Spinner spinnerPayment, spinnerCategory;
EditText etamt, etbdgt, et_get_other;
String date, sBdgt, budget, bankname, cardno, chequeno;
String sAmt;
String spinnerItemSelectedPayment;
String spinnerItemSelectedCategory;
// String category;
int amt;
int date2;
TextView caategories, tv_cat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enteramount);
save = (Button) findViewById(R.id.bsaveDb);
caategories = (TextView) findViewById(R.id.tvCaategories);
etamt = (EditText) findViewById(R.id.etAmount);
etbdgt = (EditText) findViewById(R.id.etbudget);
spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
spinnerPayment = (Spinner) findViewById(R.id.payment_spinner);
List<String> sCategory = new ArrayList<String>();
String[] categories = {"Food", "Bills",
"Travel", "Entertainment", "Office Stationary",
"Medical Expenses", "Fuel"
};
sCategory.add("Food");
sCategory.add("Office Stationary");
sCategory.add("Bills");
sCategory.add("Travel");
sCategory.add("Entertainment");
sCategory.add("Medical Expenses");
sCategory.add("Fuel");
ArrayAdapter<String> sc = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sCategory);
spinnerCategory.setAdapter(sc);
List<String> l = new ArrayList<String>();
String[] paymentMode = {"Cash", "Credit/Debit Card", "Cheque", "NetBanking"};
l.add("Cash");
l.add("Credit/Debit Card");
l.add("Cheque");
l.add("NetBanking");
ArrayAdapter<String> sp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, l);
spinnerPayment.setAdapter(sp);
save.setOnClickListener(this);
spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedCategory = parent.getItemAtPosition(pos)
.toString();
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedCategory = "Food";
}
});
spinnerPayment.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedPayment = parent.getItemAtPosition(pos).toString();
if (spinnerItemSelectedPayment.equals("Cheque")) {
Intent cheque = new Intent(EnterAmount.this, Cheque.class);
cheque.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(cheque);
} else if (spinnerItemSelectedPayment.equals("Credit/Debit Card")) {
Intent card = new Intent(EnterAmount.this, CardNo.class);
card.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(card);
}
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedPayment = "Cash";
}
});
final Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy-HH:mm:ss ");
date = sdf.format(c.getTime());
int yy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH) + 1;
int dd = c.get(Calendar.DAY_OF_MONTH);
String s = yy + "" + (mm < 10 ? ("0" + mm) : (mm)) + ""
+ (dd < 10 ? ("0" + dd) : (dd));
Log.e("datechange", s);
date2 = Integer.parseInt(s);
Log.e("integer2", "hello" + date2);
}
#Override
public void onBackPressed () {
super.onBackPressed();
finish();
}
private void vibrate(int ms) {
((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(ms);
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
budget = sharedPreferences.getString("Budget", " ");
getSharedPreferences(mypreference,Context.MODE_PRIVATE);
bankname = sharedPreferences.getString("Bank Name", "Not Applicable");
cardno = sharedPreferences.getString("Card No", "Not Applicable");
chequeno = sharedPreferences.getString("Cheque No", "Not Applicable");
}
private void removeSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("Bank Name");
editor.remove("Cheque No");
editor.remove("Card No");
editor.apply();
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bsaveDb: {
savePreferences("Budget", etbdgt.getText().toString());
loadSavedPreferences();
sAmt = etamt.getText().toString();
Log.e("category", "Hello" + sAmt);
try {
amt = Integer.parseInt(sAmt);
Log.e("amt is", "" + amt);
} catch (Exception e) {
}
DbClass dc = new DbClass(this);
dc.open();
if (amt == 0) {
Toast.makeText(getApplicationContext(),
"Please insert the amount", Toast.LENGTH_SHORT).show();
} else {
dc.categoryDetailsInsert(amt, spinnerItemSelectedCategory, date, spinnerItemSelectedPayment, date2, bankname, cardno, chequeno);
dc.close();
Toast.makeText(getApplicationContext(), "Saved successfully",
Toast.LENGTH_LONG).show();
amt = 0;
etamt.setText("");
etbdgt.setText(budget);
removeSavedPreferences();
}
break;
}
}
}
}
i am attching a screenshot of sqlite database and you can see bank name is getting stored properly but cardno and cheque no is always same with respect to payment.Screenshot Of Database
Attach your keys to the context tag to prevent override of values.
like:
String TAG = "ContextName or ActivityName";
then on saving do:
pref.put(TAG+key, "value");
Actually above code is Fine the Problem was in the code where i was retrieving code from the database i inserted the same index number for the two different columns. so i was getting same values for cheque no and debit card number.
Please help me, code below
The textview is always 0 when i close and start my app.
EDIT
The full code is now added.
TextView txt = (TextView)findViewById(R.id.textView23);
int mynum1 = ea1.TimeCounter++;
int mynum2 = ea2.TimeCounter++;
int mynum3 = ea3.TimeCounter++;
int mynum4 = ea4.TimeCounter++;
int mynum5 = ea5.TimeCounter++;
int mynum6 = ea6.TimeCounter++;
in = (mynum1) + (mynum2) + (mynum3) + (mynum4) + (mynum5) + (mynum6) ;
txt.setText(Integer.toString(in));
TextView tt = (TextView)findViewById(R.id.textView26);
SharedPreferences sps = getSharedPreferences(PREFS, 0);
String ss = sps.getString("Score", "Nothing Found");
tt.setText(ss);
Button btn = (Button)findViewById(R.id.button8);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView txt = (TextView)findViewById(R.id.textView23);
TextView tt = (TextView)findViewById(R.id.textView26);
if (Integer.parseInt(txt.getText().toString()) < Integer.parseInt(tt.getText().toString())) {
String current = txt.getText().toString();
SharedPreferences sp = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Score", in);
editor.commit();
tt.setText(current);
}
else if(Integer.parseInt(txt.getText().toString()) > Integer.parseInt(tt.getText().toString())) {
SharedPreferences sps = getSharedPreferences(PREFS, 0);
String ss = sps.getString("Score", "Nothing Found");
tt.setText(ss);
}
}
});
So now i got an answer
new Thread(new Runnable() {
public void run() {
TextView txt = (TextView)findViewById(R.id.textView23);
int mynum1 = ea1.TimeCounter++;
int mynum2 = ea2.TimeCounter++;
int mynum3 = ea3.TimeCounter++;
int mynum4 = ea4.TimeCounter++;
int mynum5 = ea5.TimeCounter++;
int mynum6 = ea6.TimeCounter++;
in = (mynum1) + (mynum2) + (mynum3) + (mynum4) + (mynum5) + (mynum6) ;
txt.setText(Integer.toString(in));
TextView tt = (TextView)findViewById(R.id.textView26);
SharedPreferences sps = getSharedPreferences(PREFS, 0);
String ss = sps.getString("Score", "0");
tt.setText(ss);
Button btn = (Button)findViewById(R.id.button8);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView txt = (TextView)findViewById(R.id.textView23);
TextView tt = (TextView)findViewById(R.id.textView26);
if (Integer.parseInt(txt.getText().toString()) > Integer.parseInt(tt.getText().toString())) {
String current = Integer.toString(in);
SharedPreferences sp = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Score", current);
editor.commit();
tt.setText(current);
}
else if(Integer.parseInt(txt.getText().toString()) < Integer.parseInt(tt.getText().toString())) {
SharedPreferences sps = getSharedPreferences(PREFS, 0);
String ss = sps.getString("Score", "Nothing Found");
tt.setText(ss);
}
}
});
}
}).start();
}
I create a mini game . The User need to answer my question in 2 seconds, if user answer true , the score will increase 1 , and if user answer wrong - Game over and the score become to 0.
I want to use SharedRefences so that I can save the score when the user play again . But it's not working .
My CountDownTimer:
public void start_game() {
flag = false;
btnTrue.setClickable(true);
btnWrong.setClickable(true);
a = (int) (Math.random() * 6);
b = (int) (Math.random() * 6);
sum = (int) (Math.random() * 11);
tvDetails.setText(a + " + " + b + " = " + sum);
proTime.setSecondaryProgress(0);
timer = new CountDownTimer(3000, 10) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
btnTrue.setClickable(false);
btnWrong.setClickable(false);
if (flag) {
tmp++;
tvScore.setText("" + tmp);
start_game();
} else {
ShowDialogs();
tmp = 0;
tvScore.setText("" + tmp);
}
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
proTime.setSecondaryProgress(proTime.getSecondaryProgress() + 10);
}
};
timer.start();
}
public void ShowDialogs() {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(false);
tvNowScore = (TextView) dialog.findViewById(R.id.NowScore);
tvHighScore = (TextView) dialog.findViewById(R.id.HighScore);
ImageView btnRep = (ImageView) dialog.findViewById(R.id.Rep);
ImageView btnExit = (ImageView) dialog.findViewById(R.id.Exit);
ResPreferences();
int HighScore = Integer.parseInt(tvHighScore.getText().toString());
int Score = Integer.parseInt(tvScore.getText().toString());
if (Score > HighScore) {
HighScore = Score;
SavingPreferences();
}
tvNowScore.setText("" + Score);
tvHighScore.setText("" + HighScore);
btnExit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
System.exit(0);
}
});
btnRep.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.cancel();
if (timer != null) {
timer.cancel();
timer = null;
}
start_game();
}
});
dialog.show();
}
I can't save a score when the game finish.
This is my Save Preferences
public void SavingPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
SharedPreferences.Editor editor = pre.edit();
String HighScore = tvHighScore.getText().toString();
editor.putString("HighScore", HighScore);
editor.commit();
}
This is Restrore Pre:
public void ResPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
String score = pre.getString("HighScore", "0");
tvHighScore.setText(score);
}
Try this :
public void SavingPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
String score = null;
if(pre.contains("HighScore")){
score = pre.getString("HighScore", "0");
}
SharedPreferences.Editor editor = pre.edit();
String HighScore = tvHighScore.getText().toString();
if(score != null && Integer.parseInt(score) > Integer.parseInt(HighScore )){
editor.putString("HighScore", score);
} else {
editor.putString("HighScore", HighScore);
}
editor.commit();
}
I have a little test project below. All I want to do is save the EditText numbers entered and TextView result (thing1, thing2, result) . What's best? onSaveInstanceState, sharedPreference, or something different like SQLite?
I've frustratingly tried the first two (for probably embarrassingly too long), but couldn't figure it out. Could someone please help by adding it to the code below?
public class MainActivity extends ActionBarActivity {
EditText thing1;
EditText thing2;
TextView result;
double n1=0;
double n2=0;
double total=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button divideButton = (Button) findViewById(R.id.divideButton);
divideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
if (n2 !=0){
total = (n1 / n2);}
final double total = ((double)n1/(double)n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1+n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button subtractButton = (Button) findViewById(R.id.subtractButton);
subtractButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1-n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button multiplyButton = (Button) findViewById(R.id.multiplyButton);
multiplyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1*n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
}
If you will just use the values later like when you open your application, you
can use the SharedPreferences. Based on your code above you can add the code below
to save your EditText data to SharedPreferences and restore it later.
To save your EditText value:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences("ProjectName", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("thing1", thing1.getText.toString());
editor.commit();
To get the value from SharedPreferences you can do this in your onCreate function:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences("ProjectName", MODE_PRIVATE);
String sValue = sharedPreferences.getString("thing1", "default");
thing1.setText( sValue );
I made an Android app wherein I receive text and numeric (decimal) values from user in 5 different activities then store them in my sharedpreferences. I am able to restore all values using editor(); in all previous 5 activities.
Now
In final calculation activity I'm restoring all user input (text and numbers) and storing them in string and double variables. performing calculations in below posted code activity;
Problem
I am unable to view results in textview using getText.
Is there anything missing?
public class Xcalculateforall extends Activity {
Button qcbut, coatsolbut;
TextView TVqcbut, TVcoatsolbut, TVbrand;
double tdrum, rqctotal;
String a;
public static String FILE1 = "MyPrefsFile";
SharedPreferences abcPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.resultmain);
qcbut = (Button) findViewById(R.id.bQCS);
coatsolbut = (Button) findViewById(R.id.bCSP);
TVqcbut = (TextView) findViewById(R.id.tvQCS);
TVbrand = (TextView) findViewById(R.id.tvBrand);
TVcoatsolbut = (TextView) findViewById(R.id.tvCSP);
abcPref = this.getSharedPreferences(FILE1, 0);
a = abcPref.getString("tA", ""); //receives text value and store in 'a' String
double k = Integer.parseInt(abcPref.getString("tsK", ""));
double l = Integer.parseInt(abcPref.getString("tsL", ""));
double m = Integer.parseInt(abcPref.getString("tsM", ""));
double n = Integer.parseInt(abcPref.getString("tsN", ""));
double o = Integer.parseInt(abcPref.getString("tsO", ""));
double p = Integer.parseInt(abcPref.getString("tsP", ""));
tdrum = 20 / m;
double samv = (tdrum / k) / l;
double samv2 = (Math.sqrt(samv));
double tsample = ((samv2 + 1) * k) * l;
double rmicro = tsample * n;
double rchem = tsample * o;
double rother = tsample * p;
double rinqc = rmicro + rchem + rother;
rqctotal = rinqc - 2;
qcbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TVqcbut.setText(rqctotal + "Days");
TVbrand.setText("" + a);
// Intent results = new Intent("com.traviss.calculate.RESULT");
// startActivity(results);
}
});
}
}
Updating query --- previous activity where i take user input
public class G2J extends Activity {
Button two2five, save2;
EditText edtG, edtH, edtI, edtJ, edtK;
int tG, tH, tI, tJ, tK;
String tsG, tsH, tsI, tsJ, tsK;
public static String FileP2 = "MyPrefsFile";
SharedPreferences abcPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.g2j);
two2five = (Button) findViewById(R.id.btp2);
edtG = (EditText) findViewById(R.id.etG);
edtH = (EditText) findViewById(R.id.etH);
edtI = (EditText) findViewById(R.id.etI);
edtJ = (EditText) findViewById(R.id.etJ);
edtK = (EditText) findViewById(R.id.etK);
abcPref = getSharedPreferences(FileP2, 0);
edtG.setText(abcPref.getString("tsG", ""));
edtH.setText(abcPref.getString("tsH", ""));
edtI.setText(abcPref.getString("tsI", ""));
edtJ.setText(abcPref.getString("tsJ", ""));
edtK.setText(abcPref.getString("tsK", ""));
two2five.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((!edtG.getText().toString().equals(""))
&& (!edtH.getText().toString().equals(""))
&& (!edtI.getText().toString().equals(""))
&& (!edtJ.getText().toString().equals(""))
&& (!edtK.getText().toString().equals(""))) {
abcPref = G2J.this.getSharedPreferences(FileP2, 0);
SharedPreferences.Editor editor = abcPref.edit();
editor.putString("tsG", edtG.getText().toString());
editor.putString("tsH", edtH.getText().toString());
editor.putString("tsI", edtI.getText().toString());
editor.putString("tsJ", edtJ.getText().toString());
editor.putString("tsK", edtK.getText().toString());
editor.commit();
Toast message = Toast.makeText(G2J.this, "Values are saved", 2000);
message.setGravity(Gravity.BOTTOM, 0, 0);
message.show();
Intent openl2p = new Intent("com.traviss.calculate.L2P");
startActivity(openl2p);
}
else {
Toast failz = Toast.makeText(G2J.this,
"Values are not Entered", 2000);
failz.setGravity(Gravity.BOTTOM, 0, 0);
failz.show();
}
};
});
}
}
check your string variables and xml layout
Try -
int k = Integer.parseInt(abcPref.getString("tsK", ""));
You wont get decimal values using Integer.parseInt(String)
Do this
double k = Double.parseDouble(abcPref.getString("tsK", ""));
a = String.valueOf(abcPref.getString("tA", ""));