ListView的每一行包含5个用分号分隔的字符串,如下所示:
str1; str2; str3; str4; str5
列表的记录长度可能会有所不同,有时可能会达到400
如何将列表保存到CSV文件(在设备的内部存储中,应用程序文件夹路径)
使用ArrayAdapter:
private static MainActivity inst;
ArrayList<String> inList = new ArrayList<String>();
ListView myList;
ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.dataList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, inList);
myList.setAdapter(arrayAdapter);
}
在ListView中采样数据:
Shop1;橙子; 10; 200; 2000 Shop2; orange; 8; 150; 1200 Shop3; lemon; 20; 100; 2000
答案 0 :(得分:0)
我准备了一个示例活动供您参考。
public class MainActivity extends Activity {
ArrayList<String> listDataArray;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String line1 = "Shop1; orange; 10; 200;2000";
String line2 = "Shop2;orange;8;150;1200";
String line3 = "Shop3;lemon;20;100;2000";
listDataArray = new ArrayList<>();
listDataArray.add(line1);
listDataArray.add(line2);
listDataArray.add(line3);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listDataArray);
((ListView) findViewById(R.id.listviewData)).setAdapter(arrayAdapter);
}
public void processCSV(View view) {
try {
boolean writePermissionStatus = checkStoragePermission(false);
//Check for permission
if (!writePermissionStatus) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return;
} else {
boolean writePermissionStatusAgain = checkStoragePermission(true);
if (!writePermissionStatusAgain) {
Toast.makeText(this, "Permission not granted", Toast.LENGTH_LONG).show();
return;
} else {
//Permission Granted. Export
exportDataToCSV();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String toCSV(String[] array) {
String result = "";
if (array.length > 0) {
StringBuilder sb = new StringBuilder();
for (String s : array) {
sb.append(s.trim()).append(",");
}
result = sb.deleteCharAt(sb.length() - 1).toString();
}
return result;
}
private void exportDataToCSV() throws IOException {
String csvData = "";
for (int i = 0; i < listDataArray.size(); i++) {
String currentLIne = listDataArray.get(i);
String[] cells = currentLIne.split(";");
csvData += toCSV(cells) + "\n";
}
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String uniqueFileName = "FileName.csv";
File file = new File(directory, uniqueFileName);
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(csvData);
fileWriter.flush();
fileWriter.close();
Toast.makeText(MainActivity.this, "File Exported Successfully", Toast.LENGTH_SHORT).show();
}
private boolean checkStoragePermission(boolean showNotification) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
if (showNotification) showNotificationAlertToAllowPermission();
return false;
}
} else {
return true;
}
}
private void showNotificationAlertToAllowPermission() {
new AlertDialog.Builder(this).setMessage("Please allow Storage Read/Write permission for this app to function properly.").setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}).setNegativeButton("Cancel", null).show();
}
}
说明
String
。ArrayList
,并添加了所有这3个示例数据。我们以ArrayList
为数据。Adapter
,然后将其添加到ListView
中进行显示。Button
导出CSV ,以将CSV导出到外部目录“下载文件夹”。当用户点击导出CSV 时,将开始以下过程:
exportDataToCSV()
方法。ArrayList
中的所有行(行)以填充列表视图(通过在适配器中进行设置),并获取currentLine
。;
作为分隔符分割内容,并创建本地字符串Array
。toCSV
方法,该方法将数据与,
连接,因为它将用于创建CSV(逗号分隔值)。在每行末尾添加一个空白行\n
,以创建行。csvData
中之后,将输出写入文件。很显然,这样做的方法可能更有效,但是我尽可能地将每个功能分开,以使其易于理解。
从currentLine
生成CSV的另一种方法是直接将;
替换为,
。您应该自己尝试。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ListView
android:id="@+id/listviewData"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:onClick="processCSV"
android:text="Export CSV" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.myapplication">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>