我有一个帐户信息活动,我需要使用 PreferenceFragment 向用户显示我从 Internet 获得的帐户信息。
而且我正在尝试为首选项设置标题,但每次我有一段java.lang.NullPointerExcption
时间我都在尝试这样做。
那么问题出在哪里,我该怎么办?
AccountData.java
import android.app.Activity;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
public class AccountData extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new PrefsFragment()).commit();
try {
PrefsFragment PF = new PrefsFragment();
PF.setAccountName();
} catch (Exception e) {
e.printStackTrace();
}
}
public static class PrefsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.account_data);
}
public void setAccountName() {
Preference AccountName = (Preference) findPreference("account_name");
AccountName.setTitle("Account Name");
}
}
}
account_data.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="@string/account" >
<Preference
android:key="account_name"
android:selectable="false"
android:summary="@string/account_name"
android:title="@string/none" />
<Preference
android:key="account_type"
android:selectable="false"
android:summary="@string/account_type"
android:title="@string/none" />
</PreferenceCategory>
</PreferenceScreen>
_ **已编辑** _
堆栈跟踪
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.AccountData}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2088)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2113)
at android.app.ActivityThread.access$700(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1224)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4918)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.app.AccountData$PrefsFragment.setAccountName(AccountData.java:39)
at com.example.app.AccountData.onCreate(AccountData.java:21)
at android.app.Activity.performCreate(Activity.java:5048)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2052)
... 11 more