is there any way can do a loop for string?
This is my Database data. I can't use Int because It won't allow 0 to be the first character.
This is my data. I have two tables. "Donation_Details" TxnNo data comes from "Information" 'unitcode + lastTxnNo'
How to increase the number to be '0012' after I click the button save? I have to check every single time when users click the button save, It will auto increase automatically, to make sure the user know how many transaction have been created.
this is my CODE.
BigDecimal paidAmt = new BigDecimal(D_Amount.getText().toString()).setScale(2, RoundingMode.HALF_UP);
Model txn = new Model(); // initialize your model class first
txn.setName(D_Name.getText().toString());
//txn.setTxnNo(D_Txn.getText().toString());
txn.setTxnDate(Select_Date.getText().toString());
txn.setAmount(paidAmt);
txn.setDescription1(D_Description.getSelectedItem().toString());
txn.setDescription2(Ds_Description.getText().toString());
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", txn.getName()); // get the entered name here.
//cv.put("TxnNo", txn.getTxnNo());
cv.put("TxnDate", txn.getTxnDate());
cv.put("Amount", txn.getAmount().toPlainString());
cv.put("Description1", txn.getDescription1());
cv.put("Description2", txn.getDescription2());
db.insert("Donation_Details", null, cv);
db.close();
Toast.makeText(Donation_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Thanks in advance.
Try this
cv.put("TxnNo", String.format("%04d", txn.getTxnNo()));
It will have a zero-padding with a length of 4.
Edit
int i; // declare as global value
Button clickButton = (Button) findViewById(R.id.clickButton);
clickButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
i = ++i;
txn.setTxnNo(i);
cv.put("TxnNo", String.format("%04d", txn.getTxnNo()));
}
});
To prevent the number back to 0 , you need to use SharedPreferences.
SharedPreferences app_preferences =PreferenceManager.getDefaultSharedPreferences(Activity1.this);
SharedPreferences.Editor editor = app_preferences.edit();
int i = app_preferences.getInt("key",0);
Button clickButton = (Button) findViewById(R.id.clickButton);
clickButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
i = ++i;
txn.setTxnNo(i+""); // set to Model class
cv.put("TxnNo", String.format("%04d", txn.getTxnNo())); // save to database and padding 0 to left
editor.putInt("key",i).commit();
}
});
you can do it using shared preference,
in your case, initialise an int value,
int id;
SharedPreferences sharedpreferences = getSharedPreferences("data-Info", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("key",id++);
editor.commit();
now, to get that value using preference,
id=sharedpreferences.getInt("key", 0);
this way you don't need to care about your id.
in case you just want to increase the value of the integer just do this
String num = /*get the value from db*/;
int num1 = Integer.parseInt(num+"");
num = num1+"";
//then save the string num to the db.
but if u want to save the value in the device the sahred preferences is the way to go.
private SharedPreferences pref;
pref = getApplicationContext().getSharedPreferences("valuestorage", 0); // 0 - for private mode
String num = /*get the value from db*/;
int num1 = Integer.parseInt(num+"");
num = num1+"";
pref.edit().putString("lastno",num).apply();
//then save the string num to the db.
now you need not call the database everytime only call it if the pref value is null.
so now you'll check the value from pref increment it and save it in db again.
here is how:
considering the data is present in pref
String aa = pref.getString("lastno","");
if(!aa.equals(""))
{
String num = aa;
int num1 = Integer.parseInt(num+"");
num = num1+"";
pref.edit().putString("lastno",num).apply();
//then save the string num to the db.
}
https://developer.android.com/training/data-storage/shared-preferences
Related
my TxnNo(A0010001) came from Unitcode(A001) + LastTxnNo(0001). This is my button click.
Db_Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Model txn = new Model();// initialize your model class first
BigDecimal paidAmt = new BigDecimal(D_Amount.getText().toString()).setScale(2, RoundingMode.HALF_UP);
txn.setName(D_Name.getText().toString());
txn.setTxnNo(D_Txn.getText().toString());
txn.setTxnDate(Select_Date.getText().toString());
txn.setAmount(paidAmt);
txn.setDescription1(D_Description.getSelectedItem().toString());
txn.setDescription2(Ds_Description.getText().toString());
try {
SQLiteDatabase db = mSQLiteHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", txn.getName());
cv.put("TxnNo", txn.getTxnNo());
cv.put("TxnDate", txn.getTxnDate());
cv.put("Amount", txn.getAmount().toPlainString());
cv.put("Description1", txn.getDescription1());
cv.put("Description2", txn.getDescription2());
db.insert("Donation_Details", null, cv);
db.close();
increaseNumber++;
populate_TxnNo();
Toast.makeText(Donation_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
I put increaseNumber++; to make sure it will increase automatically. So Everytime I click the button. the number will change "A0010001" to "A0010002" and so on. But once I leave this page, and go in again. It will back to "A0010001". How to make it stay at the latest number instead of going back to "A0010001".
This is the method to set the numbering.
private void populate_TxnNo() {
int lastNumber = Integer.valueOf(txn.getLastTxnNo());
lastNumber = lastNumber + increaseNumber;
String stringLast = String.format("%04d", lastNumber);
String txnNo = txn.getUnit_Code() + stringLast;
//increaseNumber++;
D_Txn.setText(txnNo);
}
UPDATE
So for me to understand the Shared preference I put those code to the button new.
Db_New.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increaseNumber++;
populate_TxnNo();
}
});
But I don't know how to use Shared preference even though I see the example of code... Can anyone explain it for me? How to use this code?
SharedPreferences prefs;
SharedPreferences.Editor edit;
prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
edit=prefs.edit();
edit.putString("yourKey", txnNo);
edit.commit();
String txnNo = prefs.getString("yourKey", null);
Firstly, declare these two variables
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
int count;
Next add these in onCreate method
sharedPreferences = getApplicationContext().getSharedPreferences("counters", MODE_PRIVATE);
editor = sharedPreferences.edit();
count = sharedPreferences.getInt("counter", 0);
Finally modify populate_TxnNo methods
private void populate_TxnNo() {
int a = count++;
int lastNumber = Integer.valueOf(txn.getLastTxnNo());
lastNumber = lastNumber + a;
String stringLast = String.format("%04d", lastNumber);
String txnNo = txn.getUnit_Code() + stringLast;
D_Txn.setText(txnNo);
editor.putInt("counter", ++a);
editor.commit();
}
Try using Shared Preference
these two lines before onCreate()
SharedPreferences prefs;
SharedPreferences.Editor edit;
these two lines in onCreate()
prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
edit=prefs.edit();
and on onPause() save the string
#Override
protected void onPause() {
super.onPause();
edit.putString("yourKey", txnNo);
edit.commit();
}
and to access it back simply write in onStart
#Override
protected void onStart() {
super.onStart();
String txnNo = prefs.getString("yourKey", null);
}
simply add yourNumber to shared preferences
int yourNumber;
SharedPreferences number = getSharedPreferences("number", MODE_PRIVATE);
to save your number
number.edit.putInt("number",yourNumber).apply;
and read the number next time
int savedNumber = number.getInt("number",0);
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;
I'm new in developing Android application and currently I'm developing a android software that require user to input quite amount of data and save it on sharedPreferences as database. Here is my coding:
public static final String DEFAULT= "NONE";
When saving the data input by the user, a portion of coding are as shown at the following:
public void OnClickSave(){
button17=(Button)findViewById(R.id.button17);
button17.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
name = (EditText) findViewById(R.id.name);
material = (EditText) findViewById(R.id.material);
type = (EditText) findViewById(R.id.type);
proper1 = (EditText) findViewById(R.id.proper1);
p1 = (EditText) findViewById(R.id.p1);
p2 = (EditText) findViewById(R.id.p2);
p3 = (EditText) findViewById(R.id.p3);
po1 = (EditText) findViewById(R.id.po1);
po2 = (EditText) findViewById(R.id.po2);
po3 = (EditText) findViewById(R.id.po3);
c1 = (EditText) findViewById(R.id.c1);
c2 = (EditText) findViewById(R.id.c2);
c3 = (EditText) findViewById(R.id.c3);
SharedPreferences sharedPreferences = getSharedPreferences("Database", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", name.getText().toString());
editor.putString("material", material.getText().toString());
editor.putString("type", type.getText().toString());
editor.putString("proper1",proper1.getText().toString());
editor.putString("p1", p1.getText().toString());
editor.putString("p2", p2.getText().toString());
editor.putString("p3", p3.getText().toString());
editor.putString("po1", po1.getText().toString());
editor.putString("po2", po2.getText().toString());
editor.putString("po3", po3.getText().toString());
editor.putString("c1", c1.getText().toString());
editor.putString("c2", c2.getText().toString());
editor.putString("c3", c3.getText().toString());
editor.commit();
Toast.makeText(MainActivity.this, "Saved!!!", Toast.LENGTH_LONG).show();
}
}
);
}
For loading of data,
public void OnClickLoad(){
button38=(Button)findViewById(R.id.button38);
button38.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences("Database", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("name", DEFAULT);
String material = sharedPreferences.getString("material", DEFAULT);
String type = sharedPreferences.getString("type", DEFAULT);
String proper1 = sharedPreferences.getString("proper11", DEFAULT);
String p1 = sharedPreferences.getString("p1", DEFAULT);
String p2 = sharedPreferences.getString("p2", DEFAULT);
String p3 = sharedPreferences.getString("p3", DEFAULT);
String po1 = sharedPreferences.getString("po1", DEFAULT);
String po2 = sharedPreferences.getString("po2", DEFAULT);
String po3 = sharedPreferences.getString("po3", DEFAULT);
String c1 = sharedPreferences.getString("c1", DEFAULT);
String c2 = sharedPreferences.getString("c2", DEFAULT);
String c3 = sharedPreferences.getString("c3", DEFAULT);
}
}
);
AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity12.this);
a_builder.setMessage(
"Data input 1:"+ name + "\n"+ material +"\n"+ type +"\n"+ proper1 +"\n"+
p1+ "\n"+p2 +"\n"+ p3 + "\n"+po1 +"\n"+ po2 +"\n"+po3 +"\n"+ s1 +"\n"+s2 +"\n"+s3 + "\n" )
.setCancelable(false)
.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setNegativeButton("Return", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
;
AlertDialog alert= a_builder.create();
alert.setTitle("Checking");
alert.show();
}
When the user didn't input any data and didn't press the save button, the data shows will be the DEFAULT data, which is NONE as set.
public static final String DEFAULT= "NONE";
However, when the user didn't input any data and press the save button, the output of the data become blank.
Here's the question, is that possible to set the blank input or space input to DEFAULT data? (Means when user didn't insert any input(or space only) and save, corresponding data loaded is NONE.)
I been refer to some solution similar to this ,knowing that I can do it manually 1 by 1, but is that any alternative solution to make it faster and put into the Sharepreferances?
Thank in advance for anyone who concern and help ! Sorry for my poor language.
However, when the user didn't input any data and press the save button, the output of the data become blank.
It's empty string "".
Here's the question, is that possible to set the blank input or space input to DEFAULT data?
You are doing this wrong way. You should not put the entry into shared preferences, when there's noting entered. Then during read you would get your DEFAULT. So make helper like
protected void storeData(SharedPreferences.Editor editor, String key, EditText et) {
String content = et.getText().toString();
// is there any content? Empty string is no content
if ("".equals(content)) {
// ensure we do not retain previously stored value for that key
editor.remove(key);
} else {
// save new data in the storage
editor.putString(key, content);
}
}
and then replace all the calls you have that put string data directly, like this one:
editor.putString("p1", p1.getText().toString());
with calls to our helper:
storeData(editor, "p1", p1);
Am just wondering if there is a way to save data into a text file without being overwritten.
Currently i am using sharedpreferences and it overwrites the data which is okay but coinciding with this, i want somewhere where i can keep record of the value before being overwritten in a list or column form.
So it goes something like this:
60, 65, 70..etc
The values are stored one after another without being overwritten. I am thinking of doing this locally in a text file which can be read as well.
I am doing this so i can create a stats page or something like that.
I hope someone can help me find a solution.
My code:
public class workout extends Activity {
TextView weightresultText, newweightresultText, difficultyrating;
Boolean male, strength;
double newweight, newweight1;
int weight, age;
Button button, button4;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout);
button = (Button) findViewById(R.id.button);
button4 = (Button) findViewById(R.id.button4);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
weight = Integer.parseInt(sharedPreferences.getString("storedweight", "Your Weight"));
age = Integer.parseInt(sharedPreferences.getString("storedage", "Your Age"));
male = sharedPreferences.getBoolean("is_male", false);
strength = sharedPreferences.getBoolean("is_strength", false);
weightresultText = (TextView) findViewById(R.id.weightresultLabel);
newweightresultText = (TextView) findViewById(R.id.newweightresultLabel);
difficultyrating = (TextView) findViewById(R.id.difficultylevel);
if (sharedPreferences.getBoolean("firstrun", true)) {AgeCalculation();
sharedPreferences.edit().putBoolean("firstrun", false).commit();}
AfterFirstLaunch();
}
public void SaveWeight(){
savePreferences("storednewweight", (Double.toString(newweight)));
}
//Should only happen on first launch.
public void AgeCalculation() {
if (strength == true){
if (male == true && age >= 18) {
newweight = (weight * 0.8);
}
if (male == true && age >= 30) {
newweight = (weight * 0.6);
}
if (male == true && age >= 50) {
newweight = (weight * 0.4);
}
if (male == true && age >= 70) {
newweight = (weight * 0.2);
}
if (male == true && age > 80) {
newweight = (weight * 0.1);
}
if (male == false && age >= 20 ){
newweight = (weight * 0.3 );
}
weightresultText.setText(Double.toString(newweight));
SaveWeight();
}}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
// On every other launch, it is based on button, the newweight is saved and loaded each time.
public void buttonClick1(){
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//this gets the current weight based on first time launch.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
newweight1 = Double.parseDouble(newweight);
newweight1 = newweight1 + 5;
//saves value into sharedpreference
savePreferences("storednewweight", (Double.toString(newweight1)));
//save to shared preference, and load value on new launch?
//also store into local database for review later.
difficultyrating.setText("1");
button.setEnabled(false);
button4.setEnabled(false);
//save this data then on new launch it uses this figure.
// so first time it creates then uses this figure for future.
}
});}
public void buttonClick4(){
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//this gets the current weight based on first time launch.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
newweight1 = Double.parseDouble(newweight);
newweight1 = newweight1 + 10;
//saves value into sharedpreference
//save to text file in array
savePreferences("storednewweight", (Double.toString(newweight1)));
difficultyrating.setText("2");
button.setEnabled(false);
button4.setEnabled(false);
//save this data then on new launch it uses this figure.
// so first time it creates then uses this figure for future.
}
});}
//runs on every other launch
public void AfterFirstLaunch(){
buttonClick1();
buttonClick4();
//receive value on other launches and show on field.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
weightresultText.setText(newweight);
}
}
For something like this, where you're storing multiple entries of similar data, you'd really want to use an SQL database with a content provider. You'd just create new rows for each entry.
For writing into a textFile with overwritten use the following code
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/SO/";
File dir = new File(path);
if (!dir.exists()) {
if (dir.mkdirs()) {
}
}
File logFile = new File(path + "filename.txt");
if (!logFile.exists()) {
logFile.createNewFile();
}
// BufferedWriter for performance, true to set append to file
FileWriter fw = new FileWriter(logFile, true);
BufferedWriter buf = new BufferedWriter(fw);
buf.append("Message");
buf.newLine();
buf.flush();
buf.close();
Make sure you have permission defined in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
First - sorry for my english;) I'am writing profile manager for Android and i want getString from a few SharedPreferences file and create listView. It's part of my code:
private static final String PN = "profile_name";
private EditTextPreference editText;
private SharedPreferences preferences;
public class Profile_Preferences extends PreferenceActivity {
...
private void SavePreferences() {
String text= editText.getText().toString();
preferences = getSharedPreferences("Profile_" + text, Activity.MODE_PRIVATE); //Here we created SharedPreferences file with name "Profile_"+ this what user write in editText
SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.putString(PN, editText.getText());
preferencesEditor.commit();
Ok. The user was doing a few profile, so we have file for example: Profile_home.xml, Profile_work.xml, Profile_something.xml. Now i wan't create listView with profile name from this file. It's my next Activity:
public class Tab_profiles extends ListActivity {
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, listItems);
setListAdapter(adapter);
...
public void LoadList() {
//It's a good idea to getString "profile_name" form every xml file with name "Profile_" + "" ?
preferences = getSharedPreferences("Profile_"+ "", Activity.MODE_PRIVATE);
String take_profile_name = preferences.getString("profile_name", null);
listItems.add(take_profile_name );
adapter.notifyDataSetChanged();
}
But this doesn't work... logcat log:
FATAL EXCEPTION: MAIN
java.land.Null.PointerException
at android.widget.ArrayAdaper.createViewFromResource(ArrayAdapter.java:355)
...
I don't now whoat it's wrong...
Please help my:) Thank you for any answers and sorry for my errors in writing and code;)
There are a few problems in your code:
String text = editText.getText().toString();
preferences = getSharedPreferences("Profile_" + text, Activity.MODE_PRIVATE);
SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.putString(PN, editText.getText());
If a user types "home" in the EditText, you create a preference file called "Profile_home" and save its name in the same file? You need to save the user generated file names in a different file which has a name you know, so you can access it in your code.
Second problem:
preferences = getSharedPreferences("Profile_" + "", Activity.MODE_PRIVATE);
String take_profile_name = preferences.getString("profile_name", null);
You're trying to open "Profile_" settings. This file does not exist(?). The second parameter of getString must not be null, otherwise you'll add a null-reference to your list of string, which fails. Replace it with an empty string "".
Edit: Here's a little workaround to get all custom named preferences:
private void SavePreferences() {
String text = editText.getText().toString();
preferences = getSharedPreferences("ProfileNames", Activity.MODE_PRIVATE);
SharedPreferences.Editor preferencesEditor = preferences.edit();
// increment index by 1
preferencesEditor.putInt("profile_count", preferences.getInt("profile_count", 0) + 1);
// save new name in ProfileNames.xml with key "name[index]"
preferencesEditor.putString("name" + (preferences.getInt("profile_count", 0) + 1), editText.getText());
preferencesEditor.commit();
}
public void LoadList() {
preferences = getSharedPreferences("ProfileNames", Activity.MODE_PRIVATE);
List<String> profileNames = new LinkedList<String>();
int profileCount = preferences.getInt("profile_count", 0);
for (int i = 1; i <= profileCount; i++) {
profileNames.add(preferences.getString(name + i, ""));
}
listItems.addAll(profileNames);
adapter.notifyDataSetChanged();
}