我在android中开发游戏,你完成了四个问题的测试,然后回到主菜单, 现在进入主菜单活动来测试活动没问题,但每当我进入测试活动并尝试通过完成4个问题或onPressedBack()函数或按对话框上的主菜单按钮返回主菜单时它会给我NullPointerException 。 这是我的测试代码:
public class Test extends Activity implements OnClickListener{
TextView tvBorder, tvBorder2, tvOperation, tvRight, tvWrong, tvTotal, tvTimer;
Button bMcq1, bMcq2, bMcq3, bMcq4;
ImageButton ibMusic, ibPause;
Timer t;
MediaPlayer mp;
private String name;
private int difficulty;
private int ops[];
private int TotalCounter = 0;
private int TimeCounter = 0;
private int right = 0, wrong = 0;
private double answer = -1;
private boolean ispressed = false;
private Plus plus;
private Minus minus;
private Multi multi;
private Division div;
private RandomizedQueue<Integer> rd;
Random rand = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
difficulty = getIntent().getExtras().getInt("Difficulty");
Log.d("test Difficulty 2", String.valueOf(difficulty));
ops = getIntent().getExtras().getIntArray("OPstring");
Log.d("OPS 2", String.valueOf(ops.length));
name = getIntent().getExtras().getString("Reference2");
Log.d("Reference2", name);
Initialize();
generateQuestions();
}
private void Initialize() {
// TODO Auto-generated method stub
mp = MediaPlayer.create(this, R.raw.game);
mp.setLooping(true);
mp.start();
tvBorder = (TextView) findViewById(R.id.border);
tvBorder2 = (TextView) findViewById(R.id.border2);
tvOperation = (TextView) findViewById(R.id.op);
tvRight = (TextView) findViewById(R.id.right);
tvWrong = (TextView) findViewById(R.id.wrong);
tvTotal = (TextView) findViewById(R.id.total);
tvTimer = (TextView) findViewById(R.id.timer);
bMcq1 = (Button) findViewById(R.id.mcq1);
bMcq2 = (Button) findViewById(R.id.mcq2);
bMcq3 = (Button) findViewById(R.id.mcq3);
bMcq4 = (Button) findViewById(R.id.mcq4);
ibMusic = (ImageButton) findViewById(R.id.music);
ibPause = (ImageButton) findViewById(R.id.pausemenu);
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
tvTimer.setText(String.valueOf(TimeCounter));
TimeCounter++;
}
});
}
}, 1000, 1000);
bMcq1.setOnClickListener(this);
bMcq2.setOnClickListener(this);
bMcq3.setOnClickListener(this);
bMcq4.setOnClickListener(this);
ibMusic.setOnClickListener(this);
ibPause.setOnClickListener(this);
}
private void generateQuestions() {
// TODO Auto-generated method stub
if(TotalCounter == 4)
{
Intent back = new Intent(Test.this, MainMenu.class);
startActivity(back);
}
plus = new Plus(difficulty);
minus = new Minus(difficulty);
multi = new Multi(difficulty);
div = new Division(difficulty);
rd = new RandomizedQueue<Integer>();
TotalCounter++;
tvTotal.setText(String.valueOf(TotalCounter));
int gen = rand.nextInt(ops.length);
Log.d("generated number", String.valueOf(gen));
int TheChosenOP = ops[gen];
Log.d("TheChosenOP", String.valueOf(TheChosenOP));
switch(TheChosenOP)
{
case 1:
Toast t = Toast.makeText(Test.this, "Plus", 5000);
t.show();
tvOperation.setText("+");
int i = plus.getBorder();
int j = plus.getBorder2();
tvBorder.setText(String.valueOf(i));
tvBorder2.setText(String.valueOf(j));
answer = plus.getAnswer();
SetAnswer(answer);
break;
case 2:
Toast t2 = Toast.makeText(Test.this, "Minus", 5000);
t2.show();
tvOperation.setText("-");
int i2 = minus.getBorder();
int j2 = minus.getBorder2();
tvBorder.setText(String.valueOf(i2));
tvBorder2.setText(String.valueOf(j2));
answer = minus.getAnswer();
SetAnswer(answer);
break;
case 3:
Toast t3 = Toast.makeText(Test.this, "Multi", 5000);
t3.show();
tvOperation.setText("*");
int i3 = multi.getBorder();
int j3 = multi.getBorder2();
tvBorder.setText(String.valueOf(i3));
tvBorder2.setText(String.valueOf(j3));
answer = multi.getAnswer();
SetAnswer(answer);
break;
case 4:
Toast t4 = Toast.makeText(Test.this, "Division", 5000);
t4.show();
tvOperation.setText("/");
int i4 = div.getBorder();
int j4 = div.getBorder2();
tvBorder.setText(String.valueOf(i4));
tvBorder2.setText(String.valueOf(j4));
answer = div.getAnswer();
SetAnswer(answer);
break;
}
}
private void SetAnswer(double answer) {
// TODO Auto-generated method stub
int firstchoice = (int) ((int) answer - ((answer * 10) / 100));
Log.d("Test", String.valueOf(firstchoice));
int secondchoice = (int) ((int) answer + Math.ceil(((answer * 10) / 100)));
int Thirdchoice;
if (difficulty == 1)
Thirdchoice = (int) answer + 2;
else
Thirdchoice = (int) ((int) answer + Math.ceil(((answer * 25) / 100)));
rd.enqueue((int) answer);
rd.enqueue(firstchoice);
rd.enqueue(secondchoice);
rd.enqueue(Thirdchoice);
bMcq1.setText(String.valueOf(rd.dequeue()));
bMcq2.setText(String.valueOf(rd.dequeue()));
bMcq3.setText(String.valueOf(rd.dequeue()));
bMcq4.setText(String.valueOf(rd.dequeue()));
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String ans;
switch(v.getId())
{
// setting Music
case R.id.music:
if (ispressed == false)
{
mp.pause();
ispressed = true;
}
else
{
mp.start();
ispressed = false;
}
break;
// setting Pause Menu
case R.id.pausemenu:
final Dialog d = new Dialog(this);
d.setTitle("Pause Menu");
d.setContentView(R.layout.pausemenu);
Button resume = (Button) d.findViewById(R.id.Resume);
Button Back = (Button) d.findViewById(R.id.Main);
resume.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
d.cancel();
mp.start();
}
});
Back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent iback = new Intent();
iback.setClass(Test.this, MainMenu.class);
startActivity(iback);
}
});
mp.pause();
d.show();
break;
//setting answers:
case R.id.mcq1:
ans = (String) bMcq1.getText();
CheckAnswer(ans);
break;
case R.id.mcq2:
ans = (String) bMcq2.getText();
CheckAnswer(ans);
break;
case R.id.mcq3:
ans = (String) bMcq3.getText();
CheckAnswer(ans);
break;
case R.id.mcq4:
ans = (String) bMcq4.getText();
CheckAnswer(ans);
break;
}
}
private void CheckAnswer(String ans) {
// TODO Auto-generated method stub
if (Integer.parseInt(ans) == answer) {
Toast t = Toast.makeText(this, "True, Bravo!!!", 5000);
t.show();
//counter++;
right++;
tvRight.setText(String.valueOf(right));
generateQuestions();
} else {
Toast t = Toast.makeText(this,
"False, Go home u r drunk!!", 5000);
t.show();
wrong++;
tvWrong.setText(String.valueOf(wrong));
generateQuestions();
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
//mp.stop();
}
public void onBackPressed() {
//TODO Auto-generated method stub
super.onBackPressed();
startActivity(new Intent(this, MainMenu.class));
}
}
关于MainMenu活动 - 这是最重要的:
public class MainMenu extends Activity implements OnClickListener{
ImageButton ibEasy, ibIntermediate, ibHard, ibMusic, ibGo, ibTest, ibPractice, ibStatistic;
CheckBox cPlus, cMinus, cMulti, cDiv;
private int difficulty = 0;
private int operation = 0;
private int top = 0;
private boolean p = false, m = false, mu = false, d = false;
private boolean ispressed = false;
String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
Initialize();
}
private void Initialize() {
// TODO Auto-generated method stub
ibEasy = (ImageButton) findViewById(R.id.imageButton1);
ibIntermediate = (ImageButton) findViewById(R.id.imageButton2);
ibHard = (ImageButton) findViewById(R.id.imageButton3);
ibMusic = (ImageButton) findViewById(R.id.imageButton4);
ibGo = (ImageButton) findViewById(R.id.imageButton5);
ibPractice = (ImageButton) findViewById(R.id.imageButton6);
ibTest = (ImageButton) findViewById(R.id.imageButton7);
ibStatistic = (ImageButton) findViewById(R.id.imageButton8);
//ibEasy.setPressed(true);
cPlus = (CheckBox) findViewById(R.id.checkBox1);
cMinus = (CheckBox) findViewById(R.id.checkBox2);
cMulti = (CheckBox) findViewById(R.id.checkBox3);
cDiv = (CheckBox) findViewById(R.id.checkBox4);
name = getIntent().getExtras().getString("Reference");
ibEasy.setOnClickListener(this);
ibIntermediate.setOnClickListener(this);
ibHard.setOnClickListener(this);
ibMusic.setOnClickListener(this);
ibGo.setOnClickListener(this);
ibTest.setOnClickListener(this);
ibPractice.setOnClickListener(this);
ibStatistic.setOnClickListener(this);
cPlus.setOnClickListener(this);
cMinus.setOnClickListener(this);
cMulti.setOnClickListener(this);
cDiv.setOnClickListener(this);
}
if (R.id.imageButton5 == v.getId() && top == 2 && difficulty > 0 && operation > 0 )
{
int[] ops = new int [operation];
ops = getoperation(ops);
Log.d("OPS", String.valueOf(ops.length));
Intent i = new Intent();
i.setClass(MainMenu.this, Test.class);
i.putExtra("Reference2", name);
i.putExtra("Difficulty", difficulty);
i.putExtra("OPstring", ops);
startActivity(i);
}
private int[] getoperation(int[] ops) {
// TODO Auto-generated method stub
int index = 0;
if (p == true)
{
ops[index] = 1;
index++;
}
if (m == true)
{
ops[index] = 2;
index++;
}
if(mu == true)
{
ops[index] = 3;
index++;
}
if (d == true)
{
ops[index] = 4;
index++;
}
return ops;
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
stopService(new Intent(MainMenu.this,SongService.class));
finish();
}
我的申请清单:
?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mathmemes"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.mathmemes.Logo"
android:label="@string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.mathmemes.StartPoint"
android:label="@string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.StartPoint" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.mathmemes.MainMenu"
android:label="@string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.MENU" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.mathmemes.Test"
android:label="@string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.TEST" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.mathmemes.Practice"
android:label="@string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.PRACTICE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.mathmemes.Statistic"
android:label="@string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.STATISTIC" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service android:enabled="true" android:name=".SongService"/>
</application>
这是我在LOGCAT上的错误异常:
06-01 10:40:43.757: W/InputManagerService(58):
Got RemoteException sending setActive(false) notification to pid 311 uid 10036
06-01 10:40:44.758: W/NotificationService(58):
Object died trying to hide notification
android.app.ITransientNotification$Stub$Proxy@45f43aa0 in package com.mathmemes
06-01 10:40:44.758: W/ActivityManager(58):
setProcessForeground called on unknown pid: 311
06-01 10:40:44.758: W/NotificationService(58):
Object died trying to show notification
android.app.ITransientNotification$Stub$Proxy@45f4d090 in package com.mathmemes
06-01 10:40:44.758: W/ActivityManager(58):
setProcessForeground called on unknown pid: 311
06-01 10:40:44.758: W/NotificationService(58):
Object died trying to show notification
android.app.ITransientNotification$Stub$Proxy@45f344d8 in package com.mathmemes
06-01 10:40:44.767: W/ActivityManager(58):
setProcessForeground called on unknown pid: 311
06-01 10:40:44.767: W/NotificationService(58):
Object died trying to show notification
android.app.ITransientNotification$Stub$Proxy@45f317f0 in package com.mathmemes
06-01 10:40:44.767: W/ActivityManager(58):
setProcessForeground called on unknown pid: 311
06-01 10:44:28.064: D/SntpClient(58):
request time failed: java.net.SocketException:
Address family not supported by protocol
06-01 10:49:28.074: D/SntpClient(58):
request time failed: java.net.SocketException:
Address family not supported by protocol
06-01 10:54:28.090: D/SntpClient(58):
request time failed: java.net.SocketException:
Address family not supported by protocol
06-01 10:59:28.130: D/SntpClient(58):
request time failed: java.net.SocketException:
Address family not supported by protocol
06-01 11:04:28.141: D/SntpClient(58):
request time failed: java.net.SocketException:
Address family not supported by protocol
06-01 10:26:28.517: E/AndroidRuntime(271): FATAL EXCEPTION: main
06-01 10:26:28.517: E/AndroidRuntime(271): java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.mathmemes/com.mathmemes.MainMenu}:
java.lang.NullPointerException
06-01 10:26:28.517: E/AndroidRuntime(271):
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
06-01 10:26:28.517: E/AndroidRuntime(271):
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-01 10:26:28.517: E/AndroidRuntime(271):
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
06-01 10:26:28.517: E/AndroidRuntime(271):
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-01 10:26:28.517: E/AndroidRuntime(271):
at android.os.Handler.dispatchMessage(Handler.java:99)
06-01 10:26:28.517: E/AndroidRuntime(271):
at android.os.Looper.loop(Looper.java:123)
06-01 10:26:28.517: E/AndroidRuntime(271):
at android.app.ActivityThread.main(ActivityThread.java:4627)
06-01 10:26:28.517: E/AndroidRuntime(271):
at java.lang.reflect.Method.invokeNative(Native Method)
06-01 10:26:28.517: E/AndroidRuntime(271):
at java.lang.reflect.Method.invoke(Method.java:521)
06-01 10:26:28.517: E/AndroidRuntime(271):
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-01 10:26:28.517: E/AndroidRuntime(271):
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-01 10:26:28.517: E/AndroidRuntime(271):
at dalvik.system.NativeStart.main(Native Method)
06-01 10:26:28.517: E/AndroidRuntime(271):
Caused by: java.lang.NullPointerException
06-01 10:26:28.517: E/AndroidRuntime(271):
at com.mathmemes.MainMenu.Initialize(MainMenu.java:55)
06-01 10:26:28.517: E/AndroidRuntime(271):
at com.mathmemes.MainMenu.onCreate(MainMenu.java:34)
06-01 10:26:28.517: E/AndroidRuntime(271):
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-01 10:26:28.517: E/AndroidRuntime(271):
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
06-01 10:26:28.517: E/AndroidRuntime(271):
... 11 more
我真的不知道为什么它不起作用我在另一个项目中尝试了类似的代码而且它起作用所以我不知道我哪里出错了。
感谢您的考虑和时间。抱歉我的英语不好。
答案 0 :(得分:1)
引起:java.lang.NullPointerException 06-01 10:26:28.517:E / AndroidRuntime(271):
在com.mathmemes.MainMenu.Initialize(MainMenu.java:55)
这些行表示NPE被抛出的位置。你还可以发布MainMenu.java的上下文代码吗?
Test类中的成员似乎没有被正确初始化,因此在执行Test.Initialize()时应该抛出NPE。你发布了Test.java的完整代码吗?
name = getIntent().getExtras().getString("Reference");
这是NPE的来源。 getIntent()返回用于启动Activity的intent用法。如果要处理从其他Activity传回的结果,则应覆盖MainMenu中的onActivityResult():
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
data 包含其他Activity的结果。可以在调用finish();
之前调用setResult()来设置它