How to read an CSV file in android? - android

I am reading a CSV file which have format: "col1"\t"col2". As my understanding there are two methods to read an CSV file and add to array.
1. ReadByLine.
2. ReadNext.
In Readbyline I face issue if col2 have \n in between the string, and that is added to my second index. like ("Hi how r u" "I am \n fine")
In readNext I face issue when my column1 is empty it return col2 value lile ("" "I am fine"). readNext return "I am fine".
Can any one suggest any best approach to work with this format.

Each line in a CSV file uses , as a delimiter. You should read the file line by line and split the line with the above delimiter:
try {
File f = new File("source.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
while( ( line = br.readLine() ) != null ) {
String[] tokens = line.split(",");
}
} catch (IOException e) {
e.printStackTrace();
}
Then, tokens.length will give you the size.
If you have spaces the use:
String newString = tokens[x].trim();

Related

Returning rows from a csv

Hi I have a csv that looks like this:
r1c1|r1c2|r1c3
r2c1|r2c2|r2c3
As you can see it is delimited by the character "|"
In my application, I am trying to explode this using input stream. Here is my code:
String line = "";
String cvsSplitBy = "|";
try {
File initialFile = new File(myfile.txt);
InputStream targetStream = new FileInputStream(initialFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(targetStream));
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(cvsSplitBy);
String c0 = RowData[0];
String c1 = RowData[1];
String c2 = RowData[2];
Toast.makeText(mainactivity.this, c2, Toast.LENGTH_LONG).show();
}
}catch (IOException ex) {
// handle exception
}
Unfortunately, this appears to return each character in the csv as a row. The toast example above returns 1 then 2.
Any ideas how to return the proper column, anyone?
split() splits string around matches of the given regular expression, therefore use of special character (and vertical bar is one of these) requires escaping to strip its "powers".
String cvsSplitBy = "\\|"
See docs: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

SQL error 22008 with INSERT INTO

Hello I try to insert in sql
My code is:
archivo = new File("file name");
fr = new FileReader(archivo);
br = new BufferedReader(fr);
select = connection.createStatement();
statement = "INSERT INTO TABLE VALUES (";
cantidad = 0;
while(br.readLine() != null)
{
cantidad++;
}
br.close();
fr = new FileReader(archivo);
br = new BufferedReader(fr);
contador=0;
while((linea = br.readLine())!= null)
{
arrayString = linea.split("\\|");
for(int i = 0; i < arrayString.length; i++)
{
statement = statement + "'" + arrayString[i] + "',";
}
statement = statement.substring(0, statement.length() - 1) + ");";
select.executeUpdate(statement);
at the end before of select.executeUpdate(statement)
statement = INSERT INTO TABLE VALUES ('mx','mz','11','43','0','0','0','0','0','2015-01-19 09:24:20','0','10737','2015-01-19 09:24:20','20.71878','-103.45705','N','W','0.0','T','s','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','J1939','21','56','124','0','0','0');
then i receive the error SQL 22008
What is wrong?
Regards
The DateTime field format you have chosen is not acceptable.
2015-01-19 09:24:20
Try to convert to something like:
2015-01-19T09:24:20
Source on more formats:
http://msdn.microsoft.com/en-us/library/ms187819.aspx
It looks like your code is inserting some sort of tab or line break in the middle of your timestamps that you are trying to insert, that is making SQL Server throw an error that it didn't understand your format and tried to truncate/round the datetime value.
Try changing your code such that your datetime value are in the following format:
yyyy-mm-ddThh:mm:ss
For example:
2015-01-19T09:43:35

Import multiple .csv file into android sqlite database

I am now trying to import csv files from a certain directory in sd card from an android device. Recently, I can successfully import a single csv files. However, I have no ideas on how to get the list of all csv files and then using a loop to import the csv file one by one.
This is the my code for importing single csv:
button_import_csv.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
DatabaseHelper helper = new DatabaseHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
try{
FileReader file = new FileReader("/sdcard/downloadedfolder/A1/adv_sales_order.csv");
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues=new ContentValues();
String line = "";
String tableName ="adv_sales_order";
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split("\t");
contentValues.put("order_date", str[0]);
contentValues.put("cust_code", str[1]);
contentValues.put("customer_ref_no", str[2]);
contentValues.put("line_no", str[3]);
contentValues.put("item_code", str[4]);
contentValues.put("tran_code", str[5]);
contentValues.put("order_qty", str[6]);
db.insert(tableName, null, contentValues);
}
db.setTransactionSuccessful();
db.endTransaction();
}catch (IOException e){
}
}
});
The columns for different csv fileS are not the same.(For example,some may has 4 columns named A,B,C,D and the other one may has columns named as C,D,E,F) Besides hard coding all columns for each csv file, are there any possible ways?
Can anyone tell me any solution???Thank you.
There are two possibilities I can think of...
First: If you are in control of the filenames then give them names with a sequential numeric aspect, e.g., file1.csv, file2.csv etc You can then simply use a for loop to build the filenames and process them. Example...
// Lets say you have 5 files named file1.csv thru file5.csv
for(int i = 1; i < 6; i++) {
String filename = "file" + i + ".csv";
// Process the file which has the above filename
}
Second: Get all of the files in the directory using the listFiles() method. Example...
// This code assumes you have a File object for the directory called dir
File[] files = dir.listFiles();
for(int i = 0; i < files.length; i++) {
String filename = files[i].getAbsolutePath();
if (filename.endsWith(".csv")) {
// Process the file which has the above filename
}
}
I'm not sure if either of the code blocks above are perfect but basically they both simply use a for loop. There are other ways but those are the most straight-forward.
EDIT:
Some csv files use the first line to describe the column names. In some ways this is a bit like a schema of a dataset. Example (using comma-separated values)...
A,B,C,D
valueA,valueB,valueC,valueD
...
Using this approach means you can get access to the column names by reading the first line and splitting it to make an array. You can then use a for loop to put the ContentValues. Try the following...
// Read the first line separately and split to get the column names
line = buffer.readLine();
String[] cols = line.split("\t");
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split("\t");
for (int i = 0; i < cols.length; i++) {
contentValues.put(cols[i], str[i]);
}
db.insert(tableName, null, contentValues);
}
db.setTransactionSuccessful();
db.endTransaction();
BTW I notice you're splitting on "\t" so make sure your column names on the first line are tab-delimited (obviously).

Named placeholders in Android

In my android app
in message if i give message "hi #name,welcome your username:#username and password:#password" and in message #name,#username,#password are to be replaced with values iam reading from csv file
and it should send message as example:"hi praveen,welcome your username:neevarp and password:12345"
and those values are from csv .while searching i got some link
Named placeholders in string formatting
Map<String, String> values = new HashMap<String, String>();
values.put("value", x);
values.put("column", y);
StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");
but in android
StrSubstitutor
class is not there i think so is there any way to implement this
here is my code of reading values from csv and sending messages by replacing place holders
public void sendingSms(String message, String file_path) {
File file = new File("", file_path);
// Read text from file
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int iteration = 0;
while ((line = br.readLine()) != null) {
if (iteration != 0) {
StringBuilder text = new StringBuilder();
text.append(line);
String[] contact = text.toString().split(",");
String phoneNumber = contact[4];
String name = contact[1];
String username = contact[2];
String password = contact[3];
//here i have to replace place holders with name,username,password values
//message.replace("#name", name);
//message.replace("#user", username);
Toast.makeText(Message.this, "" + message,
Toast.LENGTH_SHORT).show();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null,
null);
}
iteration++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
You should really be using the built in string formatting Android provides via string resources: http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
The functionality that you want is built right into the String class itself if you want to design your own StrSubstitutor class. Essentially building/designing a foreach with your Mapped values into the function.
String result = inputString.replace(valueString, replacedValueString);
But I am unaware of the function that you are requesting being built-in. Alex Fu as well has provided alternate means by which you could handle your string replacement.

Merge First name and Last name

Here I am reading file word by word and manipulating List view with these word. Problem here is First name and Last name are appearing in different rows. e.g. Name = "John Clerk" then I am getting "John" in first row and "Clerk" in second row of List view. They must be in single row and so forth for other data. What should I make changes to work it properly? My code...
String myData = "";
String strLine;
String listName = "" ;
FileOutputStream fos;
FileInputStream fstream;
DataInputStream in;
String[] SavedFiles;
BufferedReader br;
public void readFile(String file) throws IOException
{
fstream = openFileInput(file);
Scanner scanFile = new Scanner(new DataInputStream(fstream));
ArrayList<String> words = new ArrayList<String>();
String theWord, theWord1, theWord2;
while (scanFile.hasNext())
{
theWord = scanFile.next();
words.add(theWord);
}
Toast.makeText(getBaseContext(), "" + size, 1000).show();
adapterFriends = new ArrayAdapter<String>(getBaseContext(), R.layout.text, words);
lvFinal.setAdapter(adapterFriends);
adapterFriends.notifyDataSetChanged();
}
Try to use nextLine() instead of next(), as it should return every string between \n chars.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextLine()
hope that helps
If I understand correctly what you need, try this:
while (scanFile.hasNext())
{
String name = scanFile.next();
if (scanFile.hasNext())
{
name = String.format("%s %s", name, scanFile.next());
}
words.add(name);
}

Categories

Resources