How to Read and Write to a csv file in Android? - android

I want to store 8 integers into a .csv file(the filename will be taken as an input from a EditText) and retrieve them when I want to.

To get the filename you can use this:
EditText fileNameEdit= (EditText) getActivity().findViewById(R.id.fileName);
String fileName = fileNameEdit.getText().toString();
Then write the file on disk:
try {
String content = "Separe here integers by semi-colon";
File file = new File(fileName +".csv");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
To read the file:
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(fileName+".csv"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Then to have the Integers you can use split function:
String[] intArray = sCurrentLine.split(";");

Opencsv doesn't work on Android due to JDK issue.
If you see simular to the following:
05-04 16:13:31.821 25829-25829/? E/AndroidRuntime: FATAL EXCEPTION:
main Process: com.example.pk.opencsvpoc, PID: 25829
java.lang.NoClassDefFoundError: Failed resolution of:
Ljava/beans/Introspector;
It is because Android only ported over a subset of java.beans into its
version of java. You can see a list of what is support at
https://developer.android.com/reference/java/beans/package-summary
There are plans to switch over to reflection in opencsv 5.0 but I
doubt it will remove all our dependencies on java.beans. For now the
best suggestion for opencsv is to steer clear of the com.opencsv.bean
classes until Android fully supports java.beans or we are successful
in removing java.beans.
Another possibility is to try another csv library. I checked apache
commons csv and super-csv and apache does not convert to beans but
super-csv does using only reflection.
Source: https://sourceforge.net/p/opencsv/wiki/FAQ/#getting-noclassdeffounderror-when-using-android

CSV is normal text file, where values are divided by character ";" so, you can write it using BufferedWriter for example.
BufferedWriter

Related

Storing multi color text using a file in android

I'm currently working on an android project which allows user to write text using different colors and store them for later use(i.e., editing or reading).
Is their any way to store a file in android with multi color text ??
NOTE: I googled out for the solution but can't find anything useful.
I'm guessing the user has to perform some action to switch color?
If so - you can use that trigger to store the text position/length when switching and save a list of text position - color.
A commenter suggested HTML, and that may be a good choice. You are welcome to try Html.fromHtml() to populate your EditText with the contents of a simple HTML-formatted file, and you are welcome to try Html.toHtml() to generate HTML from the contents of your EditText. However, historically, those methods were not written to do a good job of implementing a "round trip", meaning that the contents of the EditText may wind up changing from its starting point to what it contains after doing Html.toHtml() (to generate and save the HTML) and Html.fromHtml() (to populate the EditText with the previously-saved HTML). If they do not work, you can either fork that Html class and try to modify it as needed, or write your own code to take a Spanned object and convert it to/from HTML, by examining the spans and generating HTML tags from them.
PROBLEM SOLVED:
Code for storing a multi color text from EditText to a txt file:
protected void onDestroy() {
super.onDestroy();
boolean writing_allowed= ExternalStorageWriting.isWritingPossible();
if(writing_allowed)
{
String store= Html.toHtml(et.getEditableText());
File myExternalFile = new File(getExternalFilesDir(filepath), filename3);
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(store.getBytes());
fos.close();
} catch (Exception e) {
Toast.makeText(Notes.this, "Something went wrong...", Toast.LENGTH_SHORT).show();
}
}
}
Code for reading that txt file and displaying it in EditText :
private void setNotes()
{
String myData="";
try {
File myExternalFile = new File(getExternalFilesDir(filepath), filename3);
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
Spanned htmlText = Html.fromHtml(myData);
et.setText(htmlText);
}

Can not read text files

I am trying to write and read a text file which is full of words and add it to an ArrayList. The ArrayList later is used from another part of the program to display text in a TextView. But when i run the program and open the specific part of it, then there is nothing. The ArrayList is just empty. I don't get any exceptions but for some reason it doesn't work. Please help me.
I don't seem to have problems with the file writing:
TextView txt = (TextView)findViewById(R.id.testTxt);
safe = txt.getText().toString();
try {
FileOutputStream fOut = openFileOutput("test.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(safe);
osw.flush();
osw.close();
Toast.makeText(getBaseContext(), "Added to favorites", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException ex){
Log.e("Exception", "File write failed: ");
}
} catch (IOException e) {
Log.e("Exception", "File write failed: ");
}
But I think the problem is in the file reading. I made some "Log.d" and found out that everything works fine till the InputStreamReader line:
public favHacks() {
testList = new ArrayList<String>();
try {
//Works fine till here
InputStreamReader inputStreamReader = new InputStreamReader(openFileInput("test.txt"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null )
{
testList.add(receiveString);
}
bufferedReader.close();
}
catch (FileNotFoundException ex) {
Log.d("login activity", "File not found: ");
} catch (IOException ex) {
Log.d("login activity", "Can not read file: ");
}
}
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs.
http://developer.android.com/training/basics/data-storage/shared-preferences.html
also if you want to write/read files, or do any kind of operations that can block the Main Thread try to use another Thread like when you are trying to save the data in a file or use a Handler if you have multiple Threads (one for saving and one for reading).
https://developer.android.com/training/multiple-threads/index.html
In your code the method called favHacks can return an ArrayList with the list of all the strings Something like
//
public ArrayList<String> readFromFile(String file){
ArrayList<String> mArrayList= new ArrayList<String>();
//read from file here
return mArrayList;
}
but as I said before, you need to the operations that can block the UI thread in a new Thread.
https://developer.android.com/training/multiple-threads/communicate-ui.html
And also I think that the best way to do this is using Asynk task
Why and how to use asynctask

android testing accessing json file

I implemented a JSON interface for getting model data over http in one of my android projects.
this works so far and I would like to write some tests. I created a test project as suggested in the android documentation. for testing the JSON interface I need some test data which I would like to put in a file.
my research showed up that it's best to put these files in the assets folder of the android test project. to access files in the assets folder one should extend the test class by InstrumentationTestCase. then it should be possible to access the files by calling getAssets().open() on a resources object. so I came up with the following code:
public class ModelTest extends InstrumentationTestCase {
public void testModel() throws Exception {
String fileName = "models.json";
Resources res = getInstrumentation().getContext().getResources();
InputStream in = res.getAssets().open(fileName);
...
}
}
unfortunately I'm getting an "no such file or directory (2)" error when trying to access "models.json" file. (/assets/models.json)
when getting a list of the available files by
String[] list = res.getAssets().list("");
"models.json" is listed in there.
I'm running these tests on Android 4.2.2 api level 17.
public static String readFileFromAssets(String fileName, Context c) {
try {
InputStream is = c.getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String text = new String(buffer);
return text;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Then use the following code:
JSONObject json = new JSONObject(Util.readFileFromAssets("abc.txt", getApplicationContext()));
please use below code:
AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("foo.txt");
if ( inputStream != null)
Log.d(TAG, "It worked!");
} catch (IOException e) {
e.printStackTrace();
}

Internal storage not being written

I'm trying to read from website url then write into device internal storage. Below are my code, the system output can print the line out but there is no file at internal storage.
Suppose the abc.xml will appear at "/data/data/my-package/abc.xml" but there is nothing...
Kindly help me on this problem.
try {
URL sourceUrl = new URL("mysite.php");
BufferedReader in = new BufferedReader(
new InputStreamReader(sourceUrl.openStream()));
String inputLine;
OutputStream out = openFileOutput("abc.xml", Context.MODE_PRIVATE);
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
out.write(inputLine.getBytes());
}
in.close();
out.close();
}
catch (IOException e) {
Log.d(LOG_TAG, e + "");
}
I wrote a simple function that saves a user object to the internal storage. The code works and seems like same you wrote above except 1 difference. I also add 1 more catch statement which is the following
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
Log.e(LOGTAG, e1.toString());
return false;
}
I know it won't solve the problem but at least you may find out why it doesn't work if the program throws a FileNotFoundException

How to import a .csv file to SQLite for Android?

I have never used a database before, so bear with me. I am programming for the Android tablet and don't have one in my possession yet, but will be getting it within a week. I have a .csv file in Excel whose data I would like to use in my app. I am aware that Androids come with SQLite, but exactly what that is or how to use it is beyond me.
I'm going to work on learning about databases as I go, but first-- How do I get my csv file into SQLite? Can I do that from my PC or do I have to wait and do it on the tablet? What do I need to download to make this happen, what exactly and where do I need to type, etc... I need really basic instructions on doing this and everything I've found online has gone way over my head due to my complete lack of experience.
You can download SQLite to you PC and tinker with it in the meantime. The import doesn't have to happen on the phone.
You can find many ways to do this process in their wiki.
Try something like this:
...
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
String line = "";
db.beginTransaction();
try {
while ((line = buffer.readLine()) != null) {
String[] colums = line.split(",");
if (colums.length != 4) {
Log.d("CSVParser", "Skipping Bad CSV Row");
continue;
}
ContentValues cv = new ContentValues(3);
cv.put(dbCol0, colums[0].trim());
cv.put(dbCol1, colums[1].trim());
cv.put(dbCol2, colums[2].trim());
cv.put(dbCol4, colums[3].trim());
db.insert(TABLE, null, cv);
}
} catch (IOException e) {
e.printStackTrace();
}
db.setTransactionSuccessful();
db.endTransaction();
How to read the CSV file
Copy file.csv into the assets folder, and read it like this:
String mCSVfile = "file.csv";
AssetManager manager = context.getAssets();
InputStream inStream = null;
try {
inStream = manager.open(mCSVfile);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
...

Categories

Resources