在 Android 上将数据从 ListView 写入文本文件

Writing data from a ListView to a Text File on Android

我是 Java 和 Android 的新手,正在尝试了解如何编写 ListView 并从保存它的位置加载 ListView。

我有 ListView,ListView 上的每个项目都有一个字符串和布尔值,如果选中或取消选中该项目的复选框,它就会发生变化。我有一种将项目添加到 ListView 的工作方法,现在我正在尝试弄清楚如何将 ListView 写入文本文件。

我获得了一些通过单击菜单项来保存 ListView 的代码,当我在 OnCreate 中重新 运行 程序时,我试图加载它们,但没有加载任何内容。我不确定是写入或加载不起作用还是两者兼而有之。

这是我制作的 class 与我的 ListView 一起使用的。

Item.java

public class Item {
String name;
boolean isChecked = false;

public Item(String name) {this.name = name;}

public Item(String name, boolean checked){
    this.name = name;
    this.isChecked = checked;

}
@Override
public String toString(){
    return name;
}
}

这是我的 MainActivity.java,其中包括我的 saveList() 和 readFile()

public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getName();
ArrayList<Item> items = new ArrayList<>();
private ListView lv;
private static final String sFile = "Saved.txt";
protected ListView getListView() {
    if (lv == null) {
        lv = (ListView) findViewById(android.R.id.list);
    }
    return lv;
}

protected void setListAdapter(ListAdapter adapter) {
    getListView().setAdapter(adapter);
}

protected ListAdapter getListAdapter() {
    ListAdapter adapter = getListView().getAdapter();
    if (adapter instanceof HeaderViewListAdapter) {
        return ((HeaderViewListAdapter) adapter).getWrappedAdapter();
    } else {
        return adapter;
    }

}

private void deleteList()
{
    if (!items.isEmpty())
    {
        items.clear();
    }
    lv.invalidateViews();
}

private void deleteCheckedItems()
{
    SparseBooleanArray checked = lv.getCheckedItemPositions();
   for(int i = 0; i < lv.getCount(); i++)
    {
        if (checked.get(i)==true)
        {
            items.remove(i);
        }
        lv.invalidateViews();
    }

    lv.clearChoices();

}

private void saveList(ArrayList<Item> itemlist) {
    try {
        OutputStreamWriter out = new OutputStreamWriter(openFileOutput(sFile, 0));
        int iCnt = 0;
        String allstring = "";
        for (Item s : items)
        {
            if (s.isChecked)
            {
                iCnt++;
                if (iCnt < items.size()) {
                    String thisstring;
                    thisstring = s.name + "\r\n";
                    out.write(thisstring);
                    allstring += thisstring;
                } else {
                    String thisstring;
                    thisstring = s.name;
                    out.write(thisstring);
                    allstring += thisstring;
                }
            }

        }
        out.close();
        //Toast.makeText(activity, allstring + " Written", duration).show();
    }
    catch (java.io.FileNotFoundException e)
    {

    }
    catch (Exception ex)
    {
      //  Toast.makeText(activity, "Write Exception : " + ex.getMessage(), duration).show();
    }

}

public String readFile(ArrayList<Item> itemsList)
{
    String sRet = "Nothing";

    try
    {
        InputStream is = openFileInput(sFile);
        if (is != null)
        {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String sLine;
            StringBuffer sb = new StringBuffer();

            while ((sLine = br.readLine()) != null)
                sb.append(sLine + "\r\n");

            is.close();
            sRet = sb.toString();
           // Toast.makeText(Toast.LENGTH_LONG).show();
        }
    }

    catch (java.io.FileNotFoundException e)
    {

    }

    catch (Exception ex)
    {
     //   Toast.makeText(activi"Read Exception" + ex.getMessage(), Toast.LENGTH_LONG).show();
    }

    return sRet;
}


private void addItemDialog()
{

    LayoutInflater inflater = LayoutInflater.from(this);
    final View addView = inflater.inflate(R.layout.add, null);

    new AlertDialog.Builder(this)
            .setTitle("Add Item")
            .setView(addView)
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    EditText txtAdd = (EditText) addView.findViewById(R.id.etInput);
                    String sItem = (txtAdd).getText().toString();
                    items.add(new Item(sItem));
                    for (int i = 0; i < items.size(); i++)
                    {
                        lv.setItemChecked(i, items.get(i).isChecked);
                    }

                }

            })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                        }
                    }).show();
}


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

    setListAdapter(new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_multiple_choice, items));

    lv = this.getListView();
    for (int i = 0; i < items.size(); i++)
    {
        lv.setItemChecked(i, items.get(i).isChecked);
    }
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    readFile(items);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {


    switch(item.getItemId()){
        case R.id.add_item:
            addItemDialog();
            return true;
        case R.id.clear_all:
            deleteList();
            return true;
        case R.id.clear_checked:
            deleteCheckedItems();
            return true;
        case R.id.write:
            saveList(items);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }


}
}

在声明之后将您的 oncreate 方法放在上面,这意味着在这一行之后

     private static final String sFile = "Saved.txt";
      @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
        .......
        .......
        //your code
        }

    //other method

阅读Android activity lifecyle以更好地理解