Create a List of saves from one button - java

I need help with my project. I need to be able to press a save button that uses shared preferences, and every time I press that button, I need it to take the saved data and stack it underneath each other like a list. The key value is "result". So the save button takes the string and integer and places it onto my Main activity XML layout. But, if I press save again with different integers or string it will replace the original string and integer I had originally saved. I want it to be able to keep the original string and integer if i save it for the first time and make a new string and integer underneath the original if i do a second time and so on forever. Please help!
This is under my saving activity:
public void save(View view){
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString("result",String.format(stringDate, date) + " - " + text_view5.getText().toString());
editor.commit();
Toast.makeText(this, "Saved successfully!", Toast.LENGTH_LONG).show();
}
This is under my loading activity:
resultPhysical = (TextView) findViewById(R.id.home);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String physicalresult = sharedPreferences.getString("result", DEFAULT);
String physicalresult2= sharedPreferences.getString("result2", DEFAULT);
if (physicalresult.equals(DEFAULT)){
Toast.makeText(this,"No Data Found", Toast.LENGTH_LONG).show();
}
else{
resultPhysical.setText(physicalresult);
}
}

You can easily save them, just create an extra variable that refers to the size of saved results so that you can loop over them. To start saving, get the size then save with the index
int size = sharedPreferences.getInt("size", 0); // if it doesn't exist, get 0
// then save the result like
editor.putString("result" + String.valueOf(size), String.format(stringDate, date) + " - " + text_view5.getText().toString()); // just add index to result
// then increase the size
editor.putInt("size", ++size);
editor.commit();
To load the results
StringBuilder results = new StringBuilder();
int size = int size = sharedPreferences.getInt("size", 0); // get the size to start looping
if(size == 0){ // if results are empty
// show toast there is no saved result
} else { //start looping
for(int i = 0; i < size; i++){
String temp = sharedPreferences.getString("result" + String.valueOf(i), DEFAULT);
results.append(temp + " ");
}
resultPhysical.setText(results.toString());
}

Related

How to get values from array in strings.xml in order of each day?

I want to get values ​​from an array every day, respectively, and set these values ​​to a textbox. I can get values ​​from array and set them in textbox but next day value stays same. does not set the next value in array? what can I do?
<string-array name="morning">
<item>Good Morning. Message 1.</item>
<item>Good Morning. Message 2.</item>
<item>Good Morning. Message 3.</item>
</string-array>
mTestArray = getResources().getStringArray(R.array.morning);
preference_shared = this.getSharedPreferences("PREFERENCE", MODE_PRIVATE);
text_shared = this.getSharedPreferences("TEXT", MODE_PRIVATE);
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.DAY_OF_YEAR);
if (timeOfDay >= 0 && timeOfDay < 24) {
if (preference_shared.getBoolean("isFirstRun", true)) {
dailyGreetings.setText(mTestArray[(0) % (mTestArray.length)]);
saveDate();
}else {
if (!Objects.equals(preference_shared.getString("Date", ""), dateFormat.format(date))) {
int idx = new Random().nextInt(mTestArray.length);
dailyGreetings.setText(mTestArray[idx]);
text_shared.edit().putString("TEXT", dailyGreetings.getText().toString()).apply();
saveDate();
}
else {
dailyGreetings.setText(text_shared.getString("TEXT", ""));
}
}
}
It's Easy just
Resources res = getResources();
String[] mornings = res.getStringArray(R.array.morning);
//then use mornings as you use array.
String morning[] = getResources().getStringArray(R.array.morning);
// Solution
SharedPreferences sharedPreferences = getSharedPreferences("my_preference", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String currentDate = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault()).format(System.currentTimeMillis());
String[] msgArrays = getResources().getStringArray(R.array.morning);
String savedDate = sharedPreferences.getString(DATE_KEY, "");
int savedCounter = sharedPreferences.getInt(COUNTER_KEY, 0);
// First time
if (savedDate.isEmpty()) {
editor.putInt(COUNTER_KEY, savedCounter);
editor.putString(DATE_KEY, currentDate);
editor.apply();
} else if (!savedDate.equals(currentDate)) {
// New date appears, update shared preference.
savedCounter++;
if (savedCounter < msgArrays.length) {
editor.putInt(COUNTER_KEY, savedCounter);
editor.putString(DATE_KEY, currentDate);
editor.apply();
}
}
binding.tvTitle.setText(msgArrays[savedCounter]);
In this snipped of code, I'm updating shared preference by date and counter.
Date: It will be saved for next date, and if these both are not matching, shared preference will gets update with counter.
Counter: The position of your strings-arrays.
Reset: I have add another check that if in case your counter reaches to the end of array, it will be reset to '0'.

How to properly append text to TextView from SharedPreferences file instead of overwriting it?

I have two classes, one class is saving weight, then in the other class/ activity I want a log that appends the weight along with the date and time, then makes a new line and displays the next weight. This way the user can keep track of their daily weight changes.
Problem is I'm brand new to Java and clearly am getting stuck on a silly problem. Each time I try append it instead just overwrites. I probably need to save it and then add it? maybe? I've tried a few different things and nothing is working all that well.
This is day 3 of Java. Apologies.
Tried making a list that is saved with sharedpreferences. Either did it wrong or it didnt work. Also tried just calling for the weight and appending it, but it overwrites it all.
My Logging activity:
public class LogActivity extends AppCompatActivity {
TextView logger;
//TextView more;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Button back = findViewById(R.id.btnBack);
logger = findViewById(R.id.txtLog);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
SharedPreferences log = getSharedPreferences("MyPrefsFile", 0);
//Float value = log.getFloat("floatingLog",0);
Float value = log.getFloat("weight", 0);
//more.append(logger + "Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n");
logger.append("Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n");
// Adding back button
back.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v){
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
});
// SharedPreferences settings7 = getSharedPreferences("PREFS",0);
// String wordsString = settings7.getString("words","");
// String[] itemWords = wordsString.split(",");
// List<String> items = new ArrayList<String>();
// for (int i = 0; i < itemWords.length; i++){
// items.add(itemWords[i]);
// }
// for (int i = 0; i < items.size(); i++){
// Log.d("list", items.get(i));
// }
}
}
This is getting the sharedpreferences from here, in my ProfileActivity:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((TextView) findViewById(R.id.txtWeight)).setText(findViewById(R.id.txtNewWeight).toString());
floatingLog = weight.toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
floatingWeight = Float.valueOf(newWeight.getText().toString());
editor.putString("floatingLog", floatingLog);
editor.putFloat("weight", floatingWeight);
editor.apply();
editor.commit();
weight.setText(String.valueOf(floatingWeight));
Hello and welcome to SO!
actually in TextView, you can access to current value via TextView#getText() and after that you can update the text value similarly using TextView#setText(String text)
so you need to write something like this:
String currentText = logger.getText();
String updatedText = currentText + "Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n";
logger.setText(updatedText)
tada !
UPDATE
I think your problem is with how you save your records in your sharedPrefs
in this line
editor.putFloat("weight", floatingWeight); in this part you are overwriting the existing value,
simplest approach that comes to my mind is that instead of saving weight like this, you create an array of weights and append to end of it every day and store the array.
how ever it will be far more better if you use data base for this which gives you far more flexibility.
to use database take a look at Android official orm Android Room it is very simple and straightforward

How to save web page informations?

I want my app to check some web page only once a day, so I want the data to be saved anded reloaded upon starting the app again.
I followed this tutorial, but I can not save the result with MainActivity extends AppCompatActivity:
String url = "https://en.wikipedia.org/wiki/Main_Page";
SharedPreferences data;
SharedPreferences.Editor dataEditor;
String sDate = date.getString("date", "");
DateFormat df = new SimpleDateFormat("MMMM d");
String date = df.format(Calendar.getInstance().getTime());
if(sDate != date){ // <-- this does not work
new Date().execute();
}
and Date extends AsyncTask<Void, Void, Void>:
Document document = Jsoup.connect(url).get();
Elements date = document.select("div#mp-otd p b");
String sDate = date.getText();
dataEtitor.setString("date", sDate)
dataEtitor.commit;
The "Date extends AyncTask" class always start.
editor.commit() is used in order to save changes to shared preferences.
Add below line of code after setString
dataEtitor.commit(); // commit changes
SharedPreferences Example as follow
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Clearing or Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes
You muss use !(sDate.equals(date) in place of sDate != date, because the Strings are new and so they can not be compare each other.

Creating arraylist from a string with shared preferences

I want to know how to take a simple string that is being saved in shared preferences but then save each one of those strings and display them into an array list. The user will save the string once a day. And I want the strings to display as an array list. Here's the code for what I'm working with. I have "physical_fragment.java"(SAVES THE DATA) & "MainActivity.java"(LOADS THE DATA).
PHSYICAL_FRAGMENT.JAVA
public void save(View view){
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString("result",String.format(stringDate, date) + " - " + text_view5.getText().toString());
editor.commit();
Toast.makeText(this, "Saved successfully!", Toast.LENGTH_LONG).show();
}
MAINACTIVITY.JAVA
resultPhysical= (TextView) findViewById(R.id.home);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String result= sharedPreferences.getString("result",DEFAULT);
if (result.equals(DEFAULT))
{
Toast.makeText(this, "No data found", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(this, "Load Successful", Toast.LENGTH_LONG).show();
resultPhysical.setText(result);
}
I'd say use GSON for that.
To convert a list of strings to JSON to be stored in preferences you use this:
List<String> list = ...
Type type = new TypeToken<List<String>>(){}.getType();
String json = gson.toJson(list, type);
and store json in SharedPreferences using putString.
To read from SharedPreferences you use something like this:
String result = sharedPreferences.getString("result", DEFAULT);
Type type = new TypeToken<List<String>>(){}.getType();
List<String> list = gson.fromJson(result, type);
you can do as follows:
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
ArratList<String> dataList;
String data = "";
for(String itemData:dataList){
data = itemData + String.format(stringDate, date) + " - " + text_view5.getText().toString()+ "/";
editor.putString(data);
}
editor.commit();
Now get the string from Shared preference and split it.
String result= sharedPreferences.getString("result",DEFAULT);
String[] splited = str.split("/");
This helps with out having support of Libraries which can effect size of apk file

Null Pointer using SharedPreferences

I am passing and showing values from one activity to another activity, and making file name using those string like this:
AU_20140312_160107_65.jpg
AU - simple prefix
20140312_160107 - yyyyMMdd_HHmmss
6 - event_id (getting from LoginActivity.java)
5 - operative_id (getting from LoginActivity.java)
see my code below:
LoginActivity.java:
static SharedPreferences sharedprefs;
static String event_id, operative_id ;
sharedprefs = getApplicationContext().getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
Intent intent = getIntent();
event_id = intent.getStringExtra("event_id");
sharedprefs.edit().putString("EVENT_ID", event_id).commit();
operative_id = intent.getStringExtra("operative_id");
sharedprefs.edit().putString("OPERATIVE_ID", operative_id).commit();
CameraLauncherActivity.java:
static File getOutputMediaFile() {
String event_ID = LoginActivity.sharedprefs.getString("EVENT_ID", null);
Log.d("shared >>> eventID : ", event_ID);
String operative_ID = LoginActivity.sharedprefs.getString("OPERATIVE_ID", null);
Log.d("shared >>> operativeID : ", operative_ID);
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
// file name
mediaFile = new File(LoginActivity.mediaStorageDir.getPath() + File.separator
+ "AU_" + timeStamp + "_" + event_ID + operative_ID + ".jpg");
return mediaFile;
}
when launching first time, Log says:
shared >>> eventID :(29917): 12
shared >>> operativeID :(29917): 4
like you can see above, everything works fine, and getting eventID and operativeID using log as well
but once i will launch my app again, after closing it, and caputre image, then getting NPE and Log :
FATAL EXCEPTION: main
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:155)
app.mac.Camera.CameraLauncherActivity.getOutputMediaFile(CameraLauncherActivity.java:386)
at app.mac.Camera.CameraLauncherActivity$2.onPictureTaken(CameraLauncherActivity.java:362)
at android.hardware.Camera$EventHandler.handleMessage(Camera.java:789)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1036)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:803)
at dalvik.system.NativeStart.main(Native Method)
Instead of assigning the values directly to the variables event_id and operative_id store them in the db or preferences.
Instead of directly assigning like this this :
event_id = intent.getStringExtra("event_id");
operative_id = intent.getStringExtra("operative_id");
check the intent.getStringExtra("event_id") and intent.getStringExtra("operative_id") for null.
If null fetch from stored values.
If not null assign to variables and overwrite stored values with the new one for next time.
//Initialization
SharedPreferences _mypref = getApplicationContext().getSharedPreferences("mypref", 0);
//store data in shared preferences
Editor editor = _mypref.edit();
//Storing boolean - true/false;
editor.putBoolean("key_name", true);
//Storing string
editor.putString("key_name", "string value");
//Storing integer
editor.putInt("key_name", "int value");
//Storing float
editor.putFloat("key_name", "float value");
//Storing long
editor.putLong("key_name", "long value");
//commit changes
editor.commit();
// retrive data
//getting String
_mypref .getString("key_name", null);
//getting Integer
_mypref .getInt("key_name", null);
//getting Float
_mypref .getFloat("key_name", null);
//getting Long
_mypref .getLong("key_name", null);
//getting boolean
_mypref.getBoolean("key_name", null);
//remove Data
editor.remove("name");
editor.commit();
//Clear all Data
editor.clear();
editor.commit();

Categories