I am trying to read a CSV file and have it display the contents as a basic list for an Android app. I am using the method given by Kopfgeldjaeger in this thread.
I have added a couple of 'toasts' which either display 'success' or 'fail' at the bottom of the Android screen if the code managed (or didn't manage) to load the CSV file properly. See below:
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("file.csv")));
for(;;) {
next = reader.readNext();
if(next != null) {
list.add(next);
} else {
break;
}
}
Toast.makeText(getApplicationContext(), "SUCCESS",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "FAIL",
Toast.LENGTH_SHORT).show();
}
When I load the app, I get the 'SUCCESS' message, so all is well so far. Now, I'd like to see if I can load any of the data. In Kopfgeldjaeger's answer, it is suggested that I could access a string using the following code:
list.get(1)[1]
So, in order to check that it's worked, I try to generate another toast, as follows:
Toast.makeText(getApplicationContext(), list.get(1)[1],
Toast.LENGTH_SHORT).show();
This added toast causes the program to fail to load properly. The question is, have I gotten the toast syntax wrong, or is my CSV file not loading properly?
There are a couple of things to check:
Make sure your csv file has a size of at least 2 x 2 entries, otherwise retrieving the data from line index 1 and column index 1 won't work. For example, print or debug list.size() and list.get(0).length to see if they're both at least 2.
Confirm that your csv file is actually comma separated, and not e.g. semicolon separated. I have seen occassions where certain software seems to choose its own delimiter.
As a recommendation: the referenced csv reader is part of ByteCode's OpenCSV. You may want to include the latest source code or jar from that project. It supports custom delimiter characters and also provides a shorthand for parsing all the csv data into a list of string arrays:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();
Related
I'm working on an app built using Firebase on Android. The application is for keeping track of in-patients currently under our care. Our team can enter progress notes for each patient, and add tasks needed yo be performed for each patient, and mark them when they're done. I have all that done, however, I need to add one more option, where I can select a patient, and export the current view (with all the many-to-one data associated with the main record) to an external file (editable file), so we may use it to write his/her final report and summary. I've searched online, and found many recommending to export the view as a bitmap, then to pdf ... but that makes the document un-editable .. If someone has any ideas, or can point me to the right direction, I'd be grateful. The final format is not really an issue ... pdf, txt, doc, html .... I guess it doesn't really matter, as long as the data can be exported as it is in the current view (ordered and making sense), and can be edited.
Any help will be appreciated. Thank you.
I once made an app with the option to export data to a txt file on the device storage. Here's the method I used:
public void exportTxt(String text){
if(Environment.getExternalStorageState().equalsIgnoreCase("mounted"))//Check if Device Storage is present
{
try {
File root = new File(Environment.getExternalStorageDirectory(), "MyAppFolder");//You might want to change this to the name of your app. (This is a folder that will be created to store all of your txt files)
if (!root.exists()) {
root.mkdirs();
}
File myTxt = new File(root, "filename.txt"); //You might want to change the filename
FileWriter writer = new FileWriter(myTxt);
writer.append(text);//Writing the text
writer.flush();
writer.close();
Toast.makeText(this, "File exported", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Error: "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else
Toast.makeText(this, "Can't access device storage!", Toast.LENGTH_SHORT).show();
}
Don't forget to add this permission to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
So in order to use this method, all you need to do is group all of your currentView data on a single String and pass it as a parameter.
I'm trying to get my game to save the scores to a text file, which I later want to read from. However I cannot seem to get my scores to actually be stored on the file?
Also I eventually would like to be able to only store the top 10 scores, so overwrite a score if it is higher than one in the file? What would be the best means of going about this?
Thanks!
public void saveGame(Integer score){
try {
OutputStreamWriter osw = new OutputStreamWriter(getGame().getFileIO().writeFile("storetxt.txt"));
osw.write(score);
osw.close();
}
catch (IOException e){
Log.e("Exception", "Couldn't write to file: " + e.toString());
}
}
To store 10 scores I would use SharedPreferences. You can find some code examples in the link (they even use high-score as the example).
With some adjustments you can use it to store top 10 scores.
I have a little problem. Hopefully you can help me.
I have to keep the scores of a game in a txt file. At the end of the game, I give it a name (no matter what). first i have to write that name to a txt file with the related score. Now my question is how to write something to a file in the Assets folder. Then I have to show that scores in a text view.
You cannot write to the assets folder (see this answer). While you still can write the score to a file (see this answer) I would suggest that you instead write the data pertaining to each game to a database. Database support in Android is great and this would allow for a central store for all the data of all your games. This would make it easier to handle, compare and etc.
I think this can solve your problem
File f = new File(Environment.getExternalStorageDirectory(), "ScoreDetails.txt");
try {
StringBuilder scoreDetails = new StringBuilder();
scoreDetails.append("Score - A");
scoreDetails.append(" \nScore - B");
PrintWriter pw = new PrintWriter(f);
pw.append(scoreDetails.toString());
pw.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any confusion.Please let me know
I got a little problem, it seems simple (personally I think it is), but I couldn't find a answer. But atleast I don't know how to fix it.
I write some lines to a .txt file when I hit the button Save.
Then after that, when I type something else, and hit Save again, it overwrites my first lines.
But I want that it writes at a new line. Also when I close and restart the app again, and hit save again, it must save the text on a new line again.
So basically: How can I write text to a .txt file, without overwriting previous lines.
I can write to a file, so that is not the problem, but only how to NOT overwrite.
This is the "little" part of my code:
public void Data_save_contacts(View v) {
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
try {
writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt"));
writer_contact.write("Perceel "+str_boer_teler_nummer+" = "+str_boer_teler);
writer_contact.newLine();
} catch (IOException e) {
System.err.println(e);
}
}
Please put me in the good directions.
Thanks already, Bigflow
You have to do
writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt",true));
Just as said in java documentation:
FileWriter
public FileWriter(File file,
boolean append)
throws IOException
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file rather than the beginning
try:
public FileWriter (File file, boolean append)
set the append to true
Well given this is just a little of your code (and I'm assuming you chunked it out so as to not reveal other parts) what I suspect is going on is that you're opening the file root + "/Save/Contacten.txt" in a non-append mode. The first time you call it the file is created and written to. Subsequent times you call it, it finds the file, and recreates (or deletes content) and then writes to it.
Try using:
writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt", true));
Of course the first time you open/create the file you'll want it to be false (unless you ALWAYS want to append if the file already exists).
Give that a spin.
you can check for if file exits or not ?
or you can also append old file.
If not exits then and then only create new one.
My application contains a listview. Each listitem contains out of a imageview and a textview.
For showing the image i need check if the image exists in de application data folder.
My code works in the most situations, but there is 1 situation where the application crashes every time i try.
I use the following code to check if the image exists:
File file = new File(imgHelper.getSaveImageDirectoryThumb1(imageUrl));
if(file.exists()){
//show image
}
Sometimes i get the following error, else the get view gets closed without giving a error..
Is there anyone who have a clue to make sure the application won't crash or close the view?
Well, as you did not give more code or the exact error message, I suppose there is something wrong with the
imgHelper.getSaveImageDirectoryThumb1(imageUrl)
This might return NULL. Apart from checking if file!=null you should also have a look at the code mentioned above.
A try catch should catch any errors you are getting
try{
File file = new File(imgHelper.getSaveImageDirectoryThumb1(imageUrl));
if(file){
//the file is here
}else{
//display error
}
catch(Exception e){
//Error message
}