my history objects only have 2 fields (id + name). i have to save them. i used sharedpreferences because this is just perfect to save key-value pairs. problem is..there is no possibilty to change to location where the files are saved. i dont want to save them into the sharedpref folder because i want to give the user of the app the possibility to delete all history entries. i have to check which files are history files and which files are preferences files used by the app. this is no proble..but dirty imo. on the other hand..my history files shouldnt be in sharedpref folder..they have nothing to do in that folder..
the other possibility is to store the data in internal storage as xml for example. i would have to write a serializer and parser.
the third possibility (i just remembered writing this question)is to save it via Java Properties. this is probably the easiest solution. its like sharedpref
the last possibility is to store it in sqlite. i dont know..my data is so tiny..and i use a databae to store it?
my question is simply..what do u recommend to use and why. what do you use? same question belongs to the autocomplete values. id like to save the values the user once entered in a textfield. where to save them? where do you save such data?
thx in advance
You can create a separate sharedpreferences file for your history using (say) Context.getSharedPreferences("history") which will create a sharedpreferences file as follows.
/data/data/com.your.package.name/shared_prefs/history.xml
But I'm pretty sure that all sharedpreferences files will be created in /data/data/com.your.package.name/shared_prefs/. I don't think you can change the location.
I may be mis-interpreting your objective but for something like this I would just straight-up use a BufferedWriter from java.io.BufferedWriter to write a new file for each object. Likewise you can read the data with a BufferedReader. The code would look something like this:
public static void save(FileIO files){
BufferedWriter out = null;
try{
//use a writer to make a file named after the object
out = new BufferedWriter(new OutputStreamWriter(
files.writeFile(objectSomething)));
//the first line would be ID
out.write(Integer.toString(objectID));
//second line would be the name
out.write(objectName)
//Theres two possible IOexceptions,
//one for using the writer
//and one for closing the writer
} catch (IOException e) {
} finally {try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this example, I have used "objectSomething" as the string name of the file, objectID and objectName are the int and string respectively that your file contains.
to read this data, pretty straightforward:
public static void load(FileIO files) {
BufferedReader in = null;
try {
// Reads file called ObjectSomething
in = new BufferedReader(new InputStreamReader(
files.readFile(ObjectSomething)));
// Loads values from the file one line at a time
varID = Integer.parseInt(in.readLine());
varName = in.readLine();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
here, I've used varID and varName as local variables in this class that you would use if you needed them in your code throughout your application.
Related
I have an android application that collects data from a sensor via Bluetooth.
When trying to save the data to a .csv-file on the device, the data.csv-file gets created but no text is saved in the file.
The function in question:
private void writeData(boolean writeError) {
try {
File traceFile = new File(Environment.getExternalStorageDirectory(), writeError ? "error.csv" : "data.csv");
if (!traceFile.exists())
traceFile.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(traceFile, true /*append*/));
writer.write("Test string");
} catch (Exception e) {
e.printStackTrace();
}
}
No error is thrown and I've made sure that each part of the code gets executed. Any ideas as to why this doesn't work?
Solution by Hurundi V. Bakshi
Added
writer.flush();
after
writer.write("Test string");
Documentation on flush():
Flushes this writer. Implementations of this method should ensure that all buffered characters are written to the target.
I just started to learn developping android and I have a (probably) basic questions, but I didn't find anything clear.
I'm trying to store data in a JSON file, well, I've understood the logic to store it, my way is:
public boolean writeFileJson(JSONObject jobj) {
try {
FileOutputStream fOut = openFileOutput(file, Context.MODE_PRIVATE);
fOut.write(jobj.toString().getBytes());
fOut.close();
Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
} catch (Exception e1) {
e1.printStackTrace();
}
return true;
}
But my problem is to read, and concretely for the first time, because the way I do it is:
public String readFileJson() {
int c;
String temp = "";
try {
FileInputStream fin = openFileInput(file);
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
} catch (Exception e2) {
}
return temp;
}
So wen I read it for the first time and I want to acces to a parameter of my JSON is obvious that any JSON Object already exist in the file.
So I try to save a first JSON Object with my parameters in onCreate() method and save it in the file, but wen I run the app, and I stop it, it returns again to execute onCreate() and deletes all data stored during the run time.
So my question is: There is any way to init only for one time the parameters of the JSON file to could access for the first time unlike it's empty???
I hope that I'd explained well!!
Thanxxxx!!!!
You can create your own flag boolean and check when you start.
Well I don't understand well why you can use a flag if the flag is set to init value in onCreate(), but I've tried a basic method: check each time if the json file is null. But it's like so basic no? Is there any ther way, or trying to understand how to use flags without reset their values?
msgjson = readFileJson();
if(msgjson == "") {
json.put("ARRAY", jsonArray);
}else{
json = new JSONObject(msgjson);
}
Thanx!!
I'm new to Android development and I will appreciate any help I can get.
I'm designing an app that at some point needs to ask user for his Friends' names in order to work with those names later on, i.e those names will be used in drop-down lists and will be displayed at a separate View.
My question is: what is the best way to efficiently store those names and then be able to get access to them for reading, editing and deleting? The amount of names will not be big (at most 20 items).
In response to the comment about adding more info:
I need a user to specify list of names (strings) that will be used in 2 different Android Activities:
1) This list of names will be used in a Spinner that is a part of an application form
2) This list of names will be used on a separate Activity designed for Manipulating (Editing and Deleting) of existing items and adding new ones.
I also need that after manipulations (editing, deleting and creating new items) with this list changes took place in Both Activities. This list should be available after user exits the app, so as I understand it should be stored somewhere in Internal Storage.
I hate when people answer a question by just posting the link to the docs, so I won't do that.
I will post the link to the docs AND provide an answer:
DOCS: http://developer.android.com/guide/topics/data/data-storage.html
(it is actually a good read, not too long, and good to know what your options are).
It looks to me you need to save an ArrayList or something, and you are saying 20 names would be the maximum amount, so I would say you have 3 viable options, which I present here, ordered in ascending order of simplicity using my humble opinion as a comparator:
1- InternalStorage
2- SharedPreferences
3- Very interesting way I just found while researching one of the options to help you, and I will definatelly use this when I need to save a small array of data...
So the steps I would recomend are: put the names in your favourite collection object (ArrayList, HashSet, etc), then refer to those examples for the methods cited above, respectivelly:
1- https://stackoverflow.com/a/22234324/367342 (YES, this a link to a answer given on this thread, I voted it up, I feel better for cheating now).
2- Save ArrayList to SharedPreferences
3- https://stackoverflow.com/a/5703738/367342 <- this
- Convert your data to a JSONObject
- Convert it to a string
- Save this string using shared preferences
- Read it later as a jsonobject
Example on 3 (untested, sorry):
//Convert the ArrayList to json:
JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(items));
//Make it into a string
String myLittleJason = json.toString();
//save it to the shared preferences
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("KEY_TO_THE_NAMES_OF_MY_DEAR_FRIENDS", myLittleJason).commit();
//Loading it back from the preferences
String loadedJsonString = PreferenceManager.getDefaultSharedPreferences(context).getString("KEY_TO_THE_NAMES_OF_MY_DEAR_FRIENDS", "I have no friends, this is the default string returned if the key was not found, so, jokes aside, better make this a empty JSON string");
//making it into a JSON again
JSONObject loadedJson = new JSONObject(loadedJsonString);
//Converting the Json back into a ArrayList
ArrayList items = loadedJson.optJSONArray("uniqueArrays");
I loved that JSON approach, if you like it too, upvote the original (too ;) ) https://stackoverflow.com/a/5703738/367342
If you are going to store only 20 items, maybe the best way is to write and read a file.
public void writeItems(String fileName) {
final String ls = System.getProperty("line.separator");
BufferedWriter writer = null;
try {
writer =
new BufferedWriter(new OutputStreamWriter(openFileOutput(fileName,
Context.MODE_PRIVATE)));
writer.write("Item 1" + ls);
writer.write("Item 2" + ls);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void readItems(String fileName) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(openFileInput(fileName)));
String line;
while ((line = input.readLine()) != null) {
//do something
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
openFileInput and openFileOutput reference : http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
You have many options but I will give you two options:
SharedPreferences
SQLLite
If it's temporary and doesn't require intense data manipulation, I would go with SharedPreferences as it's easier to setup and easy to use and recycle.
My Program needs to be able to scan a text file, and store the values of the text file into a database.
Suppose I've read in a line of code that looks like this
3,95003,"ALLENDALE",,41.030902,-74.130957,2893
I want to be able to call a part of the string and store it as a database value. How exactly would I do that? I already know how to read in text files, but i need to know how to filter and only grab a part of them.
In a database I would usually add a value by doing something like this.
values.put("A", "B");
How can i read a value from only part of the textfile into B?
Say I want it to display values.put("A", "ALLENDALE").
Answer:
AgencyString = readText();
tv = (TextView) findViewById(R.id.letter);
tv.setText(readText());
StringTokenizer st = new StringTokenizer(AgencyString, ",");
while (st.hasMoreElements()) {
tv.setText(st.nextToken());
}
}
private String readText() {
InputStream inputStream = getResources().openRawResource(R.raw.agency);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
The next step for me is to store these values seperated into an array, and read them into my database. I was able to filter through my agency.txt file by using a StringTokenizer method and setting a 'comma' as my delimiter.
Look at. Use delimiters ",".
http://developer.android.com/reference/java/util/StringTokenizer.html
http://developer.android.com/reference/java/lang/String.html#split(java.lang.String)
http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String, int)
I have a CSV file in drawable/asset folder. In the CSV file there are four columns. First one is for date and rest three are for integer data.
I need to parse this CSV file and save the data in separate arrays.
I have searched for a solution, but I don't get proper idea on how to do this.
I like this csv reader: https://mvnrepository.com/artifact/net.sf.opencsv/opencsv/2.3
Just add it to your project.
Example code (assuming there is the file assets/test.csv):
String next[] = {};
List<String[]> list = new ArrayList<String[]>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("test.csv")));
while(true) {
next = reader.readNext();
if(next != null) {
list.add(next);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
You can access the imported data with, for example,
list.get(1)[1]
That would return a string.