2016-06-20 8 views
0

Эй, я собираю математическую игру из учебной книги. Я задал аналогичный вопрос, и удаление, а затем переустановка андроида помогла, тот же код работал. Теперь я получил еще больше кода и не могу найти ошибку. У меня есть ощущение, что это может быть размещение моего метода setQuestion() в методе onClick GameActivity.java. Кроме того, элементы оценки и уровня не обновляются, не уверен, что это часть проблемы, но я чувствую, что код просто сбой, прежде чем он обновит их. Если выполняется (как в эмуляторе, так и на моем телефоне), пока пользователь не выберет ответ, а затем он сработает. Вот мой код:Простые ошибки приложения

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.baylamafia.snzyt.mathgamechapter2.MainActivity"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="My Math Game" 
    android:id="@+id/textView" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:textSize="30sp" /> 

<ImageView 
    android:layout_width="150dp" 
    android:layout_height="150dp" 
    android:id="@+id/imageView" 
    android:layout_below="@+id/textView" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="20dp" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Play" 
    android:id="@+id/buttonPlay" 
    android:layout_centerVertical="true" 
    android:layout_alignEnd="@+id/button2" 
    android:layout_alignStart="@+id/button2" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="High Scores" 
    android:id="@+id/button2" 
    android:layout_below="@+id/buttonPlay" 
    android:layout_centerHorizontal="true" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Quit" 
    android:id="@+id/button3" 
    android:layout_below="@+id/button2" 
    android:layout_alignStart="@+id/button2" 
    android:layout_alignEnd="@+id/button2" /> 

MainActivity.java

package com.baylamafia.snzyt.mathgamechapter2; 

import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 

public class MainActivity extends AppCompatActivity implements  View.OnClickListener{ 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Button buttonPlay = (Button)findViewById(R.id.buttonPlay); 
     buttonPlay.setOnClickListener(this); 
    } 

    @Override 
    public void onClick(View view) { 
     Intent i; 
     i = new Intent(this, GameActivity.class); 
     startActivity(i); 
    } 
} 

activity_game.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="com.baylamafia.snzyt.mathgamechapter2.GameActivity"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="2" 
    android:id="@+id/textPartA" 
    android:textSize="70sp" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentStart="true" 
    android:layout_alignBottom="@+id/textOperator" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="x" 
    android:id="@+id/textOperator" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:textSize="70sp" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="2" 
    android:id="@+id/textPartB" 
    android:textSize="70sp" 
    android:layout_alignTop="@+id/textOperator" 
    android:layout_alignParentEnd="true" 
    android:layout_alignBottom="@+id/textOperator" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="=" 
    android:id="@+id/textView2" 
    android:textIsSelectable="true" 
    android:layout_below="@+id/textOperator" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="50dp" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="3" 
    android:id="@+id/buttonChoice1" 
    android:layout_alignTop="@+id/buttonChoice2" 
    android:layout_toStartOf="@+id/buttonChoice2" 
    android:textSize="40sp" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="4" 
    android:id="@+id/buttonChoice2" 
    android:layout_alignParentBottom="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginBottom="164dp" 
    android:textSize="40sp" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="7" 
    android:id="@+id/buttonChoice3" 
    android:layout_alignTop="@+id/buttonChoice2" 
    android:layout_toEndOf="@+id/buttonChoice2" 
    android:textSize="40sp" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="Score: 999" 
    android:id="@+id/textScore" 
    android:layout_alignParentBottom="true" 
    android:layout_alignParentStart="true" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="Level: 4" 
    android:id="@+id/textLevel" 
    android:layout_alignTop="@+id/textScore" 
    android:layout_alignEnd="@+id/textPartB" /> 

GameActivity.java

package com.baylamafia.snzyt.mathgamechapter2; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

import org.w3c.dom.Text; 

import java.util.Random; 

public class GameActivity extends AppCompatActivity implements  View.OnClickListener{ 

    int correctAnswer; 
    Button buttonObjectChoice1; 
    Button buttonObjectChoice2; 
    Button buttonObjectChoice3; 
    TextView textObjectPartA; 
    TextView textObjectPartB; 
    TextView textObjectScore; 
    TextView textObjectLevel; 
    int currentScore = 0; 
    int currentLevel = 1; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_game); 

    /*here we get a working object based on either the button or TextView class and base as well 
    as link our new objects directly to the appropriate UI elements that we created previously 
    */ 

     textObjectPartA = 
       (TextView)findViewById(R.id.textPartA); 

     textObjectPartB = 
       (TextView)findViewById(R.id.textPartB); 

     buttonObjectChoice1 = 
       (Button)findViewById(R.id.buttonChoice1); 

     buttonObjectChoice2 = 
       (Button)findViewById(R.id.buttonChoice2); 

     buttonObjectChoice3 = 
       (Button)findViewById(R.id.buttonChoice3); 

     buttonObjectChoice1.setOnClickListener(this); 
     buttonObjectChoice2.setOnClickListener(this); 
     buttonObjectChoice3.setOnClickListener(this); 

     setQuestion(); 
    } 

    void setQuestion(){ 
    //generate the parts of the question 
     int numberRange = currentLevel * 3; 
     Random randInt = new Random(); 

     int partA = randInt.nextInt(numberRange); 
     partA++; 

     int partB = randInt.nextInt(numberRange); 
     partB++; 

     correctAnswer = partA * partB; 
     int wrongAnswer1 = correctAnswer-2; 
     int wrongAnswer2 = correctAnswer+2; 

     textObjectPartA.setText(""+partA); 
     textObjectPartB.setText(""+partB); 

    //set the multi choice button 

     int buttonLayout = randInt.nextInt(3); 
     switch (buttonLayout){ 

      case 0: 
       buttonObjectChoice1.setText(""+correctAnswer); 
       buttonObjectChoice2.setText(""+wrongAnswer1); 
       buttonObjectChoice3.setText(""+wrongAnswer2); 
       break; 

      case 1: 
       buttonObjectChoice1.setText(""+wrongAnswer1); 
       buttonObjectChoice2.setText(""+correctAnswer); 
       buttonObjectChoice3.setText(""+wrongAnswer2); 
       break; 

      case 2: 
       buttonObjectChoice1.setText(""+wrongAnswer1); 
       buttonObjectChoice2.setText(""+wrongAnswer2); 
       buttonObjectChoice3.setText(""+correctAnswer); 
       break; 

     } 
    } 

    void updateScoreAndLevel (int answerGiven) { 

     if(isCorrect(answerGiven)){ 
      for(int i = 1; i < currentLevel; i++){ 
       currentScore = currentScore + i; 
      } 

      currentLevel++; 

     }else{ 
      currentScore = 0; 
      currentLevel = 1; 
     } 

     textObjectScore.setText("Score: " + currentScore); 
     textObjectLevel.setText("Level: " + currentLevel); 
    } 

    boolean isCorrect(int answerGiven){ 
     boolean correctTrueOrFalse; 
     if (answerGiven == correctAnswer){ 
      Toast.makeText(getApplicationContext(), "Well done!",  Toast.LENGTH_LONG).show(); 
      correctTrueOrFalse=true; 
     }else{ 
      Toast.makeText(getApplicationContext(), "Sorry", Toast.LENGTH_LONG).show(); 
      correctTrueOrFalse=false; 
     } 

     return correctTrueOrFalse; 
    } 

    @Override 
    public void onClick(View view){ 
     int answerGiven = 0; 
     switch (view.getId()) { 

      case R.id.buttonChoice1: 
       answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText()); 
       break; 

      case R.id.buttonChoice2: 
       answerGiven = Integer.parseInt("" + buttonObjectChoice2.getText()); 
       break; 

      case R.id.buttonChoice3: 
       answerGiven = Integer.parseInt("" + buttonObjectChoice3.getText()); 
       break; 

     } 

     updateScoreAndLevel(answerGiven); 
     setQuestion(); 
    } 


} 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.baylamafia.snzyt.mathgamechapter2"> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <activity android:name=".MainActivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <activity android:name=".GameActivity"></activity> 
</application> 

+4

Пожалуйста, разместите свой crashlog. – Rockney

+0

Я понял, на самом деле. Все, что мне нужно было сделать, это переместить мой метод onClick() сразу после моего метода onCreate(). Я подумал об этом, хотя, поиграв с ним. Может кто-нибудь объяснить мне, почему это? – snzy

+0

Кроме того, мой логарифм идет по личным ограничениям для моего оригинального сообщения и комментариев, есть ли способ опубликовать его и обойти это? Может быть, ссылка на текстовый файл? – snzy

ответ

0

Не используйте getApplicationContext здесь:

Toast.makeText(getApplicationContext(), "Well done!",  Toast.LENGTH_LONG).show(); 

Используйте this использовать текущую деятельность:

Toast.makeText(this, "Well done!",  Toast.LENGTH_LONG).show(); 

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

Для начала, чтобы избавиться от всех этих посторонних ""+ они не служат никакой цели. Вы не добавляете ничего строки:

buttonObjectChoice1.setText(""+correctAnswer); 

answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText()); 

Также этот

answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText()); 

потерпит неудачу, если не правильный вход т междунар.

Кроме того, я не уверен, что вы используете это для import org.w3c.dom.Text.