0

I'm trying to create a ListPreference that displays a list of successfully connected IP addresses.

I mark an IP address as successfully connected in my MainActivity and I was hoping there was a way that I can append the successful IP address as an array to SharedPreferences somehow so that when the user opens the PreferencesActivity, there is a ListPreference that shows the IP addresses I marked as a success.

I've looked at this post already and it's really close but I don't think I can convert a SharedPreference string set to a CharSequence[] can I?

Here's my code so far:

public class IPHistoryListPreference extends ListPreference {

   SharedPreferences sharedPref;

   public IPHistoryListPreference(Context context, AttributeSet attrs) {
       super(context, attrs);
       sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
   }

   public IPHistoryListPreference(Context context) {
       super(context);
       sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
   }

   @Override
   protected View onCreateDialogView() {
       ListView view = new ListView(getContext());
       view.setAdapter(adapter());
   }

   private ListAdapter adapter() {
       return new ArrayAdapter(getContext(), android.R.layout.select_dialog_singlechoice);
   }

   private CharSequence[] entries() {
    //convert sharedPref stringSet to CharSequence[] ?
   }

   private CharSequence[] entryValues() {
    //convert sharedPref stringSet to CharSequence[] ?
   }

}
Jason
  • 445
  • 1
  • 6
  • 16

2 Answers2

0

You could pipe your response into a string and then do a split into an array to get each IP address.

Eg string IPS = "some IP address|some IP address......
Joshua
  • 589
  • 1
  • 5
  • 19
0

I solved this with a bit of a hacky solution.

First was converting a Set<String> to a CharSequence[]:

Set<String> stringSet = sharedPref.getStringSet("IPEntries", null);
    return stringSet.toArray(new CharSequence[stringSet.size()]);

Then to extract the set in my MainActivity, I just used this code:

Set<String> set = sharedPref.getStringSet("IPEntries", null);
if (set == null) {
                set = new HashSet<>();
                set.add(ipAddressName);
            }
            if (!set.contains(ipAddressName)) {
                set.add(ipAddressName);
            }
            sharedPref.edit().putStringSet("IPEntries", set).apply();
Jason
  • 445
  • 1
  • 6
  • 16