[英]How to save dynamically added items in Listview with sharedpreferences?
[英]how to save ListView items to a csv file
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 中的示例數據:
店鋪 1; 橘子; 10; 200;2000 Shop2;orange;8;150;1200 Shop3;lemon;20;100;2000
我准備了一個示例活動供您參考。
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 導出到外部目錄下載文件夾。當用戶單擊Export CSV 時,將啟動以下過程:
exportDataToCSV()
方法。ArrayList
您創建的ArrayList
中的所有行(行)以填充列表視圖(通過在適配器中設置),並獲取currentLine
。;
拆分內容作為分隔符並創建一個本地 String Array
。toCSV
方法,該方法將數據與 連接起來,
因為這將用於創建 CSV(逗號分隔值)。 在每行的末尾附加一個空行\\n
以創建行。csvData
中的所有數據,將輸出寫入文件。顯然,可以有更有效的方法來做到這一點,但我盡可能地將每個功能分開,以使其易於理解。
從currentLine
生成 CSV 的另一種方法可能是替換;
與,
直接。 你應該自己試試。
活動_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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.