Populating a ListView from SharedPreferences

2019-06-10 03:52发布

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.

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.

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.

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.

Here is my code:

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!

Cheers for the help!

3条回答
Luminary・发光体
2楼-- · 2019-06-10 04:24

How many phrases are you saving into shared prefs? If it's more than just a few (say, 10), I would suggest that you use a sqlite database instead. Shared preferences are not designed for large lists of data.

Anyways, I think I may have found your problem. When you click the "Save" button, this code runs:

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

You already set the adapter to use the listItems array at the beginning, and (I believe) now adapter has it's own internal array that it's using to hold the data. Try this:

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

In fact, I don't think you really need the listItems array as an instance variable, and you should be able to get rid of phrasesCollection entirely. Back at the beginning in your onCreate method, try this:

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

}

Hopefully this helps.

查看更多
闹够了就滚
3楼-- · 2019-06-10 04:36

Maybe contents of rows are being shown, but their font color is black! Test it by clicking on them or set background color for listview.

查看更多
一夜七次
4楼-- · 2019-06-10 04:39

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

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

Updated source code:

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

Enjoy!

查看更多
登录 后发表回答