preferencefragment no view found for id android - android

I had the getpreferencescreen deprecated so I tryed to implement the header preference activity.
here is my code:
public class EditPreferences extends PreferenceActivity {
ListPreference m_list_preference_dive_centre_rating;
ListPreference m_list_preference_dive_region_rating;
ListPreference m_list_preference_wreck;
ListPreference m_list_preference_cave;
MultyChoiceListPlugin m_list_preference_marine_life;
ListPreference m_list_preference_region;
Preference m_order_by_name;
SharedPreferences.Editor m_editor;
static Context m_context;
int m_order_type_val = 0;
boolean m_wreck_selected = false;
boolean m_cave_selected = false;
boolean m_marine_life_selected = false;
boolean m_region_selected = false;
int number_click_wreck = 0;
int number_click_cave = 0;
int number_click_marine_life = 0;
int number_click_region = 0;
boolean m_without_guide_selected = false;
boolean m_without_equipment_selected = false;
boolean m_budget_selected = false;
boolean m_region_rating = false;
boolean m_centre_rating = false;
private ListView m_preferenceView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//m_order_by_name.setOnPreferenceClickListener(onOrderByNamePrefClick);
final Button back_btn = (Button)this.findViewById(R.id.back);
final Button home_btn = (Button)this.findViewById(R.id.home);
//final Button search_btn = (Button)this.findViewById(R.id.search);
final Button info_btn = (Button)this.findViewById(R.id.info);
back_btn.setOnClickListener(onBackBtn);
home_btn.setOnClickListener(onHomeBtn);
// search_btn.setOnClickListener(onSearchBtn);
info_btn.setOnClickListener(onInfoBtn);
}
/**
* Populate the activity with the top-level headers.
*/
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
public static class Prefs1Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.wrap_preferences);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
//PreferenceManager.setDefaultValues(getActivity(),
// R.layout.wrap_preferences, false);
addPreferencesFromResource(R.xml.preferences1);
}
}
public static class Prefs2Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
//PreferenceManager.setDefaultValues(getActivity(),
// R.xml.preferences, false);
addPreferencesFromResource(R.xml.preferences2);
}
}
public static class Prefs3Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
// PreferenceManager.setDefaultValues(getActivity(),
// R.xml.preferences, false);
addPreferencesFromResource(R.xml.preferences3);
}
}
private View.OnClickListener onBackBtn = new OnClickListener() {
public void onClick(View v) {
//set the view for dive center list ordered by rating
Intent intent_call_back = new Intent();
intent_call_back.putExtra("goback","last_from");
setResult(DivingReview.CALL_BACK,intent_call_back);
finish();
}
};
private View.OnClickListener onHomeBtn = new OnClickListener() {
public void onClick(View v) {
//set the view for dive center list ordered by rating
//set the result to the callback of the parent activitie
Intent intent_call_back = new Intent();
intent_call_back.putExtra("goback","home");
setResult(DivingReview.CALL_BACK,intent_call_back);
finish();
}
};
I've got the error:No view found for id 0x1020343 (android:id/prefs) for fragment
XML code pref_headers.xml:
<?xml version="1.0" encoding="UTF-8"?>
<preference-headers
xmlns:android="http://schemas.android.com/apk/res/android" >
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs1Fragment"
style="#style/pref_style"
android:key="who_is_the_best"
android:title="#string/who_is_the_best_text"
android:summary="#string/who_is_the_best_summary">
</header>
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs2Fragment"
android:title="#string/what_is_your_budget_text"
android:summary="#string/what_is_your_budget_summary" >
</header>
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs3Fragment"
android:title="#string/order_by_name_title"
android:summary="#string/order_by_name_summary">
</header>
<!-- <header
android:icon="#drawable/icon_question"
android:title="Blackmoon Info Tech Services"
android:summary="link to BITS blog">
<intent android:action="android.intent.action.VIEW"
android:data="http://www.blackmoonit.com/2012/07/all_api_prefsactivity/" />
</header>
-->
XML code preferences1.xml:
<?xml version="1.0" encoding="UTF-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/pref_style"
android:key="who_is_the_best"
android:title="#string/who_is_the_best_text"
android:summary="#string/who_is_the_best_summary">
<PreferenceCategory
android:title="#string/who_is_the_best_dive_centre_text"
android:key="who_is_the_best_dive_centre_category">
<ListPreference
android:key="select_dive_centre_rating"
android:title="#string/select_dive_centre_rating_text"
android:summary="#string/select_dive_centre_rating_summary"
android:entries="#array/search_dive_centre_names"
android:entryValues="#array/search_dive_centre_clauses"
android:dialogTitle="#string/search_dive_centre_choice_title"/>
</PreferenceCategory>
</PreferenceScreen>
thanks in advance

The official documentation is misleading:
Removing the onCreate function in public class EditPreferences extends PreferenceActivity resolves the issue.
I just moved what was in onCreate to onBuildHeaders function.

I was having this problem too, until I realized that I had specified the wrong layout in setContentView() of the onCreate() method of the FragmentActivity.
The id passed into FragmentTransaction.add(), in your case R.id.feedContentContainer, must be a child of the layout specified in setContentView().
You didn't show us your onCreate() method, so perhaps this is the same problem.

Related

EditTextPreference value only refreshed after clicking ListPreference second time

I've been struggling with this issue for a while now so I decided to ask here what I' m doing wrong.
First of all:
- I have a PreferenceFragment with a ListPreference on top and an EditTextPreference below
- The ListPreference is filled with Objects, the values are stored in a file and read from there (this works flawlessly)
- The EditTextPreference should display the value of the in the ListPreference chosen object. And that's the problem: after choosing the value nothing changes so I have to click the ListPreference once more and the value is set correctly. Is this a problem with my Listener?
Here's the code:
public class SettingsTestFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
private final String[] pref_key_array = {"pref_key_lp", "pref_key_et""}; // array that contains all the preference keys of changeable values
private final int numberOfEntries = pref_key_array.length;
private Preference[] pref_entries;
String[] entries = {"Value 1", "Value 2", "Value 3"};
String[] entryValues = {"0", "1", "2"};
private int position;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
final SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(getActivity());
final EditTextPreference et = (EditTextPreference) findPreference("pref_key_et");
final ListPreference lp = (ListPreference) findPreference("pref_key_lp");
prepareListPref(lp);
pref_entries = new Preference[numberOfEntries];
for(int i = 0; i < numberOfEntries; i++) {
pref_entries[i] = getPreferenceScreen().findPreference(pref_key_array[i]);
}
lp.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
position = Integer.valueOf(myPreference.getString("pref_key_lp", "0"));
et.setText(entries[position]);
return true;
}
});
Preference.OnPreferenceChangeListener changeListener = new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
position = Integer.valueOf(myPreference.getString("pref_key_lp", "0"));
preference.setSummary(entries[position]);
return true;
}
};
lp.setOnPreferenceChangeListener(changeListener);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updateSummary(key, pref_key_array, numberOfEntries, pref_entries);
}
#Override
public void onResume() {
super.onResume();
// Set up listener when a key changes
for(int i = 0; i < numberOfEntries; i++) {
updateSummary(pref_key_array[i], pref_key_array, numberOfEntries, pref_entries);
}
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
// Unregister listener every time a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public void prepareListPref(ListPreference lp) {
lp.setEntries(entries);
lp.setEntryValues(entryValues);
lp.setDefaultValue("0");
}
public void updateSummary(String key, String[] pref_key_array, int numberOfEntries, Preference[] pref_entries) {
for(int i = 0; i < numberOfEntries; i++) {
if(key.equals(pref_key_array[i])) {
if(pref_entries[i] instanceof EditTextPreference) {
final EditTextPreference currentPreference = (EditTextPreference) pref_entries[i];
pref_entries[i].setSummary(currentPreference.getText());
} else if(pref_entries[i] instanceof ListPreference) {
final ListPreference currentPreference = (ListPreference) pref_entries[i];
pref_entries[i].setSummary(currentPreference.getEntry());
}
break;
}
}
}
}
Summarizing the code for reading from the file and writing the value to the Settings works but only after clicking the ListPreference a second time. Do you have any ideas why?
Thanks
ok, I'm not sure what you are trying to do and what is the problem, so I've made a sample, showing the next thing:
a listPreference that its default value&entry will set the title&summary of an EditTextPreference .
when choosing an item on the ListPreference, it will also update tge title&summary of the EditTextPreference according to the value&entry of the item being selected.
Not sure what to do with the EditTextPreference. This is your choice.
I still think you should consider making a custom Preference class, as you wrote that you intend to use a lot of couples of ListPreference&EditTextPreference.
BTW, code is based on an app that I've made (link here). I've made it so that it will be easy to handle multiple listPreferences easier.
Here's the code:
res/values/strings_activity_settings.xml
<resources>
<string name="pref__custom_app_theme" translatable="false">pref__custom_app_theme</string>
<string name="pref__app_theme" translatable="false">pref__app_theme</string>
<string-array name="pref__app_theme_entries">
<item>#string/cards_light</item>
<item>#string/cards_dark</item>
</string-array>
<string name="pref__app_theme__cards_ui" translatable="false">CARDS_UI</string>
<string name="pref__app_theme__cards_ui_dark" translatable="false">CARDS_UI_DARK</string>
<string name="pref__app_theme_default" translatable="false">#string/pref__app_theme__cards_ui</string>
<string-array name="pref__app_theme_values">
<item>#string/pref__app_theme__cards_ui</item>
<item>#string/pref__app_theme__cards_ui_dark</item>
</string-array>
</resources>
res/values/strings.xml
<resources>
<string name="app_name">My Application</string>
<string name="app_theme">App Theme</string>
<string name="cards_light">cards light</string>
<string name="cards_dark">cards dark</string>
</resources>
res/xml/pref_general.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- theme -->
<ListPreference
android:defaultValue="#string/pref__app_theme_default"
android:entries="#array/pref__app_theme_entries"
android:entryValues="#array/pref__app_theme_values"
android:key="#string/pref__app_theme"
android:title="#string/app_theme"/>
<EditTextPreference android:key="#string/pref__custom_app_theme"/>
</PreferenceScreen>
SettingsActivity.java
public class SettingsActivity extends PreferenceActivity
{
public interface IOnListPreferenceChosenListener
{
public void onChosenPreference(String key,String entry,String value);
}
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
final EditTextPreference editTextPreference=(EditTextPreference)findPreference(getString(R.string.pref__custom_app_theme));
final ListPreference listPreference=prepareListPreference(this,R.string.pref__app_theme,R.array.pref__app_theme_entries,R.array.pref__app_theme_values,R.string.pref__app_theme_default,new IOnListPreferenceChosenListener()
{
#Override
public void onChosenPreference(final String key,final String entry,final String value)
{
editTextPreference.setTitle(value);
editTextPreference.setSummary(entry);
}
});
editTextPreference.setTitle(listPreference.getValue());
editTextPreference.setSummary(listPreference.getEntry());
}
public static ListPreference prepareListPreference(final PreferenceActivity activity,final int prefKeyId,//
final int entriesId,final int valuesId,final int defaultValueId,final IOnListPreferenceChosenListener listener)
{
final String prefKey=activity.getString(prefKeyId);
#SuppressWarnings("deprecation")
final ListPreference pref=(ListPreference)activity.findPreference(prefKey);
final String[] entries=activity.getResources().getStringArray(entriesId);
final String[] values=activity.getResources().getStringArray(valuesId);
final String defaultValue=activity.getResources().getString(defaultValueId);
final String currentValue=PreferenceManager.getDefaultSharedPreferences(activity).getString(prefKey,defaultValue);
for(int i=0;i<values.length;++i)
{
final String value=values[i];
if(TextUtils.equals(currentValue,value))
{
pref.setSummary(entries[i]);
pref.setValueIndex(i);
break;
}
}
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
#Override
public boolean onPreferenceChange(final Preference preference,final Object newValue)
{
final String newValueStr=newValue.toString();
String entryChosen=null;
for(int i=0;i<values.length;++i)
{
final String value=values[i];
if(TextUtils.equals(newValueStr,value))
{
entryChosen=entries[i];
break;
}
}
pref.setSummary(entryChosen);
if(listener!=null)
listener.onChosenPreference(prefKey,entryChosen,newValueStr);
return true;
}
});
return pref;
}
}

Android - SharedPreferences ListPreference - PreferenceFragment onCreate not called

Ok, I know there have been a lot of questions about SharedPreferences in Android asked before, and I did manage to get quite far, but since I'm kinda new to SharedPreferences I don't know the last few steps to get it to work.
In my MainActivity I have the following:
public class MainActivity extends ActionBarActivity
{
...
// Public static MainActivity so we can use findViewById from MyPrefsActivity
public static MainActivity mActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mActivity = this;
}
...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(id){
case R.id.action_settings:
startActivity(new Intent(this, MyPrefsActivity.class));
return true;
}
return false;
}
}
And this is MyPrefsActivity.java:
package com.example.checkboxoptionsv2;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ImageButton;
public class MyPrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
private static int prefs = R.xml.settings;
private ImageButton cbButton, spinnerButton, popupButton;
private final String LIST_PREFERENCE = "prefCheckboxOption";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
getClass().getMethod("getFragmentManager");
AddResourceApi11AndGreater();
}
catch(NoSuchMethodException e){ // Android API < 11
AddResourceApiLessThan11();
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.registerOnSharedPreferenceChangeListener(this);
* ListPreference listPreference = (ListPreference) findPreference(LIST_PREFERENCE);
if(listPreference.getValue() == null)
listPreference.setValue("0");
cbButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnCheckbox);
spinnerButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnSpinner);
popupButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnPopup);
setChosenPreference(0);
}
private void setChosenPreference(int chosen_value){
// First put all Visibilities on GONE
cbButton.setVisibility(View.GONE);
spinnerButton.setVisibility(View.GONE);
popupButton.setVisibility(View.GONE);
// Then turn the chosen on VISIBLE again
switch(chosen_value){
case 0: // Multi-Click CheckBox
default:
cbButton.setVisibility(View.VISIBLE);
break;
case 1: // Dropdown CheckBox
spinnerButton.setVisibility(View.VISIBLE);
break;
case 2: // Pop-up CheckBox
popupButton.setVisibility(View.VISIBLE);
break;
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(LIST_PREFERENCE)){
ListPreference listPreference = (ListPreference) findPreference(key); // LIST_PREFERENCE
listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int chosen_option = Integer.valueOf((String) newValue);
setChosenPreference(chosen_option);
return false;
}
});
}
else{
// Other settings
}
}
#SuppressWarnings("deprecation")
protected void AddResourceApiLessThan11(){
addPreferencesFromResource(prefs);
}
#TargetApi(11)
protected void AddResourceApi11AndGreater(){
* MyPreferenceFragment pf = new MyPreferenceFragment();
getFragmentManager().beginTransaction().replace(android.R.id.content, pf).commit();
}
#TargetApi(11)
public static class MyPreferenceFragment extends PreferenceFragment{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
* addPreferencesFromResource(MyPrefsActivity.prefs); // outer class
// private members seem to be visible for inner class, and
// making it static made things so much easier
}
}
}
And the settings.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="#string/checkbox_options_title" >
<ListPreference
android:key="prefCheckboxOption"
android:title="#string/pref_checkbox_option"
android:summary="#string/checkbox_options_summary"
android:entries="#array/checkbox_options"
android:entryValues="#array/checkbox_option_values" />
</PreferenceCategory>
</PreferenceScreen>
and arrays.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="checkbox_options">
<item>CheckBox as Multi-Click</item>
<item>CheckBox as Dropdown</item>
<item>CheckBox as Pop-up</item>
</string-array>
<string-array name="checkbox_option_values">
<item>0</item>
<item>1</item>
<item>2</item>
</string-array>
</resources>
(Of course I've also included the MyPrefsActivity in the AndroidManifest.xml)
My goal is to make one of the three checkbox-option (found in the setChosenPreference method) VISIBLE, and the other two GONE, based on the preference selected in the ListPreference.
Right now the Listpreference in both the onCreate() method and onSharedPreferenceChanged() is null and giving a NullPointerException. So I set some breakpoints (see the three " * ") and the reason they are null is because the third " * " (in the static class PF) isn't called.
The addPreferencesFromResources should be called before using findPreference, otherwise it will return null. Does anyone know why during debugging I do get to the second " * " in the AddResourceApi11AndGreater() method, but I'm not getting to the third one in the MyPreferenceFragment-class onCreate method() ?.. the onCreate isn't called at all..
Also, does the rest of my code seems ok(-ish) or should I change something in order to make it work as I intended?
Thanks in advance for the responses.
TL;DR: MyPreferenceFragment instantion is created successfully, but it's #Override onCreate method is never called.
EDIT 1: Ok, I did found the problem: When I added addPreferencesFromResource(prefs) in the activity's onCreate method as a debug-test, I found out that the MyPreferenceFragment-class is indeed being initialized, then it finishes the activity's onCreate method (which would have failed at findPreference() if I didn't added the addPreferencesFromResource(prefs) test-line), and only after the activity's onCreate method is completely finished, it goes to the MyPreferenceFragment's onCreate method.
Is there a way to let the PreferenceFrament's onCreate method go first, while in the middle of the activity's onCreate method, so after AddResourceApi11AndGreater() but before findPreference(LIST_PREFERENCE)?
Move your logic to PF, don't do things in PreferenceActivity.
There are also changes in the way of listening to the preferences changes. Check the code.
public class MyPrefsActivity extends PreferenceActivity {
private static int prefs = R.xml.settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
getClass().getMethod("getFragmentManager");
AddResourceApi11AndGreater();
}
catch(NoSuchMethodException e){ // Android API < 11
AddResourceApiLessThan11();
}
}
#SuppressWarnings("deprecation")
protected void AddResourceApiLessThan11(){
addPreferencesFromResource(prefs);
}
#TargetApi(11)
protected void AddResourceApi11AndGreater(){
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PF()).commit();
}
#TargetApi(11)
public static class PF extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
private ImageButton cbButton, spinnerButton, popupButton;
private final String LIST_PREFERENCE = "prefCheckboxOption";
#Override
public void onCreate(final Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(MyPrefsActivity.prefs); // outer class
// private members seem to be visible for inner class, and
// making it static made things so much easier
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
preferences.registerOnSharedPreferenceChangeListener(this);
ListPreference listPreference = (ListPreference) findPreference(LIST_PREFERENCE);
if(listPreference.getValue() == null)
listPreference.setValue("0");
cbButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnCheckbox);
spinnerButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnSpinner);
popupButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnPopup);
setChosenPreference(Integer.valueOf(preferences.getString(LIST_PREFERENCE, "0")));
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
int chosen_option = Integer.valueOf(sharedPreferences.getString(key, "0"));
setChosenPreference(chosen_option);
}
private void setChosenPreference(int chosen_value){
// First put all Visibilities on GONE
cbButton.setVisibility(View.GONE);
spinnerButton.setVisibility(View.GONE);
popupButton.setVisibility(View.GONE);
// Then turn the chosen on VISIBLE again
switch(chosen_value){
case 0: // Multi-Click CheckBox
default:
cbButton.setVisibility(View.VISIBLE);
break;
case 1: // Dropdown CheckBox
spinnerButton.setVisibility(View.VISIBLE);
break;
case 2: // Pop-up CheckBox
popupButton.setVisibility(View.VISIBLE);
break;
}
}
}
}

Android can't figure out why perference screen won't show preference textbox

I'm trying to display preference screen and with a text box and doesn't show but in another screen it has no problem? It shows a negative 1 or null.
StatsActivity
public class StatsActivity extends Activity {
static final String TAG = "StatsActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats_settings_layout);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
StringBuilder builder = new StringBuilder();
builder.append("\n" + sharedPrefs.getString("time_usage_key", "-1"));
TextView settingsTextViewStats = (TextView) findViewById(R.id.stats_settings_text_view);
settingsTextViewStats.setText(builder.toString());
}
}
StatsPrefsActivity
public class StatsPrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener{
static final String TAG = "StatsPrefsActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_stats);
PreferenceManager.setDefaultValues(this,R.xml.preferences_stats, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menu.add(Menu.NONE, 0, 0, "Show current settings");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
startActivity(new Intent(this, StatsActivity.class));
return true;
}
return false;
}
#Override
public void onStart(){
super.onStart();
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(StatsPrefsActivity.this);
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences s = getSharedPreferences("MY_PREFS", 0);
// Create a editor to edit the preferences:
SharedPreferences.Editor editor = s.edit();
}
}
preference_stats.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Settings"
android:key="first_category">
<EditTextPreference
android:id="#+id/text_pref_box"
android:key="time_usage_key"
android:title="7 Day Usage"
android:summary="A total of usage of 7 days." />
</PreferenceCategory>
</PreferenceScreen>
if you want an inital value then set one. right now you have "-1" set as the default value. so if the preference has never been used before your going to get "-1" as the default. Try changing that to a blank string "" or something if you want better presentation.

Android Preference Activity, show edittext dialog when tap listview item

How to make a preference activity where contain listpreference, where the summary will change based on selected listpreference item, and when certain list item is taped, it will show a edit text dialog which it will also become the the summary string value.
Thank in advance.
as requested, here my current code
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/pref_category_general"
android:key="pref_category_general">
<CheckBoxPreference
android:key="pref_debug_mode"
android:title="#string/pref_debug_mode"
android:summary="#string/pref_debug_mode_summary"
android:defaultValue="false" />
<ListPreference
android:dependency="pref_debug_mode"
android:key="pref_remotehost"
android:title="#string/pref_remotehost"
android:dialogTitle="#string/pref_remotehost_dialog_title"
android:entries="#array/pref_remotehost_entries"
android:entryValues="#array/pref_remotehost_entries_values"
android:defaultValue="#string/pref_remotehost_default" />
</PreferenceCategory>
</PreferenceScreen>
and my activity
public class SettingActivity extends SherlockPreferenceActivity implements View.OnClickListener {
private MainApplication G;
private SherlockPreferenceActivity me;
private Intent intent;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
this.G = ((MainApplication) getApplicationContext());
assert this.G != null;
super.onCreate(bundle);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// Add a button to the header list.
if (hasHeaders()) {
Button button = new Button(this);
button.setText("Some action");
setListFooter(button);
button.setOnClickListener(this);
}
PreferenceFragment prefFragment = new PreferenceGeneralFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, prefFragment);
fragmentTransaction.commit();
this.intent = getIntent();
this.me = this;
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onClick(View v) {
/*
switch (element.getId()) {
default:
return;
case R.id.setting_cancel_config:
onBackPressed();
return;
case R.id.setting_save_config:
int i = this.modeSpinner.getSelectedItemPosition();
boolean flag = true;
if (i == 1) {
flag = false;
};
MainApplication.setDeveloperMode(flag);
MainApplication.setRemoteHost(this.remoteHostEdittext.getText().toString());
SettingActivity.this.finish();
onBackPressed();
return;
}
*/
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
/**
* This fragment shows the preferences for the first header.
*/
public static class PreferenceGeneralFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
//PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences_general, false);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences_general);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updatePrefSummary(findPreference(key));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
}
}
i don't know where to start

How to get child Activity View in Parent Activity Class(Android)?

I implemented a bottom button bar(something like a tab bar controller in iPhone). For this I created a common layout (button_bar.xml, 5 image buttons) and included in other activity xml files. and for the managing the click action I created a BaseActivity.java extended from Activity and perform the click actions. and I extend other activity which need button bar from this BaseActivity, which works fine. Now I want to include a selected state to these buttons, but when I access the buttons in base activity it give a null pointer error. How can I solve this.
button_bar.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/bottomButtonBar"
style="#android:style/ButtonBar"
... >
<ImageButton
android:id="#+id/btnGuests"
android:onClick="showAllGuests"
android:src="#drawable/ic_guest_list" />
<ImageButton
android:id="#+id/btnAddGuest"
android:onClick="selectGuestType"
android:src="#drawable/ic_add_guest" />
<ImageButton
android:id="#+id/btnAddParty"
android:onClick="showAddParty"
android:src="#drawable/ic_add_party" />
....
</LinearLayout>
public class BaseActivity extends Activity {
// common to other activities.
public void showAddParty(View view) {
//showAddParty is one one of the buttons click method. 4 more buttons are there
Intent intent = new Intent(this, AddPartyActivity.class);
startActivity(intent);
// I can get "view.findViewById(R.id.btnAddParty)" here
// but I can't get "findViewById(R.id.btnAddGuest)" here. how this possible
}
}
public class AddPartyActivity extends BaseActivity{
....
}
Here i can get the corresponding view from parameter view, and change backgroundIbageSource. but when it goes to "AddPartyActivity" that inherited from Baseactivity, the new image is replaced by old one. How can I implement the selected feature in BaseActivity itself?
you can hold the state of the Button(clicked or not) using booloean in BaseActivity and check the value of these variables in AddPropertyActivity's onCreate() method.
public class BaseActivity extends Activity {
protected static boolean isButton1Clicked = false;
protected static boolean isButton2Clicked = false;
protected static boolean isButton3Clicked = false;
protected static boolean isButton4Clicked = false;
.....
public void showAddParty(View view) {
isButton1Clicked = true;
//showAddParty is one one of the buttons click method. 4 more buttons are there
Intent intent = new Intent(this, AddPartyActivity.class);
startActivity(intent);
}
}
public class AddPartyActivity extends BaseActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
Button button1 = (Button)findViewById(R.id.button1);
if(isButton1Clicked) {
button1.setBackground(R.drawable.clicked);
} else {
button1.setBackground(R.drawable.not_clicked);
}
......
......
}
}
and remember that all boolean variables must be static variables. (every object will have it's own copy of instance variables but all objects will share a single copy of static members).
public class BaseActivity extends Activity {
protected static boolean isButton1Clicked = false;
protected static boolean isButton2Clicked = false;
protected static boolean isButton3Clicked = false;
protected static boolean isButton4Clicked = false;
protected Button button1;
protected Button button2;
protected Button button3;
protected Button button4;
protected void checkButtonsState() {
if (isButton1Clicked) {
button1.setBackgroundResource(R.drawable.image1);
} else {
button1.setBackgroundResource(R.drawable.image2);
}
..........
}
public void showAddParty(View view) {
isButton1Clicked = true;
// showAddParty is one one of the buttons click method. 4 more
// buttons are there
Intent intent = new Intent(this, AddPartyActivity.class);
startActivity(intent);
}
}
public class AddPartyActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button);
button2 = (Button) findViewById(R.id.item1);
.....
checkButtonsState();
}
}
Your error come from because you are using view.findViewById(), but the view variable correspond of the object that catch the click event (look in your xml, the 'android:onClick="showAddParty"').
So, you have in parameter a view instance that point directly to the btnAddParty button.
Is why you can access with findViewById to btnAddParty id but not btnAddGuest id.
You can access to all the view hierarchy by using direct findViewById as method of the activity class:
View btAddParty = findViewById(R.id.btnAddParty)
View btAddGuest = view.findViewById(R.id.btnAddGuest)
Now, you can have a full solution, by implement a special method (setMyInternalContent in the sample below) in the BaseActivity and keep an instance of each button, after, you just have to update there state on click action:
public class BaseActivity extends Activity {
protected Button mBtAddParty;
protected Button mBtAddGuest;
// ...
protected void setMyContentView(int resId) {
setContentView(resId);
mBtAddParty = (Button)findViewById(R.id.btnAddParty);
mBtAddParty = (Button)findViewById(R.id.btnAddGuest);
// ...
}
public void showAddParty(View view) {
mBtAddParty.setClickable(true);
mBtAddGuest.setClickable(false);
// ...
//showAddParty is one one of the buttons click method. 4 more buttons are there
Intent intent = new Intent(this, AddPartyActivity.class);
startActivity(intent);
}
}
public class AddPartyActivity extends BaseActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setMyContentView(R.layout.activity_layout);
// Do not forget to set initial button state:
mBtAddParty.setClickable(true);
mBtAddGuest.setClickable(false);
// ...
}
}

Categories

Resources