Parsing error in Android - android

I am storing an array of numbers as string(I get the string from shared preferences) and then trying to parse it.
But when I use parseInt my app crashes. The activity Second is called by Main class.
public class Second extends Activity {
public int[] x = new int[50];
public int[] y = new int[50];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
SharedPreferences data= getSharedPreferences("data",0);
SharedPreferences.Editor editor= data.edit();
StringBuilder str = new StringBuilder();
str.append(data.getString("val", "0")).append(",").append(getIntent().getExtras().getString("thetext"));
String end = str.toString();
editor.putString("val", end);
editor.commit();
//EditText et1= (EditText) findViewById(R.id.editText2);
//et1.
String savedString = data.getString("val", "0");
savedString.replaceAll("\\s","");
String[] st = savedString.split(",");
int i;
for(i=0;i<st.length;i++){
st[i].trim();
Log.d("Debug" , "st["+i+"] = "+st[i]);
x[i] = Integer.valueOf(st[i]);
y[i]=i;}
}
public void lineGraphHandler (View view)
{
LineGraph line = new LineGraph();
Intent lineIntent = line.getIntent(this);
startActivity(lineIntent);
}
}
Where is it going wrong?

Add a line between these
st[i].replaceAll("\\s","");
Log.d("Debug" , "st["+i+"] = "+st[i])
x[i] = Integer.parseInt(st[i]);
and see that if that is a convertible string or there are some letters accidently inserted that can't be converted to int?

Related

Getting Same Values For Two Different Keys in Shared Preferences

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.

How to calculate a key with integer value from SharedPreferences

I want to calculate 2 values with key from SharedPreferences.
This is my code
This is my first activity
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(A1, option_scoreA1);
editor.commit();
Intent intent = new Intent(QuestionActivity.this, SecondActivity.class);
startActivity(intent);
This is my second activity
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(A2, option_scoreA4);
editor.commit();
Intent intent = new Intent(SecondActivity.this, TestFinalActivity.class);
startActivity(intent);
This is my final activity
protected QuestionActivity activity1;
protected SecondActivity activity2;
String c = activity1.A1;
String b = activity2.A2;
String A = c + b ;
#Bind(R.id.hasil)
TextView hasil;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
total();
}
public void total() {
hasil = (TextView) findViewById(R.id.hasil);
hasil.setText(A);
}
I want to totalize each value from key A1 and A2. But what i got was the key, not the value when I totalize them.
Thank you
It is because you add or concatenate the keys into variable A. And you want to calculate the int so you should better put the total result into float or int data type, right?
Do something as shown below
very fist of all make two keys as your instance filed in QuestionActivity class
public static final String KEY_A = "ka";
public static final String KEY_B = "kb";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int a = sharedPreferences.getInt(QuestionActivity.KEY_A, 0);
int b = sharedPreferences.getInt(QuestionActivity .KEY_B, 0);
A = a+b;
total();
}
and since it is integer, you need to cast the result into string format.
public void total() {
hasil = (TextView) findViewById(R.id.hasil);
hasil.setText(String.valueOf(A));
}
SharedPreference starting guide
access to value in SharedPreferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int value1 = preferences.getInt("your key", default_value);
int value2 = preferences.getInt("your key", default_value);
First create sharedpreferences and then get values of your keys.
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
int c = pref.getInt(A1, 0) // here A1 is the key and 0 is default value
int b = pref.getInt(A2, 0) // here A2 is the key and 0 is default value
int A = c + b;

Unable to access my sharedpreferences and calculate

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", ""));

I saved my tasks but i can't retrieve all the tasks using shared preferences?

I saved more tasks, but while retrieving the tasks are displayed one by one. I need to display all the tasks.
This is my code to store the tasks.
public static int i=0;
task_ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String prefs_name = null;
SharedPreferences remind = getApplicationContext().getSharedPreferences(prefs_name,0);
SharedPreferences.Editor taskedit=remind.edit();
taskedit.putString("taskname"+i, edit_task.getText().toString().trim());
taskedit.putString("taskdate"+i, edit_date.getText().toString().trim());
taskedit.putString("tasktime"+i, edit_time.getText().toString().trim());
taskedit.apply();
i++;
Toast.makeText(getApplicationContext(), "Task added", Toast.LENGTH_SHORT).show();
Intent ret_view=new Intent(Add.this,TaskActivity.class);
startActivity(ret_view);
}
});
This is the code for retreiving..
public static int i=0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
TextView tv=(TextView)findViewById(R.id.textView2);
String prefs_name = null;
SharedPreferences remind= getApplicationContext().getSharedPreferences(prefs_name,0);
remind.getAll();
String viewtask=remind.getString("taskname"+i, "");
String viewdate=remind.getString("taskdate"+i, "");
String viewtime=remind.getString("tasktime"+i, "");
tv.setText(new StringBuilder().append(viewtask).append(" ").append(viewdate).append(" ").append(viewtime));
i++;
try it like this
String taskname = ("taskname"+i);
String taskdate = ("taskdate"+i);
String tasktime = ("tasktime"+i);
taskedit.putString(taskname, edit_task.getText().toString().trim());
taskedit.putString(taskdate, edit_date.getText().toString().trim());
taskedit.putString(tasktime, edit_time.getText().toString().trim());
Retrieving
String taskname = ("taskname"+i);
String taskdate = ("taskdate"+i);
String tasktime = ("tasktime"+i);
String viewtask=remind.getString(taskname, "");
String viewdate=remind.getString(taskdate, "");
String viewtime=remind.getString(tasktime, "");
and do exactly same when you are retrieving data from sharePreference.
That code works for me . Hope this will help you as well
Cheers

Android: How to store array of strings in SharedPreferences for android

I'm building an app which searches the web using search engine. I have one edittext in my app from which user will search the web. I want to save the search keywords just like browser history does. I'm able to save and display it with the last keyword but I can't increase the number of searches result. I want to display the last 5 searhes. Here is my code :
public class MainActivity extends Activity implements OnClickListener {
Button insert;
EditText edt;
TextView txt1, txt2, txt3, txt4, txt5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.search_word);
txt1 = (TextView) findViewById(R.id.txt1);
txt1.setOnClickListener(this);
insert = (Button) findViewById(R.id.insert);
insert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((edt.getText().toString().equals(""))) {
Toast.makeText(
getBaseContext(),
"Whoa! You haven't entered anything in the search box.",
Toast.LENGTH_SHORT).show();
} else {
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = edt.getText().toString();
editor.putString("key", text);
editor.commit();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG)
.show();
}
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
txt1.setText(text);
}
public void onClick(View v) {
String text = txt1.getText().toString();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_SHORT).show();
}
}
Please help me in overcoming this problem.
SAVE ARRAY
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putString(arrayName + "_" + i, array[i]);
return editor.commit();
}
LOAD ARRAY
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
String array[] = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
Convert your array or object to Json with Gson library and store your data as String in json format.
Save;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString(TAG, json);
editor.commit();
Read;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);
Original answer: Storing Array List Object in SharedPreferences

Categories

Resources