【发布时间】:2019-04-08 02:36:30
【问题描述】:
我有一个简单的日志应用程序,它将数据收集到三个数组列表中,我希望将其保存到 CSV 文件中,然后共享到 Google Drive、电子邮件等。
这是我保存数据的方式:
StringBuilder data = new StringBuilder();
data.append("Timestamp,Mass,Change in Mass\n");
for(int i = 0; i < mass_list.size(); i++){
data.append(String.valueOf(timestamp_list.get(i))+ ","+String.valueOf(mass_list.get(i))+","+String.valueOf(mass_roc_list.get(i))+"\n");
}
FileOutputStream out = openFileOutput("scale.csv", Context.MODE_APPEND );
out.write(data.toString().getBytes());
out.close();
这只是将我的 ArrayLists 组合成一个字符串,并将数据保存到具有名称比例的 csv 文件中。
这是我尝试分享的方式:
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[{"email@gmail.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Scale Data");
emailIntent.putExtra(Intent.EXTRA_TEXT, "This is the body");
emailIntent.putExtra(Intent.EXTRA_STREAM, Environment.getExternalStorageDirectory() + "/scale.csv");
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
当我在电子邮件中尝试此操作时,没有附件,只有正文。当我尝试使用 Google Drive 时,只有正文被保存到一个文本文件中。我不确定我做错了什么,但它可能与文件位置有关。也许我找不到我保存的文件?
我将不胜感激任何帮助,并准备应要求提供澄清。
使用反馈进行编辑
我尝试了其中一种建议的解决方案。这就是我的代码现在的样子:
StringBuilder data = new StringBuilder();
data.append("Timestamp,Mass,Change in Mass\n");
for(int i = 0; i < mass_list.size(); i++){
data.append(String.valueOf(timestamp_list.get(i))+ ","+String.valueOf(mass_list.get(i))+","+String.valueOf(mass_roc_list.get(i))+"\n");
}
try {
//saving data to a file
FileOutputStream out = openFileOutput("scale.csv", Context.MODE_APPEND);
out.write(data.toString().getBytes());
out.close();
Context context = getApplicationContext();
String filename="/scale.csv";
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
Uri path = FileProvider.getUriForFile(context, "com.example.scaleapp.fileprovider", filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent.setType("vnd.android.cursor.dir/email");
String to[] = {"email.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Scale Data");
emailIntent.putExtra(Intent.EXTRA_TEXT, "This is the body");
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
//this line is where an exception occurs and "Error" is displayed on my phone
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
infoView.setText("Something worked!");
}
catch(Exception e){
e.printStackTrace();
infoView.setText("Error");
}
一切正常编译和运行。但是,当我上传到云端硬盘时,它显示“无法上传”,当我发送电子邮件时,它显示“无法附加空文件”。
【问题讨论】:
标签: java android csv android-intent export-to-csv