Reading CSV file in resources folder android - android

I am developing an android app in netbeans. I am trying to read CSV file using opencsv. When I put the file in resources folder and try to read it from there, there's an error while building saying invalid resource directory. Where should I store csv file so that it can be read each time the app starts?

you should put csv file in assets folder ..
InputStreamReader is = new InputStreamReader(getAssets()
.open("filename.csv"));
BufferedReader reader = new BufferedReader(is);
reader.readLine();
String line;
while ((line = reader.readLine()) != null) {
}

Some advices;
Create an object for holding one row data into the csv. ( Ex: YourSimpleObject . It provides you to manage the data easily.)
Read file row by row and assign to object. Add the object to list. (Ex: ArrayList<YourSimpleObject >)
Code:
private void readAndInsert() throws UnsupportedEncodingException {
ArrayList<YourSimpleObject > objList= new ArrayList<YourSimpleObject >();
AssetManager assetManager = getAssets();
InputStream is = null;
try {
is = assetManager.open("questions/question_bank.csv");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
StringTokenizer st = null;
try {
while ((line = reader.readLine()) != null) {
st = new StringTokenizer(line, ",");
YourSimpleObject obj= new YourSimpleObject ();
//your attributes
obj.setX(st.nextToken());
obj.setY(st.nextToken());
obj.setZ(st.nextToken());
obj.setW(st.nextToken());
objList.add(sQuestion);
}
} catch (IOException e) {
e.printStackTrace();
}
}

As an alternative, take a look at uniVocityParsers. It provides a vast number of ways to parse delimited files. The example bellow loads a Csv File (see in the picture below) from a res/raw folder into a InputStream object, and read it in a colunar manner (a map where key=Column & value=ColumnValues).
calendario_bolsa.csv
//Gets your csv file from res/raw dir and load into a InputStream.
InputStream csvInputStream = getResources().openRawResource(R.raw.calendario_bolsa);
//Instantiate a new ColumnProcessor
ColumnProcessor columnProcessor = new ColumnProcessor();
//Define a class that hold the file configuration
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.getFormat().setLineSeparator("\n");
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.setProcessor(columnProcessor);
//Creates a new CsvParser, passing the settings into its construtor:
CsvParser csvParser = new CsvParser(parserSettings);
//Calls parse method, instantiating an InputStreamReader, passing to its constructor the InputStream object
csvParser.parse(new InputStreamReader(csvInputStream));
//Gets the csv data as a Map of Column / column values.
Map<String, List<String>> columnarCsv = columnProcessor.getColumnValuesAsMapOfNames();
To add univocityParsers into your Android Project:
compile group: 'com.univocity', name: 'univocity-parsers', version: '2.3.0'

Using opencsv:
InputStream is = context.getAssets().open(path);
InputStreamReader reader = new InputStreamReader(is, Charset.forName("UTF-8"));
List<String[]> csv = new CSVReader(reader).readAll();

you may use this code
try {
InputStream csvStream = assetManager.open(CSV_PATH);
InputStreamReader csvStreamReader = new InputStreamReader(csvStream);
CSVReader csvReader = new CSVReader(csvStreamReader);
String[] line;
// throw away the header
csvReader.readNext();
while ((line = csvReader.readNext()) != null) {
questionList.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
you may download csvreader file from
http://sourceforge.net/projects/opencsv/files/latest/download
and import in your project

Related

android add license for 3rd party library

I'm creating a new app using Android studio, and I used 3rd party library as in jar file.
I know I need to add license for library, but I don't know how to do that.
My questions
do I need to add license in code or create new license file?
how to do that?
Here I suggest you to show License first time after installation of app.
Put
liesence.txt
file in your
assets folder
Read this file using following code:
String message = "";
try{
AssetManager am = getApplicationContext().getAssets();
InputStream is = am.open("licence.txt");
InputStreamReader inputStreamReader = new InputStreamReader(is, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
if(receiveString.equals("")){
stringBuilder.append(System.getProperty("line.separator"));
}else{
stringBuilder.append(receiveString);
}
}
is.close();
message = stringBuilder.toString();
} catch (IOException e) {e.printStackTrace();}
And then show this message in AlertDialog

Create JSON Object from Local JSON File

How do I create a "JSONObject" from a local JSON file inside my "raw" folder.
I have the following JSON file under the "raw" folder of my android app project. The file is called "app_currencies.json". I need the information contained on this file as an object in my class. Below are the file contents:
{
"EUR": { "currencyname":"Euro", "symbol":"EUR=X", "asset":"_European Union.png"},
"HTG": { "currencyname":"Haitian Gourde", "symbol":"HTG=X", "asset":"ht.png"},
"WST": { "currencyname":"Samoan Tala", "symbol":"WST=X", "asset":"ws.png"},
"GBP": { "currencyname":"British Pound", "symbol":"GBP=X", "asset":"gb.png"}
}
I think what I need is to use the following:
//Get data from Json file and make it available through a JSONObject
InputStream inputStream = getResources().openRawResource(R.raw.app_currencies.json);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
JSONObject jObject = new JSONObject;
jObject is what I need. I think I need an InputStream, ByteArrayOutputStream so that I can store it into JSONObject... the problem is that I'm not sure how to implement this code properly so that I can access the data? If any of you could give detailed instructions on how to do this, I would really appreciate it.
The following code reads a json file into a Json Array. See if it helps. Note, the file is stored in Assets instead
BufferedReader reader = null;
try {
// open and read the file into a StringBuilder
InputStream in =mContext.getAssets().open(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// line breaks are omitted and irrelevant
jsonString.append(line);
}
// parse the JSON using JSONTokener
JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue();
// do something here if needed from JSONObjects
for (int i = 0; i < array.length(); i++) {
}
} catch (FileNotFoundException e) {
// we will ignore this one, since it happens when we start fresh
} finally {
if (reader != null)
reader.close();
}

How to create a properly formatted array of gson objects

Everytime someone makes a transaction in my app I would like to save it to local storage using json / gson. I believe I am nearly there but my problem is correctly formatting the json file every time I write to it.
I would like to append to the file every time I create a Transaction object, and then at some point read every Transaction object from the file for display in a list. Here is what I have so far:
public void saveTransaction(Transaction transaction)
throws JSONException, IOException {
Gson gson = new Gson();
String json = gson.toJson(transaction);
//Write the file to disk
Writer writer = null;
try {
OutputStream out = mContext.openFileOutput(mFilename, Context.MODE_APPEND);
writer = new OutputStreamWriter(out);
writer.write(json);
} finally {
if (writer != null)
writer.close();
}
}
My transaction object has an amount, a user id and a boolean, writing with this code I can read the following json String:
{"mAmount":"12.34","mIsAdd":"true","mUID":"76163164"}
{"mAmount":"56.78","mIsAdd":"true","mUID":"76163164"}
I am reading these values like so but can only read the first one (I guess because they are not in an array / properly formatted json object):
public ArrayList<Transaction> loadTransactions() throws IOException, JSONException {
ArrayList<Transaction> allTransactions = new ArrayList<Transaction>();
BufferedReader reader = null;
try {
//Open and read the file into a string builder
InputStream in = mContext.openFileInput(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
//Line breaks are omitted and irrelevant
jsonString.append(line);
}
//Extract every Transaction from the jsonString here -----
} catch (FileNotFoundException e) {
//Ignore this one, happens when launching for the first time
} finally {
if (reader != null)
reader.close();
}
return allTransactions;
}
im not sure i understand your question, but have you tried creating a TransactionCollection object that has an ArrayList<Transaction> transactions
and create your json from the TransactionCollection object instead of each transaction?

How to load a csv file into android for read/write

I am building an app which needs to read and edit items from a .csv file.
I can place the .csv in the assets folder but would rather the ability to search for it in the external storage as it will change regularly.
A friend has given me this code for placing it in the assets folder, but I am relatively new to android and this code doesn't make sense to me and I cant get it to work.
public ArrayList<String> Job = new ArrayList<String>();
try {
is = res.getAssets().open("Job.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null)
Job.add(line);
} catch (IOException ex) {
// handle exception
} finally {
try {
is.close();
} catch (IOException e) {
// handle exception
}
}

Replacing a line of text in an android external text file

I just want to delete 2 lines of text from a text file that I created. Currently, this is what I'm trying to get rid of the 2 lines:
private void deleteDataFromFile(String title, String Date) {
try {
//open the file
FileInputStream myIn= openFileInput(FILENAME);
//the reader given the input file stream.
InputStreamReader inputReader = new InputStreamReader(myIn);
//Aftert he inputstream is open, need also a bufferedReader
BufferedReader BR = new BufferedReader(inputReader);
//holds a line of input
String line;
//used for only erasing one date.
int counter = 0;
while ((line = BR.readLine()) != null && counter < 1) {
if (line.equals(title)) {
line.replace(title, "" + "\n");
line = BR.readLine();
line.replace(Date, "" + "\n");
counter++;
}
}
BR.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I realize that since I'm using the replace function on a string it has no effect on the actual file itself, but I can not find any other function in the IO library to affect the text file. What I'm thinking about doing is creating a new file on the phone with the exact contents of this file and just deleting the 2 lines from it. That seems troublesome and inefficient though, and I'd like to avoid it. Any suggestions?

Categories

Resources