从SharedPreferences填充ListView

时间:2012-03-10 16:51:32

标签: android listview arraylist alertdialog sharedpreferences

我要做的是从AlertDialog条目填充ListView。我曾尝试使用SharedPreferences执行此操作,之前我已将最后一个条目保存到ListView中(如果我输入了多个String),所以当我离开活动并返回列表中出现的所有内容时,我的最后一个条目。

但是我想出了这个问题,并修改了保存程序,通过增加附加的Int变量来更改存储的首选项的“Key”字段。

为您提供正在发生的事情的全貌: 所以图片的第一篇文章在这里:http://imgur.com/yGLQx 这是ListView的多个条目的输出。

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

这是我的代码:

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);
}

所以,请看看,告诉我,如果我做了一些荒谬的事,请告诉我!

欢呼帮助!

3 个答案:

答案 0 :(得分:0)

可能正在显示行的内容,但它们的字体颜色是黑色的!通过单击它们或为列表视图设置背景颜色来测试它。

答案 1 :(得分:0)

您在共享首选项中保存了多少个短语?如果它不仅仅是几个(比方说10),我建议您使用sqlite数据库。共享首选项不适用于大型数据列表。

无论如何,我想我可能已经找到了你的问题。单击“保存”按钮时,此代码将运行:

listItems.add(input.getText().toString());                  
adapter.notifyDataSetChanged();

您已经将适配器设置为在开头使用listItems数组,并且(我相信)现在adapter拥有它用于保存数据的内部数组。试试这个:

adapter.add(input.getText().toString());         
adapter.notifyDataSetChanged();

事实上,我认为你真的不需要listItems数组作为实例变量,你应该能够完全摆脱phrasesCollection。回到onCreate方法的开头,试试这个:

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

    prefs = getSharedPreferences(prefName, MODE_PRIVATE);

    int phraseCount = prefs.getInt("phrase_count", 0);
    ArrayList <String> listItems = new ArrayList <String>();

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

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

}

希望这有帮助。

答案 2 :(得分:0)

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

解决方案现在基本上从ListViewAlertDialog添加手动条目,条目存储在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);
    }        
}

享受!