删除ListView项从列表和共享preferences [英] Deleting ListView item from list and SharedPreferences

查看:110
本文介绍了删除ListView项从列表和共享preferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,并有一些类似的问题,但没有一个有效的解决方案。

I've looked around, and there are some similar questions, but none with a working solution.

我创建了一个简单的ListView从一个EditText需要输入,并点击按钮列表中显示出来。如果点击列表项目,我有一个对话框弹出,并要求您确认删除。当是点击,则该项目出现删除。但如果我再试着删除另一个项目,该项目将删除,但previous项目将在它的地方出现。我不知道如何解决这个问题。从我有限的了解,好像是该项目从来没有从共享preferences删除,当我再次加载它们的下一个的onClick,老项目再次出现。虽然我已经试过清除共享preferences,然后删除,没有工作后,节省了他们。

I've created a simple ListView to take input from an EditText and display it in a list on button click. If a list item is clicked, I have a dialog popup and ask for confirmation to delete. When "yes" is clicked, the item appears to delete. Though if I then try to delete another item, that item will delete, but the previous item will reappear in its place. I have no idea how to solve this problem. From my limited understanding it seems as though the item is never deleted from SharedPreferences, and when I load them again on the next "onClick", the old item appears again. Though I've tried clearing SharedPreferences and then saving them after deleting, which did not work.

package com.example.send2omni;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.AndroidCharacter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class ContextsList extends Activity {

public static final String CONTEXTS = "contexts_list";

EditText display;
ListView lv;
public ArrayAdapter<String> adapter;
Button addButton;
String temp_appender;
String appender = "";
List<String> dataset;
String[] splitup;
public String items;
ArrayList<String> itemsarraylist;


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

    display = (EditText) findViewById(R.id.editText);
    lv = (ListView) findViewById(R.id.listView);
    addButton = (Button) findViewById(R.id.bAdd);
    LoadPreferences();
    lv.setAdapter(adapter);
    LoadPreferences();
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);

    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            appender = LoadPreferences();
            if(display.getText().toString() != null){
                temp_appender = display.getText().toString();
                String string_to_split = appender + "," + temp_appender;
                List<String> items = Arrays.asList(string_to_split.split(","));
                adapter = new ArrayAdapter<String>
(getApplicationContext(), android.R.layout.simple_list_item_1, items);

                lv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                SavePreferences("LISTS", string_to_split, null);

                LoadPreferences();
            }


            display.setText("");
        }
    });

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            deleteItem(arg1);
        }
    });

}

protected void deleteItem(final View arg1)
{
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    dialogBuilder.setTitle("Delete");
    dialogBuilder.setMessage
("Do you want to delete \"" + ((TextView) arg1).getText() + "\"?");
    dialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {


            String splitit = LoadPreferences();
            List<String> listit = Arrays.asList(splitit.split(","));
            ArrayList<String> itemsarraylist = new ArrayList<String>();
            for(int i = 0; i <listit.size(); i++){
                itemsarraylist.add(i, listit.get(i));
            }


            try {
                adapter.remove(((TextView) arg1).getText().toString());
                adapter.notifyDataSetChanged();
                itemsarraylist.remove(((TextView) arg1).getText().toString());


                try{
                    SavePreferences("LISTS", null, itemsarraylist);


                }catch(Exception e){

                }
            } catch (Exception e) {


                Log.e("remove", "failed");
            }



        }


    });
    dialogBuilder.setNeutralButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    AlertDialog deleteDialog = dialogBuilder.create();
    deleteDialog.show();
}


protected void SavePreferences(String key, String value, ArrayList<String> opt) {
    // TODO Auto-generated method stub
    SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);

    if (opt != null){
        for (int i = 0 ; i <= opt.size(); i++)
            value += opt.get(i) + ",";
    }

    SharedPreferences.Editor editor = data.edit();
    editor.putString(key, value);
    editor.commit();


}

protected String LoadPreferences(){
    SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
    String dataSet = data.getString("LISTS", "");
    dataset = Arrays.asList(dataSet.split(","));
    splitup = dataSet.split(",");



    List<String> items = Arrays.asList(dataSet.split(","));
    ArrayList<String> itemsarraylist = new ArrayList<String>();
    for(int i = 0; i <items.size(); i++){
        itemsarraylist.add(i, items.get(i));
    }
    adapter = new ArrayAdapter<String>
    (this, android.R.layout.simple_list_item_1,  itemsarraylist);

    lv.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    return dataSet;

}

}

我已经包括一切从类code,以防万一,你必须尝试一下在你的IDE的时间,因为工作的部分可能是其他初学者有用。

I've included all the code from the class, just in case you have the time to try it out in your IDE, and because the working part may be useful to other beginners.

我不能EX preSS我的感激之情会是如果有人可以帮助我解决这个问题。这是pretty多最后一步我完成我的第一个应用之前拿的,我真的不期待着有学习SQLite的只是为了节省字符串列表。

I can't express how grateful I'd be if anyone could help me fix this. It's pretty much the last step I have to take before completing my first app, and I'm really not looking forward to having to learn SQLite just to save a list of strings.

感谢您的时间大家..

Thanks for your time everyone..

推荐答案

您需要修改

for (int i = 0 ; i <= opt.size(); i++) {

这行178

for (int i = 0 ; i < opt.size(); i++) {

您应该已经发现了的ArrayIndexOutOfBounds 例外,但因为你是追赶它在线145和未打印堆栈跟踪,你从来没有看到它。

You should have spotted the ArrayIndexOutofBounds exception but since you're catching it on line 145 and aren't printing a stacktrace, you're never seeing it.

编辑:您可能还需要删除您要添加的值。
像这样的东西应该工作

You might also need to remove the "," that you're adding to the values. Something like this should work

value += opt.get(i);
if (i != opt.size() - 1)
    value += ",";

这篇关于删除ListView项从列表和共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆