如何在按钮点击时以文本格式保存listview的所有数据

时间:2017-03-31 05:35:57

标签: android android-layout listview android-studio android-api-levels

<TextView
    android:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    android:textColor="#000000"
    android:textSize="20sp"/>

我是Android编程的新手请大家帮助我。如何在我们的手机按钮点击中以文本格式保存Listview的所有数据

 static String[] city = {"Indore","Bhopal","Mumbai","Pune","Delhi","Kolkata",
        "Hyderabad","Banglore","Chennai","Amritsar","jhalandhar"};

Button button;
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    listView = (ListView) findViewById(R.id.lv);

    MyAdapter myadapter = new MyAdapter(getApplicationContext(),city);
    listView.setAdapter(myadapter);

2 个答案:

答案 0 :(得分:0)

希望这会有所帮助。

SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
    for (int i = 0 ; i < items.size(); i++) {
        ListViewItem item = items.get(i);
        edit.putString(Integer.toString(i), item.elementOne + "," + item.elementTwo + "," + item.elementthree);
    }
    edit.commit();

答案 1 :(得分:0)

在按钮的单击

上写下此代码
try {
        File myFile = new File("/sdcard/mysdfile.txt");
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter =
                new OutputStreamWriter(fOut);
        for (int i = 0; i < city.length; i++) {
            myOutWriter.append(city[i] +"\n");    
        }

        myOutWriter.close();
        fOut.close();
        Toast.makeText(getBaseContext(),
                "Done writing SD 'mysdfile.txt'",
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(),
                Toast.LENGTH_SHORT).show();
    }

注意:请勿忘记在AndroidMenifest.xml

中授予以下权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />