I’m trying to add preferences to my app but cant make it work.
Here is my res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:key="format"
android:title="Saving Format"
android:summary="Select the file format"
android:defaultValue=".jpg"
android:entries="@array/format"
android:entryValues="@array/formatValues" />
</PreferenceScreen>
Here is my values/array.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="format">
<item name=".jpg">JPEG</item>
<item name=".gif">GIF</item>
</string-array>
<string-array name="formatValues">
<item name=".jpg">.jpg</item>
<item name=".gif">.gif</item>
</string-array>
</resources>
Here is my preferences activity:
package com.sass.recorder;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class MyPreferences extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Here is the main activity class:
...imports..
public class MyApp extends Activity {
...Initializations..
SharedPreferences preferences;
.....
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
....
private OnClickListener mOneShotListener = new OnClickListener() {
public void onClick(View v) {
//evaluate preferences and change the path variable
if (preferences.getString("format", ".jpg") == ".jpg") {
path = "/sdcard/output/" + editText1.getText() + ".jpg";
} else if (preferences.getString("format", ".gif") == ".gif"){
path = "/sdcard/output/" + editText1.getText() + ".gif";
}
}
}
}
}
The preferences acitivity works(from the menu which I didn’t paste here), but the button that has the preferences evaluation simply won’t click or react. Sometimes the debuger shows a NullPointerException in the line
if (preferences.getString("format", ".jpg") == ".jpg")
Any ideas what I’m doing wrong?
Thanks!
You’ve declared the variable preferences both as instance variable in the class, which is used in the OnClickListener, and inside the onCreate method. The instance variable is never initialized and is therefor null when accessed in the OnClickListener. Change
into
in the MyApp activity and it will probably work.