Saving data in file onStop and reading it in onCreate - android

I'm creating and saving data in a file in the onPause of the Base Activity but I'm reading the information in the onCreate of other activities. The thing is, the onPause saving has been called and no errors seem to appear in the logcat. However if I try to read the info in the onCreate I'm receiving the old content I had there, instead of the new one I saved.
public String parseToJsonString(Object object){
String json = gson.toJson(object);
return json;
}
public static boolean save(Context ctx, String filename, String content){
boolean wasSaved = false;
FileOutputStream fos = null;
try {
fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.flush();
wasSaved = true;
Log.d(TAG, content);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return wasSaved;
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
String jsonSettings = APP().parseToJsonString(settings);
FileUtil.save(this, getString(R.string.file_settings_preferences), jsonSettings);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getResources().getBoolean(R.bool.phone_size))
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.att_base_activity);
preferences = APP().getSecuredPreferences();
workflow = APP().createWorkflow();
settings = getAttendanceSettings();
Log.d(TAG, settings.toString());
toolbar = (Toolbar) findViewById(R.id.ab_tool_bar);
setSupportActionBar(toolbar);
}
public AttSettings getAttendanceSettings() {
AttSettings settings = null;
try {
JSONObject jsonSettings = FileUtil.getJSONContentFromFile(this,
getString(R.string.file_settings_preferences));
if (jsonSettings != null)
settings = new AttSettings(jsonSettings);
else
settings = new AttSettings();
} catch (IOException e) {
e.printStackTrace();
}
return settings;
}
I really don't know what I'm doing wrong, help would be appreciated.

Related

Android - How to clear sharepreference by position recyclerview

Here is my code that I got share preference
private void getAllSharePreference() {
SharedPreferences sharedPreferences = getContext().getSharedPreferences(SharePreferenceKey.SONG_LIST, Context.MODE_PRIVATE);
getSongJson = sharedPreferences.getString(SharePreferenceKey.SONG_LIST, "N/A");
if (!getSongJson.equals("N/A")) {
Type type = new TypeToken<List<SongRespones.Songs>>() {}.getType();
songSharePreference = new Gson().fromJson(getSongJson, type);
adapter.addMoreItem(songSharePreference);
rvFavorite.setAdapter(adapter);
}
}
This is my code that I want to clear list in share preference by position recyclerview.
#Override
public void onClickView(final int position, View view) {
final PopupMenu popupMenu = new PopupMenu(getContext(), view);
popupMenu.inflate(R.menu.remove_favorite);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.popup_remove_favorite:
songSharePreference.remove(position);
adapter.notifyItemChanged(position);
break;
}
return false;
}
});
popupMenu.show();
}
But I cannot clear share preference.
Please help me:
If u want to clear all data from SharedPreferences, this is the way to clear all data of this "SharePreferenceKey.SONG_LIST".
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.popup_remove_favorite:
songSharePreference.remove(position);
adapter.notifyItemChanged(position);
SharedPreferences sharedPreferences =
getContext().getSharedPreferences(
SharePreferenceKey.SONG_LIST, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
constants.editor.clear();
constants.editor.commit();
break;
}
return false;
}
i suggest u to use file to save and retrieve an object. It's easy to use and handle.
private void saveDataToFile() {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = getContext().openFileOutput("fileName", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
try {
if (objectOutputStream != null) {
objectOutputStream.writeObject(yourObject); //which data u want to save
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Retrieve data from file
private void getDataFromFile() {
FileInputStream fileInputStream = null;
try {
fileInputStream = getContext().openFileInput("fileName");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
} catch (IOException |NullPointerException e) {
e.printStackTrace();
}
try {
yourObject = (ObjectClass) objectInputStream.readObject(); //if arraylist then cast to arrylist ( (ArrayList<ObjectClass>) objectInputStream.readObject();)
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

ANDROID: How to save JSON data in a file and retrieve it?

I'm new to android so please help me out. I am trying to save my ToDoList in a file so that the next time I open it, all the items are reloaded
This is the code I have so far,
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader("storage.json"));
Entry e = gson.fromJson(br, Entry.class);
Log.d("reading", e.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}}
#Override
protected void onStop() {
super.onStop();
json = gson.toJson(mEntries);
Log.d("jsondata", json);
try {
file1 = new FileWriter("storage.json");
file1.write(json);
file1.flush();
file1.close();
} catch (IOException e) {
e.printStackTrace();
}
Entry.java
public class Entry {
String S;
boolean b;
public Entry(String S, boolean b) {
this.S = S;
this.b = b;
}
public String getS() {
return S;
}
public void setS(String S) {
this.S = S;
}
public void setB(boolean b) {
this.b = b;
}
public boolean isB() {
return b;
}
}
How do I proceed from here? In onCreate() I would like to check if the file exists and if yes, import data from file and display on screen.
Every android app has its own internal storage only that app can access, you can read from there or write to it.
In you case, you first want to check if you such file exist before creating one.
private String read(Context context, String fileName) {
try {
FileInputStream fis = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (FileNotFoundException fileNotFound) {
return null;
} catch (IOException ioException) {
return null;
}
}
private boolean create(Context context, String fileName, String jsonString){
String FILENAME = "storage.json";
try {
FileOutputStream fos = context.openFileOutput(fileName,Context.MODE_PRIVATE);
if (jsonString != null) {
fos.write(jsonString.getBytes());
}
fos.close();
return true;
} catch (FileNotFoundException fileNotFound) {
return false;
} catch (IOException ioException) {
return false;
}
}
public boolean isFilePresent(Context context, String fileName) {
String path = context.getFilesDir().getAbsolutePath() + "/" + fileName;
File file = new File(path);
return file.exists();
}
onCreate of the Activity, you can use do the following
boolean isFilePresent = isFilePresent(getActivity(), "storage.json");
if(isFilePresent) {
String jsonString = read(getActivity(), "storage.json");
//do the json parsing here and do the rest of functionality of app
} else {
boolean isFileCreated = create(getActivity, "storage.json", "{}");
if(isFileCreated) {
//proceed with storing the first todo or show ui
} else {
//show error or try again.
}
}
reference https://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Process Dialog not showing ( Android / AsyncTask )

Someone please read my code its given below,
the process dialog is not showing up,
seems like a minor mistake :D
Thanks in advance.
public class InternalData extends Activity implements OnClickListener {
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String FILENAME = "internalString";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedprefs);
InitializeVars();
}
public void InitializeVars() {
Button save = (Button) findViewById(R.id.bSave);
Button load = (Button) findViewById(R.id.bLoad);
sharedData = (EditText) findViewById(R.id.etSharedPrefs);
dataResults = (TextView) findViewById(R.id.tvSharedPrefs);
save.setOnClickListener(this);
load.setOnClickListener(this);
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bSave:
String data = sharedData.getText().toString();
/*
* //Saving data via File File f = new File(FILENAME); try { fos =
* new FileOutputStream(f); fos.close(); } catch(IOException e) {
* e.printStackTrace(); }
*/
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.bLoad:
new loadSomeStuff().execute(FILENAME);
break;
}
}
public class loadSomeStuff extends AsyncTask<String, Integer, String> {
ProgressDialog dialog = new ProgressDialog(InternalData.this);
protected void onPreExecute(String f) {
// dialog = new ProgressDialog(InternalData.this)
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
// all this can be done without making this whole AsyncTask class,
// but it will exaust our activity user interface, / slow it down
String collected = null;
FileInputStream fis = null;
for (int i = 0; i < 20; i++) {
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
dialog.dismiss();
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1) {
collected = new String(dataArray);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
return collected;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
dialog.incrementProgressBy(progress[0]);
}
protected void onPostExecute(String result) {
dataResults.setText(result);
}
}
}
Change your onPreExecute() you're using it wrong, you should this instead
#Override
protected void onPreExecute() {
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}

saving data to interal memory with async task (newboston tutorials sample) error it has progress bar

this is my first post here
i'm new, so be good with me!
i'm following travis's tutorials and it goes to saving data and using async task
i really focused but i can't find out whats wrong with my code, so i posted here! :
I added the logcat!
it worked without async and progress bar (both save and load)
latest changes!:
i fixed the progress bar but loadwithasync class is not working, i mean this line:
I think this must return the Srting ld and set that in text view res. but it is not looking this way! why travis from mybringback! didn't wrote the line like Strig s = new loadWith..... ? can u tell me where is the problem! i'm confused and i don't know how to debug properly!!
new loadWithAsyncTask().execute(FILENAME);
public class SaveAndLoadInternal extends Activity implements OnClickListener {
EditText file, data;
TextView res;
FileInputStream fis;
FileOutputStream fos;
String FILE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.save_load_internal);
Button load, save;
file = (EditText) findViewById(R.id.etSLIfile);
data = (EditText) findViewById(R.id.etSLIdata);
res = (TextView) findViewById(R.id.tvSLIres);
load = (Button) findViewById(R.id.bSLIload);
save = (Button) findViewById(R.id.bSLIsave);
// set file and close it!
load.setOnClickListener(this);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
FILE_NAME = file.getText().toString();
switch (v.getId()) {
case R.id.bSLIload:
//Commented just for doing some tweaks! run
//loading process in another thread to give UI thread rest :D for avoid hanging!
FileInputStream fis = null;
String ld = "LOADING FAILED!";
/* try {
fis = openFileInput(FILE_NAME);
byte[] b = new byte[fis.available()];
while (fis.read(b) != -1) {
ld = new String(b);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
res.setText(ld);
*/
new loadWithAsyncTask ().execute(FILE_NAME);
// execute will run doInBackground method!
break;
case R.id.bSLIsave:
String sd = data.getText().toString();
/*
// one way to save in file is below! must work but it isn't!
File f = new File(FILE_NAME);
try {
fos = new FileOutputStream(FILE_NAME);
fos.write(sd.getBytes());
fos.close();
res.setText("SAVING DONE!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
*/
try {
fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fos.write(sd.getBytes());
fos.close();
res.setText("SAVING DONE!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
// /*
// first param: what is being passed in (FILE_NAME)
// second param for progress bar (we use integer here)
// third one is what we will return! (the saved text! String ld)
public class loadWithAsyncTask extends AsyncTask<String, Integer, String>{
ProgressDialog pd;
String Ld = "LOADING FAILED!";
FileInputStream fis = null;
// this gonna called first
#Override
protected void onPreExecute(){
// example: setting up variables or something else!
pd = new ProgressDialog(SaveAndLoadInternal.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMax(100);
pd.show();
}
#Override
protected String doInBackground(String... params) {
//for progress dialog
for(int i =0 ; i< 20 ; i++){
publishProgress(5);
try {
Thread.sleep(88);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pd.dismiss();
try {
fis = openFileInput(FILE_NAME);
byte[] b = new byte[fis.available()];
res.setText(String.valueOf(fis.available()));
while (fis.read(b) != -1) {
Ld = new String(b);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
//return the string!
return Ld;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
// progress of loading in example!
#Override
protected void onProgressUpdate(Integer...progress){
pd.incrementProgressBy(progress[0]);
}
}// */
}
When you look at the error, you'll see that onProgressUpdate() throws a NPE. Looking at the code, there are two possibilities: 1. pd is null or 2. progress is null. Add a breakpoint or some logging there to see what exactly is going on.
protected void onProgressUpdate(Integer...progress){
pd.incrementProgressBy(progress[0]);
}

Android, write to file using inheritance

I am currently saving a message to a single file from multiple activity classes within my app. Each activity class has the same function WriteToFile.
public void WriteToFile(String info) {
FileOutputStream FoutS = null;
OutputStreamWriter outSW = null;
try {
FoutS = openFileOutput("file.txt", MODE_PRIVATE);
outSW = new OutputStreamWriter(FoutS);
outSW.write(info);
outSW.flush();
}
catch (Exception e) {
}
finally {
try {
outSW.close();
FoutS.close();
} catch (IOException e) {
}
}
}
I have been attempting to create a separate class which holds this function write (and read) to file but I haven't been able to without getting errors.
I think the function needs to have context passed through to the WriteToFile void like...
//Changes to this line
public void WriteToFile(String info, Context context) {
FileOutputStream FoutS = null;
OutputStreamWriter outSW = null;
try {
//Changes to this line
FoutS = context.openFileOutput("file.txt", MODE_PRIVATE);
outSW = new OutputStreamWriter(FoutS);
outSW.write(info);
outSW.flush();
}
catch (Exception e) {
}
finally {
try {
outSW.close();
FoutS.close();
} catch (IOException e) {
}
}
}
if that is correct am I passing the context correctly?
String msg = "This is a message";
WriteToFile(msg, this);
It's not working so I am doing something wrong.
You should use your context to call the method
context.openFileOutput("file.txt", context.MODE_PRIVATE);
what you wrote has no meaning, or far from what you mean.

Categories

Resources