I create my Project . but I sucked in final mode.. My Table has been generated but for attaching Purpose, I have to create that Table into EXCEL.. PLease give me link. I also tried for pdf but API is not free for commercial use. so give me guide lines , links or GitHub...
Solution is to convert the sqlite database into csv then convert the csv file to xls.You will need 2 libraries (opencsv-1.7.jar poi-3.8-20120326.jar)
public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean>
{
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected Boolean doInBackground(final String... args)
{
File dbFile=getDatabasePath("database_name");
//AABDatabaseManager dbhelper = new AABDatabaseManager(getApplicationContext());
AABDatabaseManager dbhelper = new AABDatabaseManager(DatabaseExampleActivity.this) ;
System.out.println(dbFile); // displays the data base path in your logcat
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "excerDB.csv");
try
{
if (file.createNewFile()){
System.out.println("File is created!");
System.out.println("myfile.csv "+file.getAbsolutePath());
}else{
System.out.println("File already exists.");
}
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
//SQLiteDatabase db = dbhelper.getWritableDatabase();
Cursor curCSV=db.getdb().rawQuery("select * from " + db.TABLE_NAME,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)};
/*curCSV.getString(3),curCSV.getString(4)};*/
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
/*String data="";
data=readSavedData();
data= data.replace(",", ";");
writeData(data);*/
return true;
}
catch(SQLException sqlEx)
{
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
}
catch (IOException e)
{
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "Export succeed", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}}
Export CSV to XLS part
public class CSVToExcelConverter extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{this.dialog.setMessage("Exporting to excel...");
this.dialog.show();}
#Override
protected Boolean doInBackground(String... params) {
ArrayList arList=null;
ArrayList al=null;
//File dbFile= new File(getDatabasePath("database_name").toString());
File dbFile=getDatabasePath("database_name");
String yes= dbFile.getAbsolutePath();
String inFilePath = Environment.getExternalStorageDirectory().toString()+"/excerDB.csv";
outFilePath = Environment.getExternalStorageDirectory().toString()+"/test.xls";
String thisLine;
int count=0;
try {
FileInputStream fis = new FileInputStream(inFilePath);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null)
{
al = new ArrayList();
String strar[] = thisLine.split(",");
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
System.out.println();
i++;
}} catch (Exception e) {
System.out.println("shit");
}
try
{
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for(int k=0;k<arList.size();k++)
{
ArrayList ardata = (ArrayList)arList.get(k);
HSSFRow row = sheet.createRow((short) 0+k);
for(int p=0;p<ardata.size();p++)
{
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if(data.startsWith("=")){
cell.setCellType(Cell.CELL_TYPE_STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
System.out.println();
}
FileOutputStream fileOut = new FileOutputStream(outFilePath);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated");
} catch ( Exception ex ) {
ex.printStackTrace();
} //main method ends
return true;
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "file is built!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "file fail to build", Toast.LENGTH_SHORT).show();
}
}
}
Related
I have a class compositionJSON. The class has a method calls makeJSONObject, that creates a JSON-Object and put stuff in it. Here is the code of the class.
public class CompositionJso extends JSONObject {
public JSONObject makeJSONObject (String title, String desc, ArrayList<String> imgPath, ArrayList<Resources> imgView) {
JSONObject obj = new JSONObject() ;
try {
obj.put("title", title);
obj.put("desc", desc);
obj.put("imgPath", imgPath);
obj.put("imgViewPath", imgView);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
Now I create a instance of this class and call the method in another class. After that I want to write the JSONObject to file and save it on the sd card on device. Here is the code:
saveCompo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setName();
createJSONFolder();
CompositionJso obj = new CompositionJso();
obj.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);
MyCompositionsListActivity.buildList();
try {
Writer output = null;
File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");
output = new BufferedWriter(new FileWriter(file));
output.write(obj.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
The file is saving successfully but if I open it, there is nothing inside. What is wrong with the code?
makeJSONObject is returning JSONObject
Your code should be
saveCompo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setName();
createJSONFolder();
CompositionJso obj = new CompositionJso();
JSONObject jsonObject = obj.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);
MyCompositionsListActivity.buildList();
try {
Writer output = null;
File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");
output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
Try this write a simple class with static methods to save and retrieve json object in a file :
CODE :
public class RetriveandSaveJSONdatafromfile {
public static String objectToFile(Object object) throws IOException {
String path = Environment.getExternalStorageDirectory() + File.separator + "/AppName/App_cache" + File.separator;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
path += "data";
File data = new File(path);
if (!data.createNewFile()) {
data.delete();
data.createNewFile();
}
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
objectOutputStream.writeObject(object);
objectOutputStream.close();
return path;
}
public static Object objectFromFile(String path) throws IOException, ClassNotFoundException {
Object object = null;
File data = new File(path);
if(data.exists()) {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(data));
object = objectInputStream.readObject();
objectInputStream.close();
}
return object;
}
}
To save json in a file use RetriveandSaveJSONdatafromfile.objectToFile(jsonObj) and to fetch data from file use
path = Environment.getExternalStorageDirectory() + File.separator +
"/AppName/App_cache/data" + File.separator;
RetriveandSaveJSONdatafromfile.objectFromFile(path);
Thanks #Chris Handy! I created a JSONObjectVariable and assign it to the makeJSONObject. Here is my final code:
saveCompo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setName();
createJSONFolder();
CompositionJso compositionJso = new CompositionJso();
JSONObject obj;
obj = compositionJso.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);
MyCompositionsListActivity.buildList();
try {
Writer output;
File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");
output = new BufferedWriter(new FileWriter(file));
output.write(obj.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
In the method makeJSONObject you instantiate a new JSONObject.
this code should work.
public void makeJSONObject (String title, String desc, ArrayList<String> imgPath, ArrayList<Resources> imgView) {
try {
this.put("title", title);
this.put("desc", desc);
this.put("imgPath", imgPath);
this.put("imgViewPath", imgView);
} catch (JSONException e) {
e.printStackTrace();
}
}
I am new in android. I made a 3 columns in sqlite and I am storing user input in sqlite
I want when device get Wifi(Internet) it will upload all data to google excel sheet accordingly with column on specific user account.
My solution is to convert the sqlite database into csv in first step then in second step is to convert the csv file to xls and it works fine for me, you will need 2 libraries (opencsv-1.7.jar; poi-3.8-20120326.jar)
public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean>
{
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected Boolean doInBackground(final String... args)
{
File dbFile=getDatabasePath("database_name");
//AABDatabaseManager dbhelper = new AABDatabaseManager(getApplicationContext());
AABDatabaseManager dbhelper = new AABDatabaseManager(DatabaseExampleActivity.this) ;
System.out.println(dbFile); // displays the data base path in your logcat
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "excerDB.csv");
try
{
if (file.createNewFile()){
System.out.println("File is created!");
System.out.println("myfile.csv "+file.getAbsolutePath());
}else{
System.out.println("File already exists.");
}
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
//SQLiteDatabase db = dbhelper.getWritableDatabase();
Cursor curCSV=db.getdb().rawQuery("select * from " + db.TABLE_NAME,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)};
/*curCSV.getString(3),curCSV.getString(4)};*/
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
/*String data="";
data=readSavedData();
data= data.replace(",", ";");
writeData(data);*/
return true;
}
catch(SQLException sqlEx)
{
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
}
catch (IOException e)
{
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "Export succeed", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}}
Export CSV to XLS part
public class CSVToExcelConverter extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{this.dialog.setMessage("Exporting to excel...");
this.dialog.show();}
#Override
protected Boolean doInBackground(String... params) {
ArrayList arList=null;
ArrayList al=null;
//File dbFile= new File(getDatabasePath("database_name").toString());
File dbFile=getDatabasePath("database_name");
String yes= dbFile.getAbsolutePath();
String inFilePath = Environment.getExternalStorageDirectory().toString()+"/excerDB.csv";
outFilePath = Environment.getExternalStorageDirectory().toString()+"/test.xls";
String thisLine;
int count=0;
try {
FileInputStream fis = new FileInputStream(inFilePath);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null)
{
al = new ArrayList();
String strar[] = thisLine.split(",");
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
System.out.println();
i++;
}} catch (Exception e) {
System.out.println("shit");
}
try
{
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for(int k=0;k<arList.size();k++)
{
ArrayList ardata = (ArrayList)arList.get(k);
HSSFRow row = sheet.createRow((short) 0+k);
for(int p=0;p<ardata.size();p++)
{
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if(data.startsWith("=")){
cell.setCellType(Cell.CELL_TYPE_STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
System.out.println();
}
FileOutputStream fileOut = new FileOutputStream(outFilePath);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated");
} catch ( Exception ex ) {
ex.printStackTrace();
} //main method ends
return true;
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "file is built!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "file fail to build", Toast.LENGTH_SHORT).show();
}
}
}
I suggest you to study about google spreadsheets APIs
I am very new with android and doing this first time. I am trying to download pdf form url in my app but its not getting downloaded. I really got messed up with this. I don't what i am missing ,why this is not working for me. Please help me to do this.
Here i am pasting my code:
public class ProductBrochureActivity extends Activity {
private static String cookie;
private static String nid;
WebView webViewForBrochureAndVideo;
private String prodBrochureURL;
private String prodVideoURL;
private static int clickedItemId;
ActionBar actionBar;
private static HashMap<String, String> cookieWithRequest = new HashMap<String, String>();
static Object json;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_brochure);
actionBar = getActionBar();
actionBar.hide();
Intent intent = getIntent();
cookie = intent.getStringExtra(BsharpConstant.WEB_SERVICES_COOKIES);
nid = intent.getStringExtra(BsharpConstant.PRODUCT_NODE_ID);
clickedItemId = intent.getIntExtra(BsharpConstant.CLICKED_ITEM_ID, 0);
String jsonResponseFromWebservices = WebserviceBsharpUtil
.callWebServicesToGetTheProductBrochureAndVideo(cookie, nid);
urlFromResponse(jsonResponseFromWebservices);
cookieWithRequest.put(BsharpConstant.WEB_SERVICES_COOKIES, cookie);
switch (clickedItemId) {
case 0:
if (!prodBrochureURL.isEmpty()) {
try {
new DownloadFile();
} catch (ActivityNotFoundException e) {
Toast.makeText(this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "No PDF is Attached with this Product",
Toast.LENGTH_SHORT).show();
}
break;
case 1:
if (!prodVideoURL.isEmpty()) {
try {
new DownloadFile();
} catch (ActivityNotFoundException e) {
Toast.makeText(this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
break;
} else {
Toast.makeText(this, "No Video is Attached with this Product",
Toast.LENGTH_SHORT).show();
}
}
}
/**
* GetTheBrochureAndAttachedVideoURL
*
* #param jsonResponse
*/
public void urlFromResponse(String jsonResponse) {
try {
json = new JSONTokener(jsonResponse).nextValue();
if (json instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) json;
prodBrochureURL = jsonArray.getJSONObject(0).getString(
BsharpConstant.PRODUCT_BROCHURE_URL);
prodVideoURL = jsonArray.getJSONObject(0).getString(
BsharpConstant.PRODUCT_VIDEO_URL);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private class DownloadFile extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String filename = "brochure.pdf";
HttpURLConnection connection;
try {
URL url = new URL(prodBrochureURL);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty(
BsharpConstant.WEB_SERVICES_COOKIES, cookie);
connection.setDoOutput(true);
connection.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File folderDir = new File(getExternalFilesDir("Bsharp_PDF")
+ "/Download");
File file = new File(folderDir, filename);
if (file.exists()) {
file.delete();
}
if ((folderDir.mkdirs() || folderDir.isDirectory())) {
try {
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(
folderDir + "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len1);
}
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Unable to create folder", Toast.LENGTH_LONG).show();
}
return "Done";
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
super.onPostExecute(result);
}
}
}
In order for an AsyncTask (DownloadFile in your case) to be executed one has to explicitly call its execute(Params... params) method. In your case in addition to instantiating your task call execute without providing any parameters, i.e.
DownloadFile task = new DownloadFile();
task.execute();
Hope this helps.
I've build an app for managing transactions and i'm currently adding dropbox backup. I do this by uploading the databasefiles to dropbox (which seems to be appearing correctly). Then i want to download the files again and overwrite the existing databases. When i do this the databases get saved as files ei. get listed by context.fileList(); instead of context.databaseList(); How do i handle the database files to get them in the right place?
Here is the code i thought relevant:
private static class Downloader extends AsyncTask<Integer, Integer, Boolean>{
Context context;
#Override
protected void onPreExecute(){
context = SpendoBase.getContext();
}
#Override
protected Boolean doInBackground(Integer... arg0) {
System.out.println("DoInBackground:");
try {
List<DropboxAPI.Entry> entries = mDBApi.metadata("/", -1, null, true, null).contents;
File file;
FileOutputStream os;
int count = 0;
for(DropboxAPI.Entry entry: entries){
count++;
System.out.println("Entry.path(): " + entry.path + " " + count + "/" + entries.size());
file = new File(entry.path);
System.out.println("1");
os = context.openFileOutput(file.getName(), Context.MODE_PRIVATE);
System.out.println("2");
DropboxFileInfo info = mDBApi.getFile(entry.path, null, os, null);
os.flush();
os.close();
System.out.println("3 " + info);
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
private static class Uploader extends AsyncTask<Integer, Integer, Boolean>{
String[] databaseList;
Context context;
#Override
protected void onPreExecute(){
context = SpendoBase.getContext();
databaseList = context.databaseList();
}
#Override
protected Boolean doInBackground(Integer... params) {
for(String dbName: databaseList){
try {
File f = context.getDatabasePath(dbName);
FileInputStream fis = new FileInputStream(f.getPath());
mDBApi.putFileOverwrite("/" + dbName, fis, f.length(), null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DropboxException e) {
e.printStackTrace();
}
}
return null;
}
}
private static class MetaReader extends AsyncTask<Integer, Integer, List<String>>{
#Override
protected List<String> doInBackground(Integer... arg0) {
try {
List<String> result = new Vector<String>();
DropboxAPI.Entry existingEntry = mDBApi.metadata("/", -1, null, true, null);
List<DropboxAPI.Entry> temp = existingEntry.contents;
for(int i = 0; i < temp.size(); i++){
File f = new File(temp.get(i).path);
result.add(f.getName());
}
return result;
} catch (DropboxException e) {
System.out.println("Something went wrong: " + e);
}
return null;
}
#Override
protected void onPostExecute(List<String> result){
for(String str:result){
System.out.println(str);
}
}
}
I don't do much Android development, so I could be way off base here, but why can't you just use context.getDatabasePath(dbName) again in the Downloader and write the file to that path?
I managed to solve it. My error was simply that I saved the database in the wrong place.
Changing:
file = new File(entry.path);
System.out.println("1");
os = context.openFileOutput(file.getName(), Context.MODE_PRIVATE);
to:
file = new File("/data/data/com.SverkerSbrg.SpendoFull/databases/" + entry.path);
System.out.println("1");
os = new FileOutputStream(file.getPath());
Solved the problem
You need to root your target phone to save your file on /data/data/com.SverkerSbrg.SpendoFull/databases/ this location.
I am developing an application in which I am using database and storing that database file with .db extention into sdcard .. Now I want to convert this "db file into .csv", so that the user can open that .csv file and can easily able to see all its data...
Hey I got the answer of my own question: I downloaded a library OpenCSV and added opencsv.jar file into my application and the below code:
class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean>{
private final ProgressDialog dialog = new ProgressDialog(MyDatabaseActivity.this);
// can use UI thread here
#Override
protected void onPreExecute(){
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
// automatically done on worker thread (separate from UI thread)
protected Boolean doInBackground(final String... args){
File dbFile=getDatabasePath("mydb.db");
// DbClass DBob = new DbClass(MyDatabaseActivity.this);
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, "excerDB.csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
//SQLiteDatabase db = DBob.getReadableDatabase();
Cursor curCSV=mydb.rawQuery("select * from " + TableName_ans,null);
// Cursor curCSV = db.rawQuery("SELECT * FROM table_ans12",null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext()){
String arrStr[] ={curCSV.getString(0),curCSV.getString(1)};
/*curCSV.getString(2),curCSV.getString(3),curCSV.getString(4)*/
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
return true;
} catch(SQLException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
} catch (IOException e) {
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
// can use UI thread here
#Override
protected void onPostExecute(final Boolean success) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (success) {
Toast.makeText(MyDatabaseActivity.this, "Export successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MyDatabaseActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}
}