我对申请大学的测验有问题
即使在我通过正确答案后,应用程序崩溃了:Incorrect on the main activity screen
请帮帮我
我认为问题在于在活动之间或在if指令中传递变量。
我的主要活动代码:
package com.example.mariusz.qiuz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button b3;
private static final String answer_1= "Mariusz";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b3 = (Button) findViewById(R.id.answer1);
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Answer1Activity.class));
}
});
Intent intent = getIntent();
String message = intent.getStringExtra(Answer1Activity.EXTRA_MESSAGE);
if (message != null ) {
if (message == answer_1) {
TextView textView_1 = new TextView(MainActivity.this);
textView_1.setGravity(Gravity.CENTER);
textView_1.setTextSize(40);
textView_1.setText(R.string.correct);
LinearLayout activity_main = (LinearLayout)findViewById(R.id.layout);
activity_main.addView(textView_1);
} else {
TextView textView_1 = new TextView(MainActivity.this);
textView_1.setGravity(Gravity.CENTER);
textView_1.setTextSize(40);
textView_1.setText(R.string.incorrect);
LinearLayout activity_main = (LinearLayout)findViewById(R.id.layout);
activity_main.addView(textView_1);
}
}
else {
}
}
}
我的第二个活动代码:
package com.example.mariusz.qiuz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by Mariusz on 2016-03-04.
*/
public class Answer1Activity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.mariusz.quiz.MESSAGE";
Button a1;
EditText e1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.answer1);
a1 = (Button) findViewById(R.id.buttona1);
e1 = (EditText) findViewById(R.id.text1);
a1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Answer1Activity.this, MainActivity.class);
String message = e1.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
}
}
答案 0 :(得分:1)
这不是检查两个字符串的正确方法,因此请尝试替换此行
if (message == answer_1) {
。通过强>
if (message.equalsIgnoreCase(answer_1)) {
注意: 我使用了equalsIgnoreCase
,因为我认为您不需要根据给定的答案区分大小写。
答案 1 :(得分:1)
始终使用string.equals(String other)
函数来比较字符串,而不是==
运算符。
string.equals(String other)
函数检查字符串的实际内容,但==
运算符检查对象的引用是否相等。
equalsIgnoreCase
是在不考虑案例时使用的另一个函数