Sqlite数据到Android中的CSV文件 [英] Sqlite Data To CSV file in android
本文介绍了Sqlite数据到Android中的CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我运行此代码时的代码,它不会在SD卡中存储或生成任何文件.我不知道我在哪里做错,对不起,因为我是编程的始作俑者
This is my code when i run this it does not store or generate any file in my sd card. I dont know where i'm doing mistake sorry for mistake as im begginer in programming
List<ClientModel> list = new ArrayList<ClientModel>(); //My Model
DatabaseHelper db = new DatabaseHelper(getApplicationContext()); //My DBHelper Class
list = db.getAllClientList(); //My Method to get all data from database
File exportDir = new File(Environment.getExternalStorageDirectory(), ""); //
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "Abc.csv"); //File Name
//writing data to a txt file
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file)); //Writing data in csv file
for (int index = 0; index < list.size();) {
String arrStr[] = { String.valueOf(list.get(0))};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
//But Above Code is not working for me
} catch (IOException e) {
e.printStackTrace();
}
推荐答案
您需要检查Api 23的运行时permission
:
you need to check runtime permission
for Api 23:
尝试一下:
if(isStoragePermissionGranted()){
Save_file();
}
现在在您的活动中添加以下方法:
Now add this methods in your activity:
public void Save_file(){
File exportDir = new File(Environment.getExternalStorageDirectory(), ""); //
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "Abc.csv"); //File Name
//writing data to a txt file
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file)); //Writing data in csv file
for (int index = 0; index < list.size();) {
String arrStr[] = { String.valueOf(list.get(0))};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
//But Above Code is not working for me
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
Save_file();
}
}
这篇关于Sqlite数据到Android中的CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文