从 SharedPreferences 填充 ListView [英] Populating a ListView from SharedPreferences

查看:35
本文介绍了从 SharedPreferences 填充 ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是从 AlertDialog 条目填充 ListView.我曾尝试使用 SharedPreferences 来做到这一点,以前我将最后一个条目保存到 ListView(如果我输入了多个字符串),所以当我离开活动并返回列表中出现的所有内容时,这是我的最后一个入口.

What I'm looking to do is populate a ListView from an AlertDialog entry. I've tried to do this with SharedPreferences, previously I've had the last entry just saving into the ListView (if I entered more than one String), so when I left the activity and returned all that appeared in the list was my last entry.

但是我发现了这个问题,并修改了保存过程,通过增加附加的 Int 变量来更改存储首选项的键"字段.

However I figured that problem out and have modified the save procedure to change the "Key" field of the stored preference by incrementing an attached Int variable.

为了让您全面了解正在发生的事情:第一个帖子所以图片在这里:http://imgur.com/yGLQx这是 ListView 的多个条目的输出.

To give you the full picture of what's happening: First post so pic is here : http://imgur.com/yGLQx This is the output of multiple entries to the ListView.

如果您留在 Activity 中,ListView 将填充来自用户的条目,但是在离开 Activity 并返回后,它就像条目已注册,但字符串值尚未保存.

If you remain within the Activity, the ListView is populated with the entries from the user, however after leaving the activity and returning to it, its like the entries have been registered, but the String values have not been saved.

这是我的代码:

public class ManageLinguisticPhrases extends ListActivity {

private static final String PHRASE = "Phrase_";

private SharedPreferences prefs;
private String prefName = "myPhrasesStorage";

ArrayList <String> listItems = new ArrayList <String>();    
ArrayAdapter <String> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    adapter = new ArrayAdapter <String> (this, android.R.layout.simple_list_item_1, listItems);
    setListAdapter(adapter); 

    prefs = getSharedPreferences(prefName, MODE_PRIVATE);
    LinkedList<String> phrasesCollection = new LinkedList<String>();
    int phraseCount = prefs.getInt("phrase_count", 0);

    for(int i = 1; i <= phraseCount; i++) { 
        phrasesCollection.add(prefs.getString(PHRASE + i, "<< Enter a phrase >>"));
    }

    listItems.addAll(phrasesCollection);
    adapter.notifyDataSetChanged();               

}


@Override
protected Dialog onCreateDialog(int id) 
{

    final EditText input = new EditText(this);
    final String text = input.getText().toString();

    switch (id) 
    {
    case 0:
        return new AlertDialog.Builder(this)
        .setIcon(R.drawable.ic_launcher)
        .setTitle("Please enter the new data")
        .setView(input)
        .setPositiveButton("Save", new DialogInterface.OnClickListener() 
        {   
            public void onClick(DialogInterface dialog, int whichButton)
            {                                           
                listItems.add(input.getText().toString());                  
                adapter.notifyDataSetChanged();

                prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                    //increments index by 1
                    editor.putInt("phrase_count", prefs.getInt("phrase_count", 0) + 1);
                    //save new phrase in myPhrasesStorage with key "name[index]"                
                    editor.putString(PHRASE + (prefs.getInt("phrase_count", 0) + 1), text);

                editor.commit();

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


            }
    })      

            .create();
    }
    return null;
}

private void CreateMenu(Menu menu)
{
    MenuItem mnu1 = menu.add(0, 0, 0, "Add data");
    {
        mnu1.setAlphabeticShortcut('a');
        mnu1.setIcon(android.R.drawable.ic_menu_add);
    }
    MenuItem mnu2 = menu.add(0, 1, 1, "Edit data");
    {
        mnu2.setAlphabeticShortcut('b');
        mnu2.setIcon(android.R.drawable.ic_menu_edit);
    }
    MenuItem mnu3 = menu.add(0, 2, 2, "Delete data");
    {
        mnu3.setAlphabeticShortcut('c');
        mnu3.setIcon(android.R.drawable.ic_menu_delete);
    }

}

private boolean MenuChoice(MenuItem item)
{
    switch (item.getItemId()) 
    {
        case 0:

            showDialog(0);

        return true;            
    }
    return false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    super.onCreateOptionsMenu(menu);
    CreateMenu(menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    return MenuChoice(item);
}

所以是的,看看,告诉我我是否在做一些可笑的事情,让我知道!

So yeah take a look, tell me if I'm doing something ridiculous, and let me know!

为帮助干杯!

推荐答案

所以我找到了解决方案,我第一次使用 ArrayList 迭代器使它变得过于复杂.

So I found the solution, I made it overcomplicated first time round with the ArrayList Iterator.

该解决方案现在基本上从 AlertDialogListView 添加手动条目,条目存储在 ArrayList listItems 中.

The solution now basically adds manual entries to the ListView from an AlertDialog, entries are stored in an ArrayList listItems.

更新源代码:

public class ManageLinguisticPhrases extends ListActivity 
{

    private static final String PHRASE = "Phrase_";

    private String prefName = "myPhrasesStorage";
    private SharedPreferences prefs;     

    private ArrayList <String> listItems = new ArrayList <String>();         
    private  List<String> phrasesCollection = new LinkedList<String>();

    private String phraseText = "test";            
    private static int count = 0;

    private ArrayAdapter <String> adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        adapter = new ArrayAdapter <String> (this, android.R.layout.simple_list_item_1, listItems);        
        setListAdapter(adapter);      

        prefs = this.getSharedPreferences(prefName, MODE_PRIVATE);

        for(int i = 0; i <= prefs.getAll().size(); i++) {    
            phrasesCollection.add(i, prefs.getString(PHRASE + i, "Ola, Tudo bem?"));            
        }          

        listItems.addAll(phrasesCollection);
        adapter.notifyDataSetChanged();         

    }


    @Override
    protected Dialog onCreateDialog(int id) 
    {

        final EditText input = new EditText(this);

        switch (id) 
        {
        case 0:
            return new AlertDialog.Builder(this)
            .setIcon(R.drawable.ic_launcher)
            .setTitle("Please enter the new data")
            .setView(input)
            .setPositiveButton("Save", new DialogInterface.OnClickListener() 
            {    
                public void onClick(DialogInterface dialog,    int whichButton)
                {                                            
                    phraseText = input.getText().toString();
                    listItems.add(phraseText);   

                    adapter.notifyDataSetChanged();                                        

                    prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                    SharedPreferences.Editor editor = prefs.edit();                    

                    //save new phrase in myPhrasesStorage with key "Phrase_[count]"                
                    editor.putString(PHRASE + count + "", phraseText);
                    count++;

                    editor.commit();

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


                }
        })        

                .create();
        }
        return null;
    }

    private void CreateMenu(Menu menu)
    {
        MenuItem mnu1 = menu.add(0, 0, 0, "Add data");
        {
            mnu1.setAlphabeticShortcut('a');
            mnu1.setIcon(android.R.drawable.ic_menu_add);
        }
        MenuItem mnu2 = menu.add(0, 1, 1, "Edit data");
        {
            mnu2.setAlphabeticShortcut('b');
            mnu2.setIcon(android.R.drawable.ic_menu_edit);
        }
        MenuItem mnu3 = menu.add(0, 2, 2, "Clear ALL data");
        {
            mnu3.setAlphabeticShortcut('c');
            mnu3.setIcon(android.R.drawable.ic_menu_delete);
        }

    }

    private boolean MenuChoice(MenuItem item)
    {
        switch (item.getItemId()) 
        {
            case 0:

                showDialog(0);

            return true;

            case 2:

                prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();        

                editor.clear();
                editor.commit();

                listItems.clear();
                adapter.notifyDataSetChanged();

                Toast.makeText(this, "All phrases deleted",
                        Toast.LENGTH_LONG).show();

            return true;
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        return MenuChoice(item);
    }        
}

享受吧!

这篇关于从 SharedPreferences 填充 ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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