How To Get Reference of EditTextPreference in my MainActivity? - java

I am trying to take the value from my edittextpreference and change the font size of the textviews in my mainActivity layout. Please help me with this guys.I must be doing some silly mistake.Help would be appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(this);
String str=sp.getString("editTextPref","50");
if(sp!=null)
{
Toast.makeText(this,"String value is "+str,Toast.LENGTH_LONG).show();
txt=(TextView) findViewById(R.id.textView);
txt.setTextSize(Float.parseFloat(str));
}
Toast.makeText(this,"String value is :"+str,Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int items=item.getItemId();
switch(items)
{
case R.id.setting:
Toast.makeText(this,"Settings Clicked",Toast.LENGTH_LONG).show();
finish();
Intent i=new Intent(this,Prefs.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
}
Prefs.java
public class Prefs extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
SharedPreferences sp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
// show the current value in the settings screen
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updatePreference(findPreference(key));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory cat = (PreferenceCategory) p;
for (int i = 0; i < cat.getPreferenceCount(); i++) {
initSummary(cat.getPreference(i));
}
} else {
updatePreference(p);
}
}
private void updatePreference(Preference p)
{
if(p instanceof EditTextPreference)
{
EditTextPreference editTextPreference=(EditTextPreference) p;
p.setSummary(editTextPreference.getText());
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
startActivity(new Intent(Prefs.this,MainActivity.class));
Toast.makeText(this,"Pref activity finished",Toast.LENGTH_LONG).show();
}
}
Prefs.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:enabled="false"
android:key="settingCategory"
android:title="Settings"
>
</PreferenceCategory>
<EditTextPreference
android:id="#+id/editTextPref"
android:dialogMessage="I am Dialog Message"
android:dialogTitle="Dialog Title"
android:hint="e.g 25"
android:icon="#mipmap/ic_launcher"
android:key="fontSize"
android:padding="5dp"
android:selectAllOnFocus="true"
android:singleLine="true"
android:summary="Changes Font Size of Overall App"
android:title="Change Font Size" />
</PreferenceScreen>

You should be reading value for key fontSize not the name of id field of EditTextPreference. Change your code in your MainActivity like this:
SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(this);
String str=sp.getString("fontSize","50");

Related

Changing to Night mode duplicates items in recycler view

In my app i have a settings activity to change app to dark mode with SwitchPreference and when there is change in preference app move to MainActivity - parent activity and the MainActivity recyclerView item are duplicated.
SettingsActivity
public class SettingsActivity extends AppCompatActivity {
// same as defined in preference.xml file.
public static final String TAG = "Debug";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
SwitchPreference switchPreferenceCompat = findPreference(getString(R.string.key_dark_mode));
assert switchPreferenceCompat != null;
switchPreferenceCompat.setOnPreferenceChangeListener((preference, newValue) -> {
boolean isChecked = false;
if (newValue instanceof Boolean)
isChecked = (Boolean) newValue;
if (isChecked) {
getPreferenceManager().getSharedPreferences().edit().putBoolean(getString(R.string.key_dark_mode), true).apply();
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
Log.d(TAG, "onCreatePreferences: NIGHT mode on");
} else {
getPreferenceManager().getSharedPreferences().edit().putBoolean(getString(R.string.key_dark_mode), false).apply();
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
Log.d(TAG, "onCreatePreferences: nightmode off");
}
return true;
});
}
}
}
And here is how i read in main activity :
MainActivity
protected void onCreate(Bundle savedInstanceState) {
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
boolean switchPref = sharedPref.getBoolean(getString(R.string.key_dark_mode), false);
//Toast.makeText(this, Boolean.toString(switchPref), Toast.LENGTH_SHORT).show();
if (switchPref) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
//setTheme(R.style.NightMode);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
//setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
I even tried MainActivity without PreferenceManager still items in recyclerView are duplicated.

Unable to update textview from callback method

I have an interface implemented in MainActivity, and inside that callback method i want to update my TextView but i am getting nullpointer exception.
This is my MainActivity class
public class MainActivity extends AppCompatActivity implements GenericCallback
{
Context mcontext;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mcontext = this;
Button btn = findViewById(R.id.btn);
tv = findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(MainActivity.this,SecondActivity.class));
}
});
}
#Override
public void doSomething(Context context, String... a)
{
Toast.makeText(context,"Calback"+a[0]+a[1],Toast.LENGTH_SHORT).show();
tv = findViewById(R.id.tv);//Line 43
tv.setText(a[0]+a[1]);
}
My interface looks like this
public interface GenericCallback
{
void doSomething(Context context, String... a);
}
My SecomdActivity
public class SecondActivity extends AppCompatActivity
{
Context context;
GenericCallback genericCallback = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
context = this;
String a="Secomd",b = "Activity";
genericCallback.doSomething(context,a,b);
finish();
}
}
StackTrace
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.view.Window$Callback
android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:117)
at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:149)
at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:56)
at android.support.v7.app.AppCompatDelegateImplV23.(AppCompatDelegateImplV23.java:31)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:200)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at android.com.callback.MainActivity.doSomething(MainActivity.java:43)
at android.com.callback.SecondActivity.onCreate(SecondActivity.java:21)
I already know what is nullpointer, I already referred this and this
You can use EventBus Library
For installation
compile 'org.greenrobot:eventbus:3.1.1'
First, create a Java class
public class MsgEvent {
String oo;
public String getOo() {
return oo;
}
public void setOo(String oo) {
this.oo = oo;
}
}
Then in SecondActivity
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
context = this;
String a="Secomd",b = "Activity";
MsgEvent msgEvent = new MsgEvnet();
msgEvent.setOo(a);
EventBus.getDefault().post(msgEvent);
finish();
}
Then in MainActivity
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MsgEvent event) {
String value = event.getOo();
}
You can use BroadcastReceiver
check the below example
MainActivity
public class MainActivity extends AppCompatActivity {
TextView mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = findViewById(R.id.toolbar_title);
startActivity(new Intent(this, SecondActivity.class));
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mTitle.setText(intent.getStringExtra("DATA"));
Toast.makeText(context, "recieved text : " + intent.getStringExtra("DATA"), Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction("MY_ACTION");
registerReceiver(myBroadcastReceiver, filter);
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
}
XML form MainActivity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbarIcon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Nilesh"
android:textStyle="bold" />
</LinearLayout>
Second_activity
public class SecondActivity extends AppCompatActivity {
TextView tvText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
getSupportActionBar().setTitle("SECOND Activity");
tvText = findViewById(R.id.tvText);
tvText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendBroadcast();
}
});
}
public void sendBroadcast() {
Intent broadcast = new Intent();
broadcast.putExtra("DATA", "MY NAME IS NILESH");
broadcast.setAction("MY_ACTION");
sendBroadcast(broadcast);
}
}
LAYOUT for second activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<TextView
android:layout_width="match_parent"
android:id="#+id/tvText"
android:text="Click to Send Broadcas"
android:layout_height="wrap_content" />
</LinearLayout>
The reason you are getting that null exception is that your MainActivity view is not inflated because it is not instantiated by the framework.
You can create an instance getter method from your first activity.
private static GenericCallback instance;
public static GenericCallback getHandler() {
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
...
instance = this;
...
}
And then on your 2nd activity, get that instance instead of instantiating an activity.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
context = this;
String a="Secomd",b = "Activity";
GenericCallback genericCallback = MainActivity.getHandler();
genericCallback.doSomething(context,a,b);
finish();
}

Android preferences how to make an info preference

In my android app I have settings activity, which uses preferences.
There are many preferences such as ListPreference, SwitchPreference, etc., but there aren't one kind of preference that I need.
In this preference I want to:
1. display a title that is constant and will never change (such as other preferences)
2. display text, that will be changed by the app, but NOT by the user.
Most similar preference to this is EditTextPreference, but it's not OK for me, because I don't want user to change displayed text, instead my app will change it. So my preference could be called TextViewPreference.
Good example of what I want is inside the 'Settings' android app, inside the 'device information' category.
Edit:
Code that I would like to use to change summary won't be placed in activity code, and I don't use PreferenceActivity.
In fact, only time when I have to change the summary is when the SettingsActivity is NOT on main thread.
The code below is a complete example of what you are trying to achieve, it shows an example of how to create an info preference that is directly updated based on other preferences (addition of x_pref and y_pref and displaying result in result_pref below) or is updated based on something passed from another activity.
1) DemoActivity----------
public class DemoActivity extends AppCompatActivity{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_activity);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.demo_preferences, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_settings:
Intent i = new Intent(DemoActivity.this , PrefDemoActivity.class);
i.putExtra("Passed", "Test--##%%&&");
startActivity(i);
break;
default:
throw new RuntimeException("unknown menu selection");
}
return true;
}
}
2) demo_activity.xml----------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Empty"
android:gravity="center"
android:background="#android:color/holo_blue_light"/>
</android.support.constraint.ConstraintLayout>
3) PrefDemoActivity----------
public class PrefDemoActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction mFragmentTransaction = mFragmentManager
.beginTransaction();
DemoEditPreferences mDemoPrefsFragment = new DemoEditPreferences();
mFragmentTransaction.replace(android.R.id.content, mDemoPrefsFragment);
mFragmentTransaction.commit();
}
}
4) DemEditPreferences----------
public class DemoEditPreferences extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
private SharedPreferences demo_preferences;
private int preferencesToEdit;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demo_preferences = getActivity().getSharedPreferences("demo_preference",
0);
preferencesToEdit = R.xml.demo_preferences;
String preferenceName = getResources().getString(R.string.pref_sensor_key);
PreferenceManager preferenceManager = getPreferenceManager();
preferenceManager.setSharedPreferencesName(preferenceName);
preferenceManager.setSharedPreferencesMode(0);
getActivity().setTitle("Demo Preferences");
addPreferencesFromResource(preferencesToEdit);
Preference from_another_activity_p = (Preference) findPreference("passed_from_another_activity_key");
if(getActivity().getIntent() != null) {
from_another_activity_p.setSummary(getActivity().getIntent().getStringExtra("Passed"));
}
updateResult();
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(findPreference(key) != null) {
if(findPreference(key).getKey().equals("x_key")) {
updateResult();
}else if(findPreference(key).getKey().equals("y_key")) {
updateResult();
}
checkPrefValueValidity(findPreference(key));
updatePrefSummary(findPreference(key));
}
}
private void updateResult(){
EditTextPreference x_p = (EditTextPreference) findPreference("x_key");
EditTextPreference y_p = (EditTextPreference) findPreference("y_key");
Preference result_p = (Preference) findPreference("result_key");
result_p.setSummary("( X + Y ) = " + (Float.valueOf(x_p.getText()) + Float.valueOf(y_p.getText())));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCategory = (PreferenceCategory) p;
for (int i = 0; i < pCategory.getPreferenceCount(); i++) {
initSummary(pCategory.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());
}
}
private void checkPrefValueValidity(Preference p) {
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
if (editTextPref.getText().equals("")) {
// what do you want to do if the value entered is empty
} else {
// maybe only certain values are allowed
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(android.R.color.white));
return view;
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
5) demo_menu----------
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_settings"
android:title="Settings"
android:titleCondensed="Settings"
android:orderInCategory="1">
</item>
</menu>
7) demo_preferences----------
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Demo">
<EditTextPreference
android:key="x_key"
android:title="X"
android:defaultValue="0"
android:summary="0"
android:inputType="numberDecimal|numberSigned"
android:selectAllOnFocus="true"
android:singleLine="true">
</EditTextPreference>
<EditTextPreference
android:key="y_key"
android:title="Y"
android:defaultValue="0"
android:summary="0"
android:inputType="numberDecimal|numberSigned"
android:selectAllOnFocus="true"
android:singleLine="true">
</EditTextPreference>
<Preference
android:key="result_key"
android:title="Result"
android:summary="0"> // default summary value if any
</Preference>
<Preference
android:key="passed_from_another_activity_key"
android:title="From another Activity"
android:summary="null"> // default summary value if any
</Preference>
</PreferenceCategory>
</PreferenceScreen>
8) Don't forget to add both activities to the manifest.
What you can do is have an EditTextPreference and disable it. So that the subtitle is displayed but cannot be edited.
findPreference("your-preference-key").setEnabled(false);

Eclipse, new activity on button click

I'm a beginner but I would like to modify an older project.
On the Preferences Activity, there are already few buttons, but I would like to add a new button, which, when clicked, opens a new Activity and shows an image only.
For this I declared this new activity in the Manifest:
<activity
android:name=".VisualHelpActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme" >
</activity>
I declared the button on the associated xml layout:
<Button
android:id="#+id/button_visualhelp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="visual_help"
android:text="Visual Help" />
I created the new VisualHelp layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/visualhelp_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/guide" />
Declared its new VisualHelpActivity java file:
public class VisualHelpActivity extends TranslatableActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visualhelp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.visual_help, menu);
return true;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void refreshLanguage() {
}
}
… and now I’m supposed to connect it all together in the "main" PreferencesActivity, which looks as follows:
public class PreferencesActivity extends TranslatableActivity {
public static String url = "https://www.paypal.com/cgi-bin....";
ImageView donate;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_preferences);
donate = (ImageView) findViewById(R.id.button_donate);
donate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
donate(v);
}
});
Spinner s = (Spinner) findViewById(R.id.combo_language);
Lang[] languages = LanguageUtil.Lang.values();
s.setAdapter(new ArrayAdapter<Lang>(this,
android.R.layout.simple_dropdown_item_1line, languages));
s.setSelection(getPosition(languages, LanguageUtil.getLanguage()), true);
}
private int getPosition(Object[] objs, Object item) {
for (int i = 0; i < objs.length; i++) {
if (objs[i] == item)
return i;
}
return -1;
}
public void update(View v) {
Maintenance.downloadDB(this, new onFinishListener() {
#Override
public void onFinish() {
LanguageUtil.loadLanguage(PreferencesActivity.this);
}
});
}
public void copy(View v) {
Maintenance.copyDB(this, new onFinishListener() {
#Override
public void onFinish() {
LanguageUtil.loadLanguage(PreferencesActivity.this);
}
});
}
public void save(View v) {
LanguageUtil.saveLanguage(this,
(Lang) ((Spinner) findViewById(R.id.combo_language))
.getSelectedItem());
LanguageUtil.loadLanguage(this);
setResult(RESULT_OK);
finish();
}
public void donate(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
public void cancel(View v) {
finish();
}
#Override
protected void refreshLanguage() {
((Button) findViewById(R.id.button_update)).setText(LanguageUtil
.getDeviceLabel(LanguageUtil.dev_update));
((TextView) findViewById(R.id.language_label))
.setText(LanguageUtil.getDeviceLabel(LanguageUtil.dev_language));
}
}
According to androidbegin.com, I should add this code into the PreferencesActivity java file (code above):
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visualhelp);
button = (Button) findViewById(R.id.button_visualhelp);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(PreferencesAtivity.this,
VisualHelpActivity.class);
startActivity(myIntent);
}
});
}
The only problem is that if I try to add this new public void, multiple marker errors pop up, and if I try to include all below somewhere else, my app fails to work. So, can anyone help me out where and how to include this code part to make it work?
add the code inside oncreate method like this in your PreferencesActivity class:-
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_preferences);
donate = (ImageView) findViewById(R.id.button_donate);
donate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
donate(v);
}
});
button = (Button) findViewById(R.id.button_visualhelp);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(PreferencesAtivity.this,
VisualHelpActivity.class);
startActivity(myIntent);
}
});
Spinner s = (Spinner) findViewById(R.id.combo_language);
Lang[] languages = LanguageUtil.Lang.values();
s.setAdapter(new ArrayAdapter<Lang>(this,
android.R.layout.simple_dropdown_item_1line, languages));
s.setSelection(getPosition(languages, LanguageUtil.getLanguage()), true);
}

PreferenceFragment NullPointerException

public class MyPrefs extends PreferenceActivity {
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyPreferenceFragment frag = new MyPreferenceFragment();
getFragmentManager().beginTransaction().replace(android.R.id.content, frag).commit();
Preference pref;
pref = frag.findPreference("pref_gps_updates");
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return true;
}
});
}
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.preference.Preference.setOnPreferenceChangeListener(android.preference.Preference$OnPreferenceChangeListener)' on a null object reference
I don't understand why I get this crash or what I am doing wrong?
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:key="pref_gps_updates"
android:inputType="number"
android:title="#string/pref_gps_updates"
android:summary="#string/pref_gps_updates_summary"
android:defaultValue="60" />
</PreferenceScreen>
Preference pref;
pref = frag.findPreference("pref_updates");
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return true;
}
});
Put this part into your Fragment's onCreate() (NOT in the activities onCreate) and double check if the key pref_updates is used in your xml.
Update:
public class MyPrefs extends PreferenceActivity {
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference pref;
pref = findPreference("pref_gps_updates");
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return true;
}
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyPreferenceFragment frag = new MyPreferenceFragment();
getFragmentManager().beginTransaction().replace(android.R.id.content, frag).commit();
}
}
Instead of creating a PreferenceChangedListener for each preference, it would be better to just have your PreferenceFragment implement the OnSharedPreferenceChangeListener interface.
That way, no matter how many preferences you add, you won't need to add a new listener for each one, and the logic is self-contained in the PreferenceFragment.
It would be something like this:
public class MyPrefs extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyPreferenceFragment frag = new MyPreferenceFragment();
getFragmentManager().beginTransaction().replace(android.R.id.content, frag).commit();
/* remove all of this
Preference pref;
pref = frag.findPreference("pref_gps_updates");
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return true;
}
});
*/
}
public static class MyPreferenceFragment extends PreferenceFragment
implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("pref_gps_updates")) {
//do something
}
}
}
}
In code you use
pref = frag.findPreference("pref_updates");
but in xml it says
android:key="pref_gps_updates"
change keys need to match to be found.
Try and move the code up before you do the fragment transaction.
MyPreferenceFragment frag = new MyPreferenceFragment();
Preference pref;
pref = frag.findPreference("pref_gps_updates");
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return true;
}
});
getFragmentManager().beginTransaction().replace(android.R.id.content, frag).commit();
}
}

Categories