B4A Library PreferenceActivity library

PreferenceActivity v1.01 is available.
See the tutorial for more information: http://www.b4x.com/forum/basic4andr...orials/10608-preferenceactivity-tutorial.html

preference_1.png



Installation instructions:
- Unzip the attached file.
- Copy both files to the internal libraries folder: C:\Program Files\Anywhere Software\Basic4android\Libraries

V1.01 released - fixes a bug with GetUpdatedKeys method
 

Attachments

  • PreferenceActivity.zip
    15.3 KB · Views: 1,289

Djembefola

Active Member
Licensed User
Longtime User
java.net.SocketException

Hi Erel,

On my Tablet (ACER Iconia A500, Android 3.1) the Demo Application hangs (Black Screen, "waiting for Debugger to connect") and the Log File shows:

B4X:
java.net.SocketException: Permission denied
   at org.apache.harmony.luni.platform.OSNetworkSystem.socket(Native Method)
   at dalvik.system.BlockGuard$WrappedNetworkSystem.socket(BlockGuard.java:347)
   at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:220)
   at org.apache.harmony.luni.net.PlainServerSocketImpl.create(PlainServerSocketImpl.java:40)
   at java.net.ServerSocket.<init>(ServerSocket.java:120)
   at java.net.ServerSocket.<init>(ServerSocket.java:92)
   at anywheresoftware.b4a.debug.DebugConnector.mainLoop(DebugConnector.java:83)
   at anywheresoftware.b4a.debug.DebugConnector.run(DebugConnector.java:51)
   at java.lang.Thread.run(Thread.java:1020)


Regards,
Joerg
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
On my Tablet (ACER Iconia A500, Android 3.1) the Demo Application hangs (Black Screen, "waiting for Debugger to connect") and the Log File shows:
See the explanation about manually modifying the manifest file in the above tutorial. You should either disable debugging or add this to your manifest file: <uses-permission android:name="android.permission.INTERNET" />
 

bluedude

Well-Known Member
Licensed User
Longtime User
A few wishes:

- lisitem text and value instead of just the selected text;
- option to have a preference with just a label and summary (to display data);
- file parameter to indicate to which file to save the settings, now I have two settings files;
- launch of another intent from an option;
- possibility to set the summary.

Cheers,
 

corwin42

Expert
Licensed User
Longtime User
Hello Erel,

can you add something like

B4X:
AddList2 (Key As String, Title As String, Summary As String, DefaultValue As String, Values As List, Texts as List)

So the Texts list will be displayed instead of the values? This would help much for translating apps or displaying human readable texts for somewhat cryptic values.

Perhaps a Map instead of two lists would be even better. Use the Maps key as Value and the Map Value to display in the list.

I think this will help us very much. Thanks.

PS: +1 to bluedudes suggestions (his first suggestion is exactly what I describe here and is the most important i think)
 
Last edited:

Shay

Well-Known Member
Licensed User
Longtime User
Erel,
Is there a plan to add more objects such as buttons?
If so when, since it is very good libary but limited
 
D

Deleted member 103

Guest
Hi Erel,

I would like if the list (List1) selects the text ("Black", "Red," "Green", "Blue") is displayed and does not always "This is List1".

B4X:
Sub CreatePreferenceScreen
   screen.Initialize("Settings", "")
   'create two categories
   Dim cat1, cat2 As PreferenceCategory
   cat1.Initialize("Category 1")
   cat1.AddCheckBox("check1", "Checkbox1", "This is Checkbox1", True)
   cat1.AddCheckBox("check2", "Checkbox2", "This is Checkbox2", False)
   cat1.AddEditText("edit1", "EditText1", "This is EditText1", "")
   
   cat2.Initialize("Category 2")
   cat2.AddList("list1", "List1", "This is List1", "", _
        Array As String("Black", "Red", "Green", "Blue"))
      
   'add the categories to the main screen
   screen.AddPreferenceCategory(cat1)
   screen.AddPreferenceCategory(cat2)
End Sub

How can I make it?

Ciao,
Filippo
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Yes.
B4X:
package anywheresoftware.b4a.objects;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map.Entry;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.Hide;
import anywheresoftware.b4a.BA.ShortName;
import anywheresoftware.b4a.BA.Version;
import anywheresoftware.b4a.keywords.Common;
import anywheresoftware.b4a.objects.collections.List;
import anywheresoftware.b4a.objects.collections.Map;
@Version(1.0f)
public class preferenceactivity extends PreferenceActivity{
   
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Intent in = getIntent();
      if (in == null || in.hasExtra("preferences") == false) {
         Common.Log("Intent missing root node.");
         return;
      }
      
      PreferenceScreenWrapper p = (PreferenceScreenWrapper) in.getSerializableExtra("preferences");
      PreferenceScreen ps = (PreferenceScreen) p.createPreference(this);
      this.setPreferenceScreen(ps);
      
   }
   /**
    * Provides access to the saved settings. Using PreferenceManager you can get the stored values and modify them.
    */
   @ShortName("PreferenceManager")
   public static class PreferenceManager {
      private SharedPreferences sp = android.preference.PreferenceManager.getDefaultSharedPreferences(BA.applicationContext);
      private HashSet<String> updatedKeys = new HashSet<String>();
      public PreferenceManager() {
         sp.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {

            @Override
            public void onSharedPreferenceChanged(
                  SharedPreferences sharedPreferences, String key) {
               updatedKeys.add(key);
            }
            
         });
      }
      /**
       * PreferenceActivity library allows you to show the standard settings interface and provides an easy way to handle applications settings.
       *This library requires you to modify AndroidManifest.xml. See the <link>tutorial|http://www.b4x.com/forum/basic4android-getting-started-tutorials/10608-preferenceactivity-tutorial.html</link> for more information.
       */
      public static void LIBRARY_DOC() {
         
      }
      /**
       * Returns a list with the keys that were updated since the last call to GetUpdatedKeys.
       *Note that the updated keys may include keys with unchanged values.
       */
      public List GetUpdatedKeys() {
         List l = new List();
         l.Initialize();
         for (String s : updatedKeys) {
            l.Add(s);
         }
         updatedKeys.clear();
         return l;
      }
      /**
       * Returns the String value mapped to the given key. Returns an empty string if the key is not found.
       */
      public String GetString(String Key) {
         return sp.getString(Key, "");
      }
      /**
       * Returns the Boolean value mapped to the given key. Returns False is the key is not found.
       */
      public boolean GetBoolean(String Key) {
         return sp.getBoolean(Key, false);
      }
      /**
       * Returns a Map with all the Keys and Values. Note that changes to this map will not affect the stored values.
       */
      public Map GetAll() {
         Map m = new Map();
         m.Initialize();
         for (Entry<String, ?> e : sp.getAll().entrySet()) {
            m.Put(e.getKey(), e.getValue());
         }
         return m;
      }
      /**
       * Maps the given key to the given String value.
       */
      public void SetString(String Key, String Value) {
         Editor e = sp.edit();
         e.putString(Key, Value);
         e.commit();
      }
      /**
       * Maps the given key to the given Boolean value.
       */
      public void SetBoolean(String Key, boolean Value) {
         Editor e = sp.edit();
         e.putBoolean(Key, Value);
         e.commit();
      }
      /**
       * Clears all stored entries.
       */
      public void ClearAll() {
         Editor e = sp.edit();
         e.clear();
         e.commit();
      }
   }
   /**
    * 
    */
   @ShortName("PreferenceScreen")
   public static class PreferenceScreenWrapper extends B4APreference{
      
      protected ArrayList<B4APreference> childs;
      protected static int randomKey;
      public PreferenceScreenWrapper() {
         this("PreferenceScreen" + Integer.toString(++randomKey));
      }
      protected PreferenceScreenWrapper(String key) {
         super(key, null, null, null);
      }
      /**
       * Initializes the object and sets the title that will show. The summary will show for secondary PreferenceScreens.
       */
      public void Initialize(String Title, String Summary) {
         childs = new ArrayList<B4APreference>();
         this.title = Title;
         this.summary = Summary;
      }
      /**
       * Creates the Intent object that is required for showing the PreferencesActivity.
       *Example:<code>StartActivity(PreferenceScreen1.CreateIntent)</code>
       */
      public Intent CreateIntent() {
         Intent in = new Intent();
         in.setClass(BA.applicationContext, preferenceactivity.class);
         in.putExtra("preferences", this);
         return in;
      }
      @Override
      Preference createPreference(PreferenceActivity c) {
         PreferenceScreen ps = c.getPreferenceManager().createPreferenceScreen(c);
         handleDefaults(ps);
         for (B4APreference b : childs) {
            if (b instanceof PreferenceCategoryWrapper) {
               ((PreferenceCategoryWrapper)b).parent = ps;
               b.createPreference(c);
            }
            else {
               ps.addPreference(b.createPreference(c));
            }
         }
         return ps;
      }
      /**
       * Adds a preference entry with a check box. The entry values can be either True or False.
       *Key - The preference key associated with the value.
       *Title - Entry title.
       *Summary - Entry summary (second row).
       *DefaultValue - The default value of this preference entry if the key does not already exist.
       */
      public void AddCheckBox(String Key, String Title, String Summary, boolean DefaultValue) {
         childs.add(new B4APreference(Key, Title, Summary, DefaultValue) {
            @Override
            Preference createPreference(PreferenceActivity c) {
               CheckBoxPreference cbp = new CheckBoxPreference(c);
               handleDefaults(cbp);
               return cbp;
            }
         });
      }
      /**
       * Adds a preference entry which allows the user to choose a single item out of a list.
       *Key - The preference key associated with the value.
       *Title - Entry title.
       *Summary - Entry summary (second row).
       *DefaultValue - The default value of this preference entry if the key does not already exist. Should match one of the values.
       *Values - A list of strings with the possible values.
       */
      public void AddList(String Key, String Title, String Summary, String DefaultValue, List Values) {
         final CharSequence[] values = new String[Values.getSize()];
         for (int i = 0;i < values.length;i++) {
            values[i] = String.valueOf(Values.Get(i));
         }
         childs.add(new B4APreference(Key, Title, Summary, DefaultValue) {
            @Override
            Preference createPreference(PreferenceActivity c) {
               ListPreference list = new ListPreference(c);
               handleDefaults(list);
               list.setDialogTitle(title);
               
               list.setEntries(values);
               list.setEntryValues(values);
               return list;
            }
         });
      }
      /**
       * Adds a preference entry which allows the user to enter free text.
       *Key - The preference key associated with the value.
       *Title - Entry title.
       *Summary - Entry summary (second row).
       *DefaultValue - The default value of this preference entry if the key does not already exist.
       */
      public void AddEditText(String Key, final String Title, final String Summary, final String DefaultValue) {
         childs.add(new B4APreference(Key, Title, Summary, DefaultValue) {
            @Override
            Preference createPreference(PreferenceActivity c) {
               EditTextPreference e = new EditTextPreference(c);
               e.setDialogTitle(title);
               handleDefaults(e);
               return e;
            }
         });
      }
      /**
       * Adds a secondary PreferenceScreen. When the user presses on this entry the second screen will appear.
       */
      public void AddPreferenceScreen(PreferenceScreenWrapper PreferenceScreen) {
         childs.add(PreferenceScreen);
      }
      /**
       * Adds a PreferenceCategory. A preference category is made of a title and a group of entries.
       *Note that a PreferenceCategory cannot hold other PreferenceCategories.
       */
      public void AddPreferenceCategory(PreferenceCategoryWrapper PreferenceCategory) {
         childs.add(PreferenceCategory);
      }
   }
   /**
    * PreferenceCategory holds a group of other preferences.
    */
   @ShortName("PreferenceCategory")
   public static class PreferenceCategoryWrapper extends PreferenceScreenWrapper {
      PreferenceGroup parent;
      public PreferenceCategoryWrapper() {
         super("PreferenceCategory" + Integer.toString(++randomKey));
      }
      /**
       * Initializes the object and sets the category title.
       */
      public void Initialize(String Title) {
         childs = new ArrayList<B4APreference>();
         this.title = Title;
      }
      @Override
      Preference createPreference(PreferenceActivity c) {
         PreferenceCategory pc = new PreferenceCategory(c);
         handleDefaults(pc);
         if (parent == null) {
            Common.Log("Error: PreferenceCategories cannot be nested!");
         }
         parent.addPreference(pc);
         for (B4APreference b : childs) {
            pc.addPreference(b.createPreference(c));
         }
         return pc;
      }
      @Override
      @Hide
      public Intent CreateIntent() {
         return null;
      }
   }
   static abstract class B4APreference implements Serializable{
      String key;
      Serializable defaultValue;
      String title, summary;
      public B4APreference(String key, String title, String summary, Serializable defaultValue) {
         this.key = key;
         this.defaultValue = defaultValue;
         this.summary = summary;
         this.title = title;
      }
      abstract Preference createPreference(PreferenceActivity c) ;
      protected void handleDefaults(Preference p) {
         p.setKey(key);
         p.setDefaultValue(defaultValue);
         p.setTitle(title);
         p.setSummary(summary);
      }
   }
}
 

Similar Threads

Replies
49
Views
57K
Replies
175
Views
92K
  • Locked
  • Article
Android Tutorial SQL tutorial
Replies
161
Views
276K
  • Locked
  • Article
Android Tutorial GPS tutorial
Replies
310
Views
253K
Top