How to populate the csv file? - android

i'm creating a csv file with the data from the database. All the data of the selected consumer Id's must append into the csv file. In my program the csv file was attached on email, let's say I have 3 selected consumer ID, the email sent, but when I checked the csv file, the first selected ID was did not show up and it leaves the first row blank, while the 2nd and 3rd append on the csv. I don't what happen why I cannot see the data of the first ID i selected. help me please..
here's my code:
private String getConsumersDetails(ArrayList<String> arraylistConsumerId)
{
for (int j = 0; j < arraylistConsumerId.size(); j++)
{
//Cursor cursorConsumerDetails = null;
Cursor cursorConsumerDetails = databaseAdapter.getCursorRegisteredConsumer(Integer.parseInt(arraylistConsumerId.get(j)));
//if (cursorConsumerDetails.getCount() == 0)
//cursorConsumerDetails = databaseAdapter.getCursorRegisteredConsumer(arraylistConsumerId.get(j));
// consumerData.append("\n"+lastname+","+firstname+","+middleinitial+","+cellphone+","+emailadd+","+carefriend+","+company+","+regdate);
if (cursorConsumerDetails.getCount() > 0)
{
lastname = cursorConsumerDetails.getString(cursorConsumerDetails.getColumnIndex(Constants.CONSUMER_LASTNAME));
firstname = cursorConsumerDetails.getString(cursorConsumerDetails.getColumnIndex(Constants.CONSUMER_FIRSTNAME));
middleinitial = cursorConsumerDetails.getString(cursorConsumerDetails.getColumnIndex(Constants.CONSUMER_MIDDLEINITIAL));
cellphone = cursorConsumerDetails.getString(cursorConsumerDetails.getColumnIndex(Constants.CONSUMER_CELLPHONENO));
emailadd = cursorConsumerDetails.getString(cursorConsumerDetails.getColumnIndex(Constants.CONSUMER_EMAIL));
carefriend = cursorConsumerDetails.getString(cursorConsumerDetails.getColumnIndex(Constants.CONSUMER_CAREFRIEND));
company = cursorConsumerDetails.getString(cursorConsumerDetails.getColumnIndex(Constants.CONSUMER_COMPANY));
regdate = cursorConsumerDetails.getString(cursorConsumerDetails.getColumnIndex(Constants.CONSUMER_REGISTRATIONDATE));
code = cursorConsumerDetails.getString(cursorConsumerDetails.getColumnIndex(Constants.CONSUMER_COMPANYCODE));
}
consumerData.append("\n"+lastname+","+firstname+","+middleinitial+","+cellphone+","+emailadd+","+carefriend+","+company+","+regdate);
}
return consumerData.toString();
}
This one calls the code above..
....
consumerData = new StringBuilder();
File personFile;
time = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY))+String.valueOf(calendar.get(Calendar.MINUTE))+String.valueOf(calendar.get(Calendar.SECOND));
personFile = createCSV("Person_Table_"+date+"_"+time, Constants.COLUMN_STRING_PERSON_TABLE, getConsumersDetails(arraylistConsumerId), fileCounter, false);
createEmailWithAttachments(personFile);
....

I don't know how its done in android but in general to
obtain a csv file from sqlite3 database.
.mode csv
.output filename.csv
select * from table;
csv file will be present directory where the sqlite database file is stored.

Related

Compare contact and select on click

i am creating app in which i have to compare my device contact to server data contact.i am doing this but only last data is coming,but i want to make comparison with every device contact to server contact.I am able to fetch data from device and from server but i don't know how to compare.
Here phonenumber is no coming from phonecursor and second is server data.
Objects.equals(phoneNumber, jsonObject1.getString("mobile"))
after the comparison i want to select any five contact from list and send it to another fragment.i don't know how to select item from recyclerview list.
first you have to store your all contact into DB.
then,
ArrayList<String> foundNumb = new ArrayList();
for (int A = 0; A < DB_Contact_List.size(); A++) {
// get contact from DB list one by one
DBContactBean dbDataBean = DB_Contact_List.get(A);
String DbNumb = dbDataBean.getmNumber().replaceAll("\\s+", "");
String ServrNumb = "";
ServerContactBean serverDataBeanM = null;
boolean found = false;
int BBB = 0;
if (!DbNumb.equals("")) {
innerLoop:
for (int B = 0; B < Server_Contact_List.size(); B++) {
// get contatct from Server list one by one
ServerContactBean serverDataBean = Server_Contact_List.get(B);
BBB = B;
serverDataBeanM = serverDataBean;
ServrNumb = serverDataBean.getPh_phone().replaceAll("\\s+", "");
// compare it
if (DbNumb.equalsIgnoreCase(ServrNumb)) {
found = true;
break innerLoop;
}
}
if (found) {
// if found do your task
foundNumb.add(DbNumb);
} else {
// not found
}
}
}

Android: Uploading multiple string records to Parse.com

I am working on a app where I would like to upload a string array. Code as follows:
Code:
upload_list = getResources().getStringArray(R.array.upload_list);
Utilities.custom_toast(this, ""+upload_list.length, "");
ParseObject database = new ParseObject("table_name");
for (int m = 0; m < upload_list.length; m++)
{
database.put("name_full", upload_list[m]);
database.saveInBackground();
}
Question:
The above string array has 90 items. After going through the above code, 1 new row is added to the table, and keep refreshing the table in Parse, different strings picked from the above string array is reflected in the row.
I would like instead inserting 90 new rows to the table.
How could that be fixed? Many thanks in advance!
if you want NEW ROW in the loop, move the new ParseObject :
ParseObject database;
...
for (int m = 0; m < upload_list.length; m++)
{
database = new ParseObject("table_name");
database.put("name_full", upload_list[m]);
database.saveInBackground();
}

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).

Android: Sorting mp3 files by title in a clickable listview

I am attempting to create a music player app for a Nexus 7 tablet. I am able to retrieve music files from a specific directory as well as information that is associated with them such as title, artist, etc. I have loaded the files's titles into a clickable list view. When the user clicks on a title, it takes them to an activity that plays the associated song. I was attempting to sort the titles alphabetically and ran into a snag. When I sort just the titles, they no longer match with the correct songs. This is to be expected since I only ordered the titles and not the actual files. I attempted to modify the sorting algorithm by doing this:
//will probably only work for Nexus 7
private final static File fileList = new File("/storage/emulated/0/Music/");
private final static File fileNames[] = fileList.listFiles(); //get list of files
public static void sortFiles()
{
int j;
boolean flag = true;
File temp;
MediaMetadataRetriever titleMMR = new MediaMetadataRetriever();
MediaMetadataRetriever titleMMR2 = new MediaMetadataRetriever();
while(flag)
{
flag = false;
for(j = 0; j < fileNames.length - 1; j++)
{
titleMMR.setDataSource(fileNames[j].toString());
titleMMR2.setDataSource(fileNames[j+1].toString());
if(titleMMR.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE).compareToIgnoreCase(titleMMR2.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)) > 0)
{
temp = fileNames[j];
fileNames[j] = fileNames[j+1]; // swapping
fileNames[j+1] = temp;
flag = true;
}//end if
}//end for
}//end while
}
This is supposed to retrieve the song titles from two files, compare them, and swap the files in the File array if the first comes after the second alphabetically. For some reason, when I run the activity that calls this method, the app crashes. If I remove the + 1 from titleMMR2's data source
titleMMR2.setDataSource(fileNames[j].toString());
the app no longer crashes but the list is not in order. Again this is understandable since it compares the song titles to themselves. I don't know why the + 1 would make the program crash. It is not an array out of bounds error. There are a total of 6 .mp3 files in the directory and they are the only files in that directory. I have also tried using Arrays.sort(fileNames) but that only orders them by their file name and not song title. I also tried this:
Arrays.sort(fileNames, new Comparator<File>(){
public int compare(File f1, File f2)
{
titleMMR.setDataSource(f1.toString());
titleMMR2.setDataSource(f2.toString());
return titleMMR.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE).compareToIgnoreCase(titleMMR2.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE));
} });
That snippet also resulted in a crash. There are no errors in the java code and all appropriate classes have been imported. I'm really at a loss as to what is wrong. Any help will be appreciated and if any new info is needed I will gladly provide it. Thanks in advance.
FIXED
The correct code snip is this:
public static void sortFiles()
{
int j;
boolean flag = true;
File temp;
MediaMetadataRetriever titleMMR = new MediaMetadataRetriever();
MediaMetadataRetriever titleMMR2 = new MediaMetadataRetriever();
while(flag)
{
flag = false;
for(j = 0; j < fileNames.length - 1; j++)
{
titleMMR.setDataSource(fileNames[j].toString());
titleMMR2.setDataSource(fileNames[j+1].toString());
String title1;
String title2;
if(titleMMR.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE) == null)
title1 = fileNames[j].getName();
else
title1 = titleMMR.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
if(titleMMR2.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE) == null)
title2 = fileNames[j+1].getName();
else
title2= titleMMR2.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
if(title1.compareToIgnoreCase(title2) > 0)
{
temp = fileNames[j];
fileNames[j] = fileNames[j+1]; // swapping
fileNames[j+1] = temp;
flag = true;
}//end if
}//end for
}//end while
}

How can I insert data from a text file into a sql database in android?

I'm quite new to SQLite databases and need help using an external text file to create an initial database to store a bunch of items that can be selected and added to a second database. To put this all in context, I want to have an initial database that stores a list of grocery store items. Each item will have two traits with them, a NAME and a TYPE. So there are items such as( NAME Bread, TYPE Bakery. NAME Grape Juice, TYPE Beverage. NAME Toothbrush, TYPE Toiletries. )
I need to go from something like this:
GROCERYSTORE.TXT
-- -- -- -- -- --
NAME - TYPE
Bread - Bakery
Rolls - Bakery
Juice - Beverages
Soda - Beverages
to this:
dBHelper.insert("Bread", "Bakery");
or:
dBHelper.insert(name, type);
for each item in the text file.
First of all, I would like to know how to format this text file, or any other type of file that could be read and inserted into a database if a text file is not the easiest way to go about this.
Second, how would I go about reading this text file and inserting it into the database?
I'm thinking I would use a buffered reader and inputstream within a for loop to go and insert each item into the database. I'm just not sure how to parse each line to give each item a name and a type to be inserted into the database, and how to format a text file to be read.
Any help would be greatly appreciated as I have found very little about using external files to import data into an sql database that pertains to my situation.
In my apps that have a static or default database I use an xml file for my data sort of like this:
default_grocerystore.xml stored in assets folder:
<default_grocerystore>
<grocery>
<name>Bread</name>
<type>Bakery</type>
</grocery>
<grocery>
<name>Rolls</name>
<type>Bakery</type>
</grocery>
<grocery>
<name>Juice</name>
<type>Beverages</type>
</grocery>
<grocery>
<name>Soda</name>
<type>Beverages</type>
</grocery>
</default_grocerystore>
Then in the onCreate in my database class I create my database tables I populate them with the xml like this:
private void populateGrocery(SQLiteDatabase db) {
ArrayList<GroceryObj> groceryArrayList;
groceryArrayList = buildGroceryArrayList();
String insertStmt = null;
for (int i = 0; i < groceryArrayList.size(); i++) {
insertStmt = "INSERT INTO " + GROCERY_TABLE + " ("
+ GROCERY_KEY_NAME + ", " + GROCERY_KEY_TYPE + ") "
+ "VALUES (\""
+ groceryArrayList.get(i).getName()
+ "\", \""+groceryArrayList.get(i).getType()+"\");";
db.execSQL(insertStmt);
}
private ArrayList<GroceryObj> buildGroceryArrayList() {
ArrayList<GroceryObj> aL = new ArrayList<GroceryObj>();
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream raw = context.getAssets().open(
"default_grocerys.xml");
Document dom = builder.parse(raw);
Element root = dom.getDocumentElement();
NodeList groceryItems = root.getElementsByTagName("grocery");
for (int i = 0; i < groceryItems.getLength(); i++) {
String name= null;
String type= null;
Node item = groceryItems.item(i);
NodeList groceryItem = item.getChildNodes();
for (int j = 0; j < groceryItem.getLength(); j++) {
Node nodeItem= groceryItem.item(j);
String nodeName= noteItem.getNodeName();
if (nodeName.equalsIgnoreCase("name")) {
name= nodeItem.getFirstChild().getNodeValue();
} else if (nodeName.equalsIgnoreCase("type")) {
type= nodeItem.getFirstChild().getNodeValue();
}
}
aL.add(new GroceryObj(name, type));
}
} catch (Exception e) {
e.printStackTrace();
}
return aL;
}
}

Categories

Resources