How to parse the CSV file in android application? - android

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.

Related

How to write to existing JSON file?

I need some help in writing to an existing json file. I can parse the data and read from it using GSON or just json in this example. I did it this way to filter the results by id displayed on screen. So it grabs the add and searches my list of over 900 videos and then gives the ones selected. Only issue is i don't want to display them i want to save them :)
final Button button = findViewById(R.id.buttonx);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// load json parse json and grab fields...
// then write to new file!
try {
//Load File
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.movielist)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
//Parse Json
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
ArrayList<String> fields = new ArrayList<String>();
for (int index = 0; index < jsonArray.length(); index++) {
//Set both values into the listview
JSONObject jsonObject = jsonArray.getJSONObject(index);
String series = jsonObject.getString("id");
if (series.equals(tvId.getText())) {
fields.add(jsonObject.getString("movie"));
fields.add(jsonObject.getString("year"));
fields.add(jsonObject.getString("duration"));
fields.add(jsonObject.getString("director"));
fields.add(jsonObject.getString("image"));
fields.add(jsonObject.getString("id"));
}
}
} catch (FileNotFoundException e) {
Log.e("jsonFile", "file not found");
} catch (IOException e) {
Log.e("jsonFile", "ioerror");
} catch (JSONException e) {
Log.e("jsonFile", "error while parsing json");
}
Toast.makeText(DetailActivity.this, "The following movie has been saved " + tvId.getText(), Toast.LENGTH_LONG).show();
// Toast.makeText(DetailActivity.this, "This features is not working", Toast.LENGTH_LONG).show();
}
});
My issue is once I get the data I want to be able to write this to an existing JSON file. my api is 18 so can't use FILEwriter i am trying to make the app available to pretty much everyone. A point in the right direction would be great.
If you want to write to a file packaged in the raw folder, you will have to copy it to the local file system first. Resources contained in your raw directory in your project will be packaged inside your APK and will not be writeable at runtime. Consider looking at the Internal or External Data Storage APIs.
Update raw resources is not possible

How to escape comma in a CSV file, android

I have a CSV file (the information is with Cyrillic letters, if matters). The CSV class is written so that it reads every row and splits it on a comma:
String[] row = csvLine.split(",");
In the csv I have rows in the following pattern:
ааа,бб, рр, ррр рр тт.
How can I force the CSV be split on the first comma only?
PS: I've already tried using double commas and blackslash in from of the comma, without any success so far.
EDIT:
Here is the whole CSVreader class:
public class CSVReader {
InputStream inputStream;
public CSVReader(InputStream is) {
this.inputStream = is;
}
public List<String[]> read() {
List<String[]> resultList = new ArrayList<String[]>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
} catch(IOException ex) {
throw new RuntimeException("Error in reading CSV file:" + ex);
} finally {
try{
inputStream.close();
} catch(IOException e) {
throw new RuntimeException("Error while closing input stream: " + e);
}
}
return resultList;
}
}
What I need is the above excerpt from the CSV to be split on the first comma only, and the encountered after that to be parsed and shown on the screen.
If you want to split only the first comma of each line, you can use
csvLine.split(",",2);
Where 2 is the limit parameter checking the maximum lenght of the resulting String array. This means that the split will only occur limit-1 times. In your case, 1.
As explained in JavaDocs here.
With input aa,bb,cc,dd you'll get the array {"aa","bb,cc,dd"}

Get random words from android dictionary

I am kind of learning android...and I would like to know if there is a way to access 3 letter words or 4 letter words or some specif type of words at random from the android User Dictionary class??Considering the fact that android has an auto correct feature I'm guessing it also has a dictionary in it...thus how do I use that...where can I find a proper tutorial?
i have no idea about the code...searched around a lot...please help me with the code and also the explanation possibly :)
I don't know how to access the android dictionary but you can have a "custom" dictionary as a txt file in the app's assets folder. This link has several word lists from around 20,000 words to 200,000 words. You could find more lists with google.
Afterwards, you can read the txt file and add it to an Array List if it matches the word length. A random word can then be selected from the dictionary list. The following code will create the dictionary and select a random word from it.
private ArrayList<String> dictionary;
private int wordLength; //Set elsewhere
private void createDictionary(){
dictionary = new ArrayList<String>();
BufferedReader dict = null; //Holds the dictionary file
AssetManager am = this.getAssets();
try {
//dictionary.txt should be in the assets folder.
dict = new BufferedReader(new InputStreamReader(am.open("dictionary.txt")));
String word;
while((word = dict.readLine()) != null){
if(word.length() == wordLength){
dictionary.add(word);
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dict.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Precondition: the dictionary has been created.
private String getRandomWord(){
return dictionaryList.get((int)(Math.random() * dictionaryList.size()));
}

Querying text file into database

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)

android - where to save history and autocomplete values

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.

Categories

Resources