我有一个简单的日志记录应用程序,它将数据收集到三个数组列表中,我想将其保存到 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 protected] /cdn-cgi/l/email-protection"});
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");
}
一切都编译并正常运行。但是,当我上传到云端硬盘时,它显示“无法上传”,当我发送电子邮件时,它显示“无法附加空文件”。