我正在尝试将一些高分保存到sharedPreferences。在我的GameActivity中,我创建了这样的sharedPreferences:
public class GameActivity extends Activity {
//public static final String KEY_RESTORE = "key_restore";
//public static final String PREFS_SCORES = "pref_scores";
private GameFragment mGameFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
SharedPreferences highScorePreferences = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
//final SharedPreferences highScorePreferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
}
}
然后我尝试将我的高分列表添加到sharedPreferences中,如下所示:
public class GameFragment extends Fragment {
SharedPreferences highScorePreferences = this.getActivity().getSharedPreferences("MyPref", Context.MODE_PRIVATE);
//private static final int PREFERENCE_MODE_PRIVATE = 0;
//private SharedPreferences highScorePreferences = getActivity().getPreferences(PREFERENCE_MODE_PRIVATE);
private SharedPreferences.Editor highScoreEdit = highScorePreferences.edit();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_game, container, false);
@Override
public void onClick(View view) {
if (currentImage == 2) {
hm.addScore("Bart", score);
String highScoreString = hm.getHighscoreString();
Log.d("UT3", hm.getHighscoreString());
score = 0;
highScoreEdit.putString("high_scores", highScoreString);
highScoreEdit.commit();
}
}
});
return rootView;
}
当我尝试运行应用程序时,GameActivity有这个运行时异常:android.view.InflateException: Binary XML file line #8: Error inflating class fragment
堆栈追踪:
07-25 14:00:26.895 2024-2066/? W/PowerManagerService﹕ Timer 0x3->0x3|0x0
07-25 14:00:27.015 2139-2139/? D/STATUSBAR-NetworkController﹕ onDataActivity: direction=0
07-25 14:00:27.025 2139-2139/? D/STATUSBAR-NetworkController﹕ refreshSignalCluster: data=2 bt=false
07-25 14:00:27.105 2024-2077/? I/InputReader﹕ Touch event's action is 0x0 (deviceType=0) [pCnt=1, s=0.1092 ]
07-25 14:00:27.105 2024-2076/? I/InputDispatcher﹕ Delivering touch to current input target: action: 0x0
07-25 14:00:27.105 2024-2076/? I/InputDispatcher﹕ Delivering touch to current input target: action: 0x0
07-25 14:00:27.105 2024-2076/? I/InputDispatcher﹕ Delivering touch to current input target: action: 0x0
07-25 14:00:27.215 2024-2077/? I/InputReader﹕ Touch event's action is 0x1 (deviceType=0) [pCnt=1, s=]
07-25 14:00:27.215 2024-2076/? I/InputDispatcher﹕ Delivering touch to current input target: action: 0x1
07-25 14:00:27.215 2024-2076/? I/InputDispatcher﹕ Delivering touch to current input target: action: 0x1
07-25 14:00:27.215 2024-2076/? I/InputDispatcher﹕ Delivering touch to current input target: action: 0x1
07-25 14:00:27.225 2024-2308/? I/power﹕ *** acquire_dvfs_lock : lockType : 1 freq : 1000000
07-25 14:00:27.225 2024-2308/? D/PowerManagerService﹕ acquireDVFSLockLocked : type : DVFS_MIN_LIMIT frequency : 1000000 uid : 1000 pid : 2024 tag : ActivityManager
07-25 14:00:27.225 2024-2308/? W/ActivityManager﹕ mDVFSLock.acquire()
07-25 14:00:27.305 2024-2339/? D/WindowManager﹕ PhoneWindowManager: focusChangedLw
07-25 14:00:27.305 2024-2339/? D/KeyguardViewMediator﹕ setHidden false
07-25 14:00:27.346 16854-16854/org.example.whatstate D/AndroidRuntime﹕ Shutting down VM
07-25 14:00:27.346 16854-16854/org.example.whatstate W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x419ed2a0)
07-25 14:00:27.386 16854-16854/org.example.whatstate E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.example.whatstate/org.example.whatstate.GameActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
at android.app.ActivityThread.access$700(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
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:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:316)
at android.app.Activity.setContentView(Activity.java:1901)
at org.example.whatstate.GameActivity.onCreate(GameActivity.java:22)
at android.app.Activity.performCreate(Activity.java:5047)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
at android.app.ActivityThread.access$700(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
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:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at org.example.whatstate.GameFragment.<init>(GameFragment.java:47)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Fragment.instantiate(Fragment.java:577)
at android.app.Fragment.instantiate(Fragment.java:552)
at android.app.Activity.onCreateView(Activity.java:4695)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:316)
at android.app.Activity.setContentView(Activity.java:1901)
at org.example.whatstate.GameActivity.onCreate(GameActivity.java:22)
at android.app.Activity.performCreate(Activity.java:5047)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
at android.app.ActivityThread.access$700(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
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:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
07-25 14:00:27.426 2024-2050/? E/android.os.Debug﹕ !@Dumpstate > dumpstate -k -t -z -d -o /data/log/dumpstate_app_error
07-25 14:00:27.446 16955-16955/? I/dumpstate﹕ begin
fragment_game.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/menu_background"
android:elevation="@dimen/elevation_high"
android:orientation="vertical"
android:padding="@dimen/menu_padding"
tools:context=".WhatStateActivity">
<TextView
android:id="@+id/questionTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/menu_space"
android:text="@string/guess_question"
android:textAppearance="?android:textAppearanceLarge"
android:textSize="@dimen/menu_text_size" />
<ImageView
android:id="@+id/idImageViewPic"
android:layout_width="match_parent"
android:layout_height="342dp"
android:layout_weight="1.04"
android:adjustViewBounds="true"
android:background="#66FFFFFF"
android:maxHeight="91dip"
android:maxWidth="47dip"
android:padding="10dip"
android:src="@drawable/alabama" />
<EditText
android:id="@+id/ResponseText"
android:layout_height="wrap_content"
android:hint="@string/response_hint"
android:inputType="textPersonName"
android:layout_width="fill_parent"
android:textSize="8pt">
</EditText>
<Button
android:id="@+id/guess_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/menu_button_margin"
android:padding="@dimen/menu_button_padding"
android:text="@string/continue_label" />
</LinearLayout>
更新的代码如果视图在其他位置膨胀,如何按ID查找视图? (java新手):
public class GameFragment extends Fragment {
private AlertDialog mDialog;
private ImageView hImageViewPic;
private Button iButton, gButton;
private int currentImage = 0;
int[] images = {R.drawable.alabama, R.drawable.alaska, R.drawable.arizona, R.drawable.california, R.drawable.done};
final String[] capitals = {"montgomery", "juneau", "phoenix", "sacramento"};
//final SharedPreferences highScorePreferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
//final SharedPreferences highScorePreferences = getActivity().getSharedPreferences(0);
//private static final int PREFERENCE_MODE_PRIVATE = 0;
//private SharedPreferences highScorePreferences = getActivity().getPreferences(PREFERENCE_MODE_PRIVATE);
//SharedPreferences highScorePreferences = this.getActivity().getSharedPreferences("MyPref", Context.MODE_PRIVATE);
//private SharedPreferences.Editor highScoreEdit = highScorePreferences.edit();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_game, container, false)
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
hImageViewPic = (ImageView) rootView.findViewById(R.id.idImageViewPic);
final TextView questionTextView = (TextView) rootView.findViewById(R.id.questionTextView);
iButton = (Button) rootView.findViewById(R.id.guess_button);
int resourceId = images[currentImage];
String name = getResources().getResourceEntryName(resourceId);
//hImageViewPic.setImageResource(resourceId);
hImageViewPic.setTag(name);
final EditText responseField = (EditText) rootView.findViewById(R.id.ResponseText);
final MediaPlayer bubblePlayer = MediaPlayer.create(getActivity(), R.raw.bubble);
final MediaPlayer swooshPlayer = MediaPlayer.create(getActivity(), R.raw.swoosh);
// Handle buttons here...
final View guessButton = rootView.findViewById(R.id.guess_button);
guessButton.setOnClickListener(new View.OnClickListener() {
HighscoreManager hm = new HighscoreManager();
int score = 0;
@Override
public void onClick(View view) {
bubblePlayer.start();
String response = responseField.getText().toString().toLowerCase();
String imageName = (String) hImageViewPic.getTag();
String wrongTextAnnouncement = getString(R.string.wrong_text, imageName);
Log.d("UT3", "response: " + response);
Log.d("UT3", wrongTextAnnouncement);
Log.d("UT3", "imageName: " + imageName);
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
final View customLayout = getActivity().getLayoutInflater().inflate(R.layout.capital_prompt, null);
builder.setView(customLayout);
if (imageName.equals(response)) {
Log.d("UT3", "right answer");
final EditText capitalInputField = (EditText) customLayout.findViewById(R.id.userInput);
//capitalInputField.setText("Capital name");
builder.setTitle(R.string.right_title);
builder.setMessage(R.string.right_text);
builder.setCancelable(false);
builder.setPositiveButton(R.string.ok_label,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface,
int i) {
//nothing
String capitalName = capitals[currentImage];
String capitalResponse = capitalInputField.getText().toString().toLowerCase();
if (capitalResponse.equals(capitalName)){
//add two points and move on to next picture
Log.d("UT3", "got right capital name");
score += 2;
currentImage++;
currentImage = currentImage % images.length;
hImageViewPic.setImageResource(images[currentImage]);
int resourceId = images[currentImage];
String name = getResources().getResourceEntryName(resourceId);
//hImageViewPic.setImageResource(resourceId);
hImageViewPic.setTag(name);
swooshPlayer.start();
}
else{
Log.d("UT3", "got wrong capital name");
currentImage++;
currentImage = currentImage % images.length;
hImageViewPic.setImageResource(images[currentImage]);
int resourceId = images[currentImage];
String name = getResources().getResourceEntryName(resourceId);
//hImageViewPic.setImageResource(resourceId);
hImageViewPic.setTag(name);
swooshPlayer.start();
}
}
});
score += 10;
String scoreString = String.valueOf(score);
Log.d("UT3", "Score: " + scoreString);
//String capitalString = "Name its capital";
//iButton.setOnClickListener(getOnClickDoSomething(iButton));
} else {
Log.d("UT3", "wrong answer");
final View noCapitalLayout = getActivity().getLayoutInflater().inflate(R.layout.no_capital_prompt, null);
builder.setView(noCapitalLayout);
builder.setTitle(R.string.wrong_title);
//builder.setMessage(wrongTextAnnouncement);
builder.setCancelable(false);
builder.setPositiveButton(R.string.ok_label,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface,
int i) {
// nothing
}
});
//mDialog = builder.show();
currentImage++;
currentImage = currentImage % images.length;
hImageViewPic.setImageResource(images[currentImage]);
Log.d("UT3", "reached wrong answer");
int resourceId = images[currentImage];
String name = getResources().getResourceEntryName(resourceId);
hImageViewPic.setImageResource(resourceId);
hImageViewPic.setTag(name);
swooshPlayer.start();
}
mDialog = builder.show();
Log.d("UT3", "currentImage: " + currentImage);
if (currentImage == 4) {
AlertDialog.Builder nameBuilder =
new AlertDialog.Builder(getActivity());
final View nameInputLayout = getActivity().getLayoutInflater().inflate(R.layout.name_prompt, null);
nameBuilder.setView(nameInputLayout);
final EditText nameInputField = (EditText) nameInputLayout.findViewById(R.id.nameInput);
nameBuilder.setTitle(R.string.right_title);
//nameBuilder.setMessage(R.string.right_text);
nameBuilder.setCancelable(false);
nameBuilder.setPositiveButton(R.string.ok_label,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface,
int i) {
//nothing
final String userName = nameInputField.getText().toString();
hm.addScore(userName, score);
Log.d("UT3", "userName: " + userName);
String highScoreString = hm.getHighscoreString();
Log.d("UT3", hm.getHighscoreString());
score = 0;
//highScoreEdit.putString("high_scores", highScoreString);
//highScoreEdit.commit();
}
});
nameBuilder.show();
}
}
});
}
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
button.setText("text now set.. ");
}
};
}
@Override
public void onPause() {
super.onPause();
// Get rid of the about dialog if it's still up
if (mDialog != null)
mDialog.dismiss();
}
public void restartGame() {
initGame();
initViews(getView());
}
public void initGame() {
Log.d("UT3", "init game");
}
private void initViews(View rootView) {
Log.d("UT3", "init views");
}
}
答案 0 :(得分:0)
创建NullPointerException
的实例时,您正在使用GameFragment
崩溃。大多数已注释掉的代码会触发此类NullPointerException
,因为getActivity()
在调用onAttach()
之前不会对片段起作用。