将列表视图保存到 txt 文件

Posted

技术标签:

【中文标题】将列表视图保存到 txt 文件【英文标题】:Save listview to txt file 【发布时间】:2015-03-14 21:22:12 【问题描述】:

我正在尝试将 ListView 中的所有项目保存到文本文件中。我正在制作一个项目,然后单击此按钮将其保存。

@Override
public void onClick(View v) 
    switch(v.getId()) 

        case R.id.addItem:

            items.add(new ListViewItem() 

                ThumbnailResource = R.mipmap.ic_launcher;
                Title = et.getText().toString();
                SubTitle = "Item2 Description";

            );
            lv.setAdapter(adapter);

            // add-write text into file
            try 
                fileout = openFileOutput("mytextfile.txt", MODE_PRIVATE);
                outputWriter = new OutputStreamWriter(fileout);
                outputWriter.write(et.getText().toString());
                outputWriter.close();

                //display file saved message
                Toast.makeText(getBaseContext(), "File saved successfully!",
                        Toast.LENGTH_SHORT).show();

             catch (Exception e) 
                e.printStackTrace();
            
        break;

然后当人退出应用程序并返回时,此代码在创建时将列表项添加回来。

  try 
        FileInputStream fileIn=openFileInput("mytextfile.txt");
        InputStreamReader InputRead= new InputStreamReader(fileIn);

        char[] inputBuffer= new char[READ_BLOCK_SIZE];
        String start="";
        int charRead;

        while ((charRead=InputRead.read(inputBuffer))>0) 
            // char to string conversion
            String readstring=String.copyValueOf(inputBuffer,0,charRead);
            start +=readstring;
        
        InputRead.close();
        final String finalStart = start;
        items.add(new ListViewItem() 

            ThumbnailResource = R.mipmap.ic_launcher;
            Title = finalStart;
            SubTitle = "Item2 Description";

        );
        lv.setAdapter(adapter);
        Toast.makeText(getBaseContext(), start,Toast.LENGTH_SHORT).show();

     catch (Exception e) 
        e.printStackTrace();
    

问题是它一次只保存一个 ListView 项目。不是所有的,即使它在每次按钮点击后保存。我如何让它将所有他的项目保存到 txt 文件中。不只是最近的?

谢谢。

这是我所有的代码:

主活动:

 public class MainActivity extends ActionBarActivity implements 
 View.OnClickListener

EditText et;

Button bt;

ListView lv;

List<ListViewItem> items;

CustomListViewAdapter adapter;

FileOutputStream fileout;

OutputStreamWriter outputWriter;

static final int READ_BLOCK_SIZE = 100;

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

    et = (EditText) findViewById(R.id.editText);
    bt = (Button) findViewById(R.id.addItem);
    bt.setOnClickListener(this);

    lv = (ListView) findViewById(R.id.listView);
    items = new ArrayList<ListViewItem>();
    adapter = new CustomListViewAdapter(this, items);

    try 
        FileInputStream fileIn=openFileInput("mytextfile.txt");
        InputStreamReader InputRead= new InputStreamReader(fileIn);

        char[] inputBuffer= new char[READ_BLOCK_SIZE];
        String start="";
        int charRead;

        while ((charRead=InputRead.read(inputBuffer))>0) 
            // char to string conversion
            String readstring=String.copyValueOf(inputBuffer,0,charRead);
            start +=readstring;
        
        InputRead.close();
        final String finalStart = start;
        items.add(new ListViewItem() 

            ThumbnailResource = R.mipmap.ic_launcher;
            Title = finalStart;
            SubTitle = "Item2 Description";

        );
        lv.setAdapter(adapter);
        Toast.makeText(getBaseContext(), start,Toast.LENGTH_SHORT).show();

     catch (Exception e) 
        e.printStackTrace();
    

    lv.setOnItemLongClickListener(new ListView.OnItemLongClickListener() 
        // setting onItemLongClickListener and passing the position to the function
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int position, long arg3) 
            removeItemFromList(position);

            return true;
        
    );


@Override
public void onClick(View v) 
    switch(v.getId()) 

        case R.id.addItem:

            items.add(new ListViewItem() 

                ThumbnailResource = R.mipmap.ic_launcher;
                Title = et.getText().toString();
                SubTitle = "Item2 Description";

            );
            lv.setAdapter(adapter);

            // add-write text into file
            try 
                fileout = openFileOutput("mytextfile.txt", MODE_PRIVATE);
                outputWriter = new OutputStreamWriter(fileout);
                outputWriter.write(et.getText().toString());
                outputWriter.close();

                //display file saved message
                Toast.makeText(getBaseContext(), "File saved successfully!",
                        Toast.LENGTH_SHORT).show();

             catch (Exception e) 
                e.printStackTrace();
            
        break;
    



class ListViewItem 

        public int ThumbnailResource;
        public String Title;
        public String SubTitle;


protected void removeItemFromList(int position) 
    final int deletePosition = position;

    AlertDialog.Builder alert = new AlertDialog.Builder(
            MainActivity.this);

    alert.setTitle("Delete");
    alert.setMessage("Do you want delete this item?");
    alert.setPositiveButton("YES", new DialogInterface.OnClickListener() 
        @Override
        public void onClick(DialogInterface dialog, int which) 
            // TOD O Auto-generated method stub

            // main code on after clicking yes
            items.remove(deletePosition);
            adapter.notifyDataSetChanged();
            adapter.notifyDataSetInvalidated();

        
    );
    alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() 
        @Override
        public void onClick(DialogInterface dialog, int which) 
            // TODO Auto-generated method stub
            dialog.dismiss();
        
    );

    alert.show();

    

自定义视图适配器:

public class CustomListViewAdapter extends BaseAdapter 

LayoutInflater inflater;
List<MainActivity.ListViewItem> items;

public CustomListViewAdapter(Activity context, List<MainActivity.ListViewItem> items) 
    super();

    this.items = items;
    this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


@Override
public int getCount() 
    // TODO Auto-generated method stub
    return items.size();


@Override
public Object getItem(int position) 
    // TODO Auto-generated method stub
    return null;


@Override
public long getItemId(int position) 
    // TODO Auto-generated method stub
    return 0;


@Override
public View getView(final int position, View convertView, ViewGroup parent) 
    // TODO Auto-generated method stub

    MainActivity.ListViewItem item = items.get(position);

    View vi=convertView;

    if(convertView==null)
        vi = inflater.inflate(R.layout.item_row, null);

    ImageView imgThumbnail = (ImageView) vi.findViewById(R.id.imgThumbnail);

    TextView txtTitle = (TextView) vi.findViewById(R.id.txtTitle);

    TextView txtSubTitle = (TextView) vi.findViewById(R.id.txtSubTitle);

    imgThumbnail.setImageResource(item.ThumbnailResource);

    txtTitle.setText(item.Title);

    txtSubTitle.setText(item.SubTitle);

    return vi;
   

【问题讨论】:

为什么要保存到文件而不是保存到 ShredPrefernces? 无论如何,您都可以在活动/片段的 onStop() 中添加方法,该方法在 listView 上循环并保存所有数据。 如何将该方法添加到 onstop 或共享偏好,以较容易者为准 最好的方法是将信息保存在数据库中,例如:***.com/questions/23284889/… 【参考方案1】:

把它放在你的 onStop 中:

 @Override
 public void onStop()
    super.onStop();
    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.ThumbnailResource + "," + item.Title + "," + item.SubTitle);
    
    edit.commit();

要检索此数据,请在 onResume() 中添加类似的内容:

SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences(this);
    String item = myPref.getString(Integer.toString(0), "empty");
    int i = 0;
    do 
        String[] result = item.split(",");
        ListViewItem listItem = new ListViewItem();
        listItem.ThumbnailResource = Integer.valueOf(result[0]);
        listItem.Title = result[1];
        listItem.SubTitle = result[2];
        items.add(listItem);
        i++;
        item = myPref.getString(Integer.toString(i), "empty");
     while (!item.equals("empty"));

【讨论】:

我觉得这会起作用,但你是对的,狭缝导致我的应用程序在启动时强制关闭。我应该如何拆分它,以免发生这种情况

以上是关于将列表视图保存到 txt 文件的主要内容,如果未能解决你的问题,请参考以下文章

需要将表格视图的内容保存为 txt 文件并稍后重新加载

Android:如何将列表视图保存在根目录中

从 JSON 文件保存和加载表视图?

带有列表视图的 C# 建议

backone-保存到带有嵌套视图的数据库

打开/保存文件对话框设置焦点到文件列表视图