android 将列表视图保存到txt文件

tzdcorbm  于 2022-11-27  发布在  Android
关注(0)|答案(2)|浏览(185)

我正在尝试将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;
   }
}
ars1skjm

ars1skjm1#

把它放在你的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"));
6kkfgxo0

6kkfgxo02#

实现'com.google.code.gson:gson:2.9.1'

//Save List Item
   @Override
public void onStop() {
    super.onStop();

    Gson gson = new Gson();

    //   String arraylist_in_string = gson.toJson(income_Arraylist); //Converting it to String
    editor.putString("income_", gson.toJson(income_Arraylist)); //now saving the String
    editor.putString("expend_", gson.toJson(expend_ArrayList)); //now saving the String
    editor.commit();
}

//在我的Splash活动中//检索列表项

String income_ = sharedPreferences.getString("income_", null);

    if (income_ != null) {
        Type type = new TypeToken<ArrayList<HashMap<String, String>>>() {
        }.getType();
        List<HashMap<String, String>> list = new Gson().fromJson(income_, type);

        if (list != null && list.size() > 0) {
            income_Arraylist.clear();
            income_Arraylist.addAll(list);

        }

    }

    String expend_ = sharedPreferences.getString("expend_", null);
    if (expend_ != null) {
        Type type = new TypeToken<ArrayList<HashMap<String, String>>>() {
        }.getType();
        List<HashMap<String, String>> list = new Gson().fromJson(expend_, type);

        if (list != null && list.size() > 0) {
            expend_ArrayList.clear();
            expend_ArrayList.addAll(list);

        }

    }

    startActivity(new Intent(Splash.this, MainActivity.class));
    finish();
}

相关问题