How to create setting for my app - android

I'm working on an app that let users turn on/off some specific features like Wi-fi, Bluetooth and so on. But i can't seem to get it right, the switch button on the preference screen is not responding to my Settings java codes. Here's what i've tried
SettingsFragment.java
import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class SettingsFragment extends PreferenceFragment implements SharedPreferences
.OnSharedPreferenceChangeListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Loads the XML preferences file.
addPreferencesFromResource(R.xml.preferences);
}
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if(key.equals(getString(R.string.wifi))){
WifiManager wifiManager = (WifiManager)getActivity().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
}
}
preference.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Battery Saver Mode">
<SwitchPreference
android:defaultValue="true"
android:key="battery_tone"
android:title="#string/pref_title_new_message_notifications"/>
<SwitchPreference
android:defaultValue="true"
android:title="#string/pref_bluetooth"
android:key="#string/bluetooth"/>
<SwitchPreference
android:defaultValue="true"
android:title="#string/pref_mobile_data"
android:key="mobile_data"/>
<SwitchPreference
android:defaultValue="true"
android:title="#string/pref_vibrate"
android:key="vibrate"/>
<SwitchPreference
android:defaultValue="true"
android:title="#string/pref_sync"
android:key="sync"/>
<SwitchPreference
android:defaultValue="true"
android:title="#string/pref_wifi"
android:key="#string/wifi"/>
<SwitchPreference
android:defaultValue="true"
android:title="#string/pref_airplane_mode"
android:key="airmode"/>
</PreferenceCategory>
</PreferenceScreen>

Related

Preference Menu on 10 inch tablet

I am trying to figure out why the layout of my Preference menu is displayed in a false way on 10' tablets when using it in landscape mode. It looks like the lines that are to the right of the Checkboxes are actually to the left of them. You can see this here http://imageshack.us/photo/my-images/109/schnappschuss2013052109.png/
On 7' tablets, everything works like expected to do.
My menu looks like that:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:title="#string/pref_message"
android:key="pref_key_message_settings">
<CheckBoxPreference
android:key="pref_key_add_timestamp"
android:summary="#string/pref_summary_addTimestamp"
android:title="#string/pref_addTimestamp"
android:defaultValue="true"/>
<ListPreference
android:dependency="pref_key_add_timestamp"
android:summary="#string/pref_summary_timestamp_option"
android:key="pref_key_timestamp_option"
android:title="#string/pref_timestampOption"
android:dialogTitle="#string/pref_timestampOptionDialog"
android:entries="#array/pref_timestampArray"
android:entryValues="#array/pref_timestampValues"
android:defaultValue="Time" />
<CheckBoxPreference
android:key="pref_key_add_newline"
android:summary="#string/pref_summary_addNewLine"
android:title="#string/pref_addNewLine"
android:defaultValue="true"/>
<ListPreference
android:dependency="pref_key_add_newline"
android:key="pref_key_newline_option"
android:summary="#string/pref_summary_newline_option"
android:title="#string/pref_newLineOption"
android:dialogTitle="#string/pref_newLineOptionDialog"
android:entries="#array/pref_newLineArray"
android:entryValues="#array/pref_newLineValues"
android:defaultValue="LF" />
<CheckBoxPreference
android:key="pref_key_clear_text"
android:summary="#string/pref_summary_clearText"
android:title="#string/pref_clearText"
android:defaultValue="false"/>
</PreferenceCategory>
<PreferenceCategory
android:title="#string/pref_storage"
android:key="pref_key_storage_settings">
<EditTextPreference
android:key="pref_key_change_name"
android:summary="#string/pref_summary_editFilename"
android:title="#string/pref_editFilename"
android:defaultValue="history"/>
<CheckBoxPreference
android:key="pref_key_add_date"
android:summary="#string/pref_summary_addDate"
android:title="#string/pref_addDate"
android:defaultValue="true"/>
<CheckBoxPreference
android:key="pref_key_add_time"
android:summary="#string/pref_summary_addTime"
android:title="#string/pref_addTime"
android:defaultValue="true"/>
<at.rtcmanager.ConfirmPreference
android:key="pref_key_clear_history"
android:summary="#string/pref_summary_clearHistory"
android:title="#string/pref_clearHistory"/>
</PreferenceCategory>
<PreferenceCategory
android:title="#string/pref_time"
android:key="pref_key_time_settings">
<CheckBoxPreference
android:key="pref_key_autosend_time"
android:summary="#string/pref_summary_austosendTime"
android:title="#string/pref_autosendTime"
android:defaultValue="false"/>
<ListPreference
android:key="pref_key_mode_sentTime"
android:title="#string/pref_mode_sentTime"
android:summary="#string/pref_summary_mode_sentTime"
android:dialogTitle="#string/pref_modeSentTimeDialog"
android:entries="#array/pref_sentTimeModeArray"
android:entryValues="#array/pref_sentTimeValues"
android:defaultValue="10Byte" />
</PreferenceCategory>
<PreferenceCategory
android:title="#string/pref_about"
android:key="pref_key_settings_about">
<Preference android:title="#string/prefs_about_app" >
<intent android:action="AboutActivity"/>
</Preference>
</PreferenceCategory>
</PreferenceScreen>
and is loded with:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsMenuFragment())
.commit();
}
public static class SettingsMenuFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.app_prefs);
}
}
I had the same problem. My solution is to extend SettingsActivity from usual Activity, not from PreferenceActivity. But SettingsFragment should extend PreferenceFragment of course. It helped me, hope this solves your issue too.

How to use Checkboxes for PreferenceActivity class in android

I have MenuSettings in which I have PreferenceActivity class. In PreferenceActivity I have displayed checkboxPreference like below.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:title="Options">
<CheckBoxPreference
android:key="pref_opt1"
android:title="Option 1"
android:summary="Tick to set this option"
android:defaultValue="true"
/>
<CheckBoxPreference
android:key="pref_opt2"
android:title="Option 2"
android:summary="Tick to set this option"
android:defaultValue="true"
/>
</PreferenceCategory>
</PreferenceScreen>
I want to use checkboxes to perform function for synchronization that I have build, But Please can any body let me know how to use checkboxes in PreferenceActivity. Is there any need to create another Activity? or we can perform function in same PreferenceActivity?
here is my PreferenceActivity:
public class SharedPref extends PreferenceActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.sharedpref);
}
// StorePreference method{
}
// readPreferences method{
}
}

Android + Preferences

I have a preferences.xml and Settings.java... In the onCreate method I want to set the summary of the preferences... Could someone guide me what is the best way to do it???
What I know is that one way of doing is
activityName_text = (EditTextPreference) findPreference("activityName");
activityName_text.setSummary(activityName_text.getText());
but for each key if I follow the above pattern I feel that the code will be bad...
Preferences.xml:
<PreferenceScreen android:title="Header" >
<EditTextPreference
android:defaultValue="TestRequest"
android:key="activityName"
android:title="activityName" />
<EditTextPreference
android:defaultValue="Request"
android:key="msgName"
android:title="msgName" />
<ListPreference
android:defaultValue="0"
android:entries="#array/msg_type"
android:entryValues="#array/msg_type_values"
android:key="msgType"
android:title="msgType" />
<EditTextPreference
android:defaultValue="AA"
android:key="senderURI"
android:title="senderURI" />
<EditTextPreference
android:defaultValue="BB"
android:key="destinationURI"
android:title="destinationURI" />
<EditTextPreference
android:defaultValue="AA"
android:key="replyToURI"
android:title="replyToURI" />
<EditTextPreference
android:defaultValue="BB"
android:key="originatorURI"
android:title="originatorURI" />
<EditTextPreference
android:defaultValue="FF"
android:key="failureReplytoURI"
android:title="failureReplytoURI" />
<EditTextPreference
android:defaultValue="AA"
android:key="correlationId"
android:title="correlationId" />
<EditTextPreference
android:defaultValue="HH"
android:key="security"
android:title="security" />
<EditTextPreference
android:defaultValue="GG"
android:key="securityType"
android:title="securityType" />
<EditTextPreference
android:defaultValue="HH"
android:key="priority"
android:title="priority" />
<ListPreference
android:defaultValue="0"
android:entries="#array/communicationPattern"
android:entryValues="#array/communicationPatternValues"
android:key="communicationPattern"
android:title="communicationPattern" />
<ListPreference
android:defaultValue="0"
android:entries="#array/communicationStyle"
android:entryValues="#array/communicationStyleValues"
android:key="communicationStyle"
android:title="communicationStyle" />
<EditTextPreference
android:defaultValue="100"
android:digits="0123456789"
android:key="requestedBatchSize"
android:title="requestedBatchSize" />
<!-- radhika-number format -->
<EditTextPreference
android:defaultValue="78"
android:digits="0123456789"
android:key="batchSequenceNumber"
android:title="batchSequenceNumber" />
<ListPreference
android:defaultValue="0"
android:entries="#array/batchSequenceEndOfReply"
android:entryValues="#array/batchSequenceEndOfReplyValues"
android:key="batchSequenceEndOfReply"
android:title="batchSequenceEndOfReply" />
<EditTextPreference
android:defaultValue="HH"
android:key="iteratorReferenceURI"
android:title="iteratorReferenceURI" />
<EditTextPreference
android:defaultValue="KK"
android:key="fileLocationURI"
android:title="fileLocationURI" />
<EditTextPreference
android:defaultValue="10/10/2010"
android:key="timestamp"
android:title="timestamp" />
<EditTextPreference
android:defaultValue="kkk"
android:key="vendorExtensions"
android:title="vendorExtensions" />
<PreferenceCategory
android:key="activityStatus"
android:title="activityStatus" >
<ListPreference
android:defaultValue="0"
android:entries="#array/activityStatusType"
android:entryValues="#array/activityStatusTypeValues"
android:key="actStatus"
android:title="activityStatus" />
<EditTextPreference
android:defaultValue="AA"
android:key="qualifier"
android:title="qualifier" />
</PreferenceCategory>
<PreferenceCategory
android:key="msgSpecificProperties"
android:title="msgSpecificProperties" >
<EditTextPreference
android:defaultValue="multiple values"
android:key="propName"
android:title="propName" />
<EditTextPreference
android:defaultValue="multiple values"
android:key="propValue"
android:title="propValue" />
</PreferenceCategory>
<PreferenceCategory
android:key="compressionType"
android:title="compressionType" >
<EditTextPreference
android:defaultValue="kkk"
android:key="compressionTypeAttr"
android:title="extension" />
<ListPreference
android:defaultValue="0"
android:entries="#array/compressionType"
android:entryValues="#array/compressionTypeValues"
android:key="compressionTypeValue"
android:title="value" />
</PreferenceCategory>
<PreferenceCategory
android:key="packingType"
android:title="packingType" >
<EditTextPreference
android:defaultValue="kkk"
android:key="packingTypeAttr"
android:title="extension" />
<ListPreference
android:defaultValue="0"
android:entries="#array/packingType"
android:entryValues="#array/packingTypeValues"
android:key="packingTypeValue"
android:title="value" />
</PreferenceCategory>
</PreferenceScreen>
<PreferenceScreen android:title="Body" >
<PreferenceScreen android:title="Managed Elements" >
<PreferenceCategory
android:key="mdOrMlsnRef"
android:title="md Or Mlsn Ref" >
<EditTextPreference
android:defaultValue="Name"
android:key="rdnName"
android:title="rdnName" />
<EditTextPreference
android:defaultValue="Value"
android:key="rdnValue"
android:title="rdnValue" />
</PreferenceCategory>
</PreferenceScreen>
<PreferenceScreen android:title="Active Alarms" >
</PreferenceScreen>
</PreferenceScreen>
</PreferenceScreen>
Settings.java:
package com.example.settingstest;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
public class Settings extends PreferenceActivity implements OnSharedPreferenceChangeListener {
EditTextPreference activityName_text;
EditTextPreference msgName_text;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference p = findPreference(key);
if(p instanceof EditTextPreference)
{
p.setSummary(sharedPreferences.getString(key, (String)p.getSummary()));
}
else if(p instanceof ListPreference)
{
p.setSummary((String)((ListPreference) p).getEntry());
}
}
}
Use like this its always better to set summary from prefrence.xml, I am giving one example I am using this code and its working perfectly
<PreferenceCategory
android:key="dbh_social"
android:title="We know you are social" >
<Preference
android:key="dbh_invite"
android:summary="Invite your friends"
android:title="Invite Facebook Friends" />
<Preference
android:key="dbh_wall_post"
android:summary="Post about us on your Facebook wall "
android:title="Post on Facebook Wall" />
</PreferenceCategory>
You can put all your keys into a string-array resource and iterate over it on onCreate()
final String[] keys = getResources().getStringArray(R.array.keys) ; // all your keys here
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
for (int i = 0; i < keys.length; i++) {
setPreferenceSummary(p, keys[i]);
}
private void setPreferenceSummary(SharedPreferences sharedPreferences, String key) {
final Preference p = findPreference(key);
if(p instanceof EditTextPreference)
{
p.setSummary(sharedPreferences.getString(key, (String)p.getSummary()));
}
else if(p instanceof ListPreference)
{
p.setSummary((String)((ListPreference) p).getEntry());
}
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
setPreferenceSummary(sharedPreferences, key);
}

Preference items being automatically re-set?

This appears like a bug to me: When you load many switch preferences in a preference fragment, they somehow re-set themselves , when you scroll the preferences. I have separately tested this with little demo code:
/res/xml/prefs.xml (Just a bunch of switch preferences, just enough to make preferences scroll on screen) :
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:key="my_prefs">
<PreferenceCategory android:key="my_prefs_cat" android:title="Settings">
<SwitchPreference android:key="p1" android:title="p1" android:defaultValue="false" />
<SwitchPreference android:key="p2" android:title="p2" android:defaultValue="false" />
<SwitchPreference android:key="p3" android:title="p3" android:defaultValue="false" />
<SwitchPreference android:key="p4" android:title="p4" android:defaultValue="false" />
<SwitchPreference android:key="p5" android:title="p5" android:defaultValue="false" />
<SwitchPreference android:key="p6" android:title="p6" android:defaultValue="false" />
<SwitchPreference android:key="p7" android:title="p7" android:defaultValue="false" />
<SwitchPreference android:key="p8" android:title="p8" android:defaultValue="false" />
<SwitchPreference android:key="p9" android:title="p9" android:defaultValue="false" />
<SwitchPreference android:key="p10" android:title="p10" android:defaultValue="false" />
</PreferenceCategory>
</PreferenceScreen>
/src/Prefs.java (A simple PreferenceFragment) :
package com.example.preflistbug;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class Prefs extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
/res/layout/main.xml (Placed PreferenceFragment in Activity layout) :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment android:name="com.example.preflistbug.Prefs"
android:id="#+id/frg_prefs"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
/src/MyActivity.java (Demo Activity) :
package com.example.preflistbug;
import android.app.Activity;
import android.os.Bundle;
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Problem: If you change the first switch preference , scroll down, scroll back up, the switch is reset. Same is true for other switch preferences which scroll out of view and are visited later. (specially, in horizontal orientation)
Happens on emulator too. I'm compiling on platform version 15, ICS. As you can see in above code, this is a very simple setup, I can't find anything in this code, that might explain why this is happening.
Update
Bug reported as Issue 26194.
Update 2
It is supposed to be fixed in android L release.
I was able to reproduce this issue. I also found a workaround but I don't know why it works :)
Create a derived class from SwitchPreference like so:
public class Pref extends SwitchPreference {
public Pref(Context context) {
super(context);
}
public Pref(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Pref(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
Then, instead of using these in your prefs.xml:
<SwitchPreference ... />
You can use these instead
<com.example.preflistbug.Pref ... />
The derivation seems to somehow fixes the issue where the view recycling in the ListView-driven preference list is reusing the controls without "freeing" them from their previous Preference object first (or so I think). I'll update this answer if I figure out more.

Android - Placing a ListView in Preferences Page

I have a preferences page in my application. As there is no Multiple Choice ListPreference (There's one after API Level 11) I want to put a ListView at preferences page. But the preferences.xml doesn't let me to insert a Linear Layout.
Here's my preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Auto Refresh Settings">
<CheckBoxPreference
android:title="Auto Refresh"
android:defaultValue="false"
android:summary="Enable / Disable Auto Refresh"
android:key="checkboxPref" />
<ListPreference
android:title="Auto Refresh Frequency"
android:summary="Select the frequency of Auto Refresh"
android:key="listPref"
android:defaultValue="20"
android:entries="#array/listArray"
android:entryValues="#array/listValues" />
</PreferenceCategory>
</PreferenceScreen>
This is how it looks:
What I want:
:
Lastly my Settings.java (preferences):
package com.sarkolata.coding;
import android.content.Context;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import android.widget.Toast;
public class Settings extends PreferenceActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
final Preference ListPref = (Preference) findPreference("listPref");
final Preference CheckPref = (Preference) findPreference("checkboxPref");
if(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getBoolean("checkboxPref", false)) {
ListPref.setEnabled(false);
}
ListPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
Main.update_tick = Integer.parseInt(newValue.toString()) * 1000;
return true;
}
});
CheckPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue.toString() == "true")
{
ListPref.setEnabled(false);
} else {
ListPref.setEnabled(true);
}
if(newValue.toString() == "true") {
Main.refreshAllServers(Main.context, Main.bcontext,"start");
} else {
Main.refreshAllServers(Main.context, Main.bcontext,"stop");
}
return true;
}
});
}
}
I don't know if is is clever to add a ListView inside a preference pane because the PreferenceActivity already uses a ListView to show the many preferences. Perhaps you want to use a MultiSelectListPreference, preference that allows you to do multiple selection. You can see an example at http://blog.350nice.com/wp/archives/240

Categories

Resources