2016-03-09 3 views
1

Я пытаюсь сделать приложение Android для викторины. Я пытаюсь отобразить вопросы и множественный выбор, который пользователь ошибается в другом действии. Я не знаю, как передать несколько неправильных вопросов.Как передать несколько строк в другую деятельность?

Вот мой класс java для викторины.

public class QuizActivityMarketing extends Activity{ 
private Iterator<Question> questionIterator; 
private TextView txtQuestion; 
private RadioButton rda, rdb, rdc, rdd; 
public Button butNext; 
private int qid = 0; 
private Question currentQ; 
private int score = 0; 

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

    // Define your views 
    txtQuestion = (TextView) findViewById(R.id.textView1); 
    rda = (RadioButton) findViewById(R.id.radio0); 
    rdb = (RadioButton) findViewById(R.id.radio1); 
    rdc = (RadioButton) findViewById(R.id.radio2); 
    rdd = (RadioButton) findViewById(R.id.radio3); 
    butNext = (Button) findViewById(R.id.button1); 



      //Log question and option if wrong 
      TextView question = (TextView) findViewById(R.id.textView1); 
      RadioButton optA = (RadioButton) findViewById(R.id.radio0); 
      RadioButton optB = (RadioButton) findViewById(R.id.radio1); 
      RadioButton optC = (RadioButton) findViewById(R.id.radio2); 
      RadioButton optD = (RadioButton) findViewById(R.id.radio3); 
      if (!currentQ.getANSWER().trim().equals(answer.getText())) { 
       Log.d("Current Question", ""+question.getText()); 
       Log.d("OptionA", ""+optA.getText()); 
       Log.d("OptionB", ""+optB.getText()); 
       Log.d("OptionC", "" + optC.getText()); 
       Log.d("OptionD", "" + optD.getText()); 
      } 

      // Load the next question, if there are any 
      if (questionIterator.hasNext()) { 
       currentQ = questionIterator.next(); 
       setQuestionView(currentQ); 
       qid++; 
      } 
      // Done asking questions 
      Intent intent1 = getIntent(); 
      int buttonValue = Integer.valueOf(intent1.getExtras().getString("button")); 
      if (qid > buttonValue) 
      { 

Вот мой результат класс

public class ResultActivityMarketing extends AppCompatActivity { 

    //get text view for score 
    TextView testResult = (TextView) findViewById(R.id.testResult); 
    //get score 
    Bundle extras = getIntent().getExtras(); 
    if (extras != null) { 
     int score = extras.getInt("score"); 
     int numberquestions = extras.getInt("button"); 
     testResult.setText("You got " + score + " out of " + numberquestions + " questions correct"); 
    } 
} 

} 

Вот мой XML-класс для результата деятельности.

<ScrollView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/scrollView" > 

     <FrameLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"> 

      <TextView 
      android:id="@+id/wrong_questions_result" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:textAppearance="?android:attr/textAppearanceMedium" 
      android:text="Wrong Questions" 
      android:paddingTop="10dp"/> 
      <RadioGroup 
      android:id="@+id/radioGroup1" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="0.04" > 
       <RadioButton 
       android:id="@+id/radio0" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:checked="true" 
       android:layout_marginTop="30dp" 
       android:text="RadioButton" /> 
       <RadioButton 
       android:id="@+id/radio1" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="RadioButton" /> 
       <RadioButton 
       android:id="@+id/radio2" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="RadioButton" /> 
       <RadioButton 
       android:id="@+id/radio3" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="RadioButton"/> 
      </RadioGroup> 
     </FrameLayout> 
    </ScrollView> 
</LinearLayout> 

Может кто-то, пожалуйста, помогите мне. Я был бы очень признателен. Я не знаю, как это сделать. Заранее спасибо!

+2

Вы видите много кода для такой простой проблемы. Я предлагаю похудеть на коде до самых простых вещей. [Представьте, что вы разговариваете с занятым коллегой] (http://stackoverflow.com/help/how-to-ask). В противном случае вы отпугнете всех уважаемых пользователей. –

+0

Несомненно, это звучит неплохо. Спасибо –

ответ

5

Сначала создайте переменный класс ArrayList, который будет содержать неисправные вопросы

private ArrayList<QuestionFialed> failedQuestions; 

Добавить каждый неудавшийся вопрос к объекту класса QuestionFialed, который добавляется к ArrayList failedQuestions.

if (isAnswerWrong) { 
     failedQuestions.add(new QuestionResult(questionNumber, selectedAnswer, correctAnswer)); 
    } 

Затем в конце викторины, вы можете отправить ArrayList, который содержит неисправные вопросы другой деятельности

if (isGameOver) {    
    Intent intent = new Intent(this, QuizResultActivity.class); 
     intent.putParcelableArrayListExtra("FailedResult", failedQuestions); 
     startActivity(intent); 
} 

На следующей активность странице, вы можете получить обратно ваш ArrayList, как это

ArrayList<QuestionResult> myFailedQuestions = getIntent().getParcelableArrayListExtra("FailedResult"); 

Я надеюсь, что это будет указать свой в правильном направлении

Обновление вашей конкретной потребности

Я не мог видеть весь свой код, но это, как вписать его в ваше приложение

import android.content.Intent; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.RadioButton; 
import android.widget.RadioGroup; 
import android.widget.TextView; 

import java.util.ArrayList; 

public class QuizActivityMarketing extends AppCompatActivity { 

private Iterator<Question> questionIterator; 
private TextView txtQuestion; 
private RadioButton rda, rdb, rdc, rdd; 
private RadioGroup radioGroup; 
public Button butNext; 
private int qid = 0; 
private Question currentQ; 
private int score = 0; 

// store failed questions and correct answer 
private ArrayList<QuestionFailed> failedQuestions; 

// holds currently selected user answer 
private String currentSelectedAnswer; 

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

    // create object of a ArrayList and clear the ArrayList object 
    failedQuestions = new ArrayList<QuestionFailed>(); 
    failedQuestions.clear(); 


    // Define your views 
    txtQuestion = (TextView) findViewById(R.id.textView1); 
    rda = (RadioButton) findViewById(R.id.radio0); 
    rdb = (RadioButton) findViewById(R.id.radio1); 
    rdc = (RadioButton) findViewById(R.id.radio2); 
    rdd = (RadioButton) findViewById(R.id.radio3); 

    // RadioGroup 
    // select the current RadioButton selected 
    radioGroup = (RadioGroup)findViewById(R.id.radioGroup1); 
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(RadioGroup group, int checkedId) { 
      if(checkedId == R.id.radio0){ 
       currentSelectedAnswer = (RadioButton)((RadioButton) findViewById(R.id.radio0)).getText().toString(); 
      } 
      else if(checkedId == R.id.radio1){ 
       currentSelectedAnswer = (RadioButton)((RadioButton) findViewById(R.id.radio1)).getText().toString(); 
      } 
      else if(checkedId == R.id.radio2){ 
       currentSelectedAnswer = (RadioButton)((RadioButton) findViewById(R.id.radio2)).getText().toString(); 
      } 
      else if(checkedId == R.id.radio3){ 
       currentSelectedAnswer = (RadioButton)((RadioButton) findViewById(R.id.radio3)).getText().toString(); 
      } 
      else{ 
       currentSelectedAnswer = ""; 
      } 
     } 
    }); 

    // use button event to move to next question if there is more 
    butNext = (Button) findViewById(R.id.button1); 
    butNext.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      // check if the user selected result matches correct answer or not 
      if(currentSelectedAnswer.equals(currentQ.getANSWER().trim())){ 
       // answer is correct 
      }else{ 
       //incorrect answer selected 
       // then add failed answer in the QuestionFailed object inside ArrayList 
       failedQuestions.add(new QuestionResult(qid, currentSelectedAnswer, currentQ.getANSWER())); 
      } 

      // check if there is more questions 
      if (questionIterator.hasNext()) { 
       currentQ = questionIterator.next(); 

       //Display next questions 
       setQuestionView(currentQ); 
       //increment question number 
       qid++; 
      } 
      else{ 
       // There is no question left which means that the quiz is over 
       // send the failed answer to next activity 
       Intent intent = new Intent(this, ResultActivityMarketing.class); 
       intent.putParcelableArrayListExtra("FailedResult", failedQuestions); 
       startActivity(intent); 
      } 
     } 
    }); 

    } 

} 

Класс QuestionFailed реализует Parcelable. См. Класс

import android.os.Parcel; 
import android.os.Parcelable; 

public class QuestionFailed implements Parcelable { 

private int questionId; 
private String yourAnswer; 
private String correctAnswer; 

public QuestionFailed(int questionId, String yourAnswer, String correctAnswer) { 
    this.questionId = questionId; 
    this.yourAnswer = yourAnswer; 
    this.correctAnswer = correctAnswer; 
} 

public QuestionFailed(Parcel in) { 
    questionId = in.readInt(); 
    yourAnswer = in.readString(); 
    correctAnswer = in.readString(); 
} 

public int getQuestionId() { 
    return questionId; 
} 

public String getYourAnswer() { 
    return yourAnswer; 
} 

public String getCorrectAnswer() { 
    return correctAnswer; 
} 

@Override 
public int describeContents() { 
    return 0; 
} 

@Override 
public void writeToParcel(Parcel dest, int flags) { 
    dest.writeInt(questionId); 
    dest.writeString(yourAnswer); 
    dest.writeString(correctAnswer); 
} 

public static final Parcelable.Creator CREATOR = new Parcelable.Creator<QuestionFailed>() { 
    public QuestionFailed createFromParcel(Parcel in) { 
     return new QuestionFailed(in); 
    } 

    public QuestionFailed[] newArray(int size) { 
     return new QuestionFailed[size]; 
    } 
    }; 
} 

Для получения результатов вы получите недочетное количество вопросов и используйте его для расчета счета.

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.TextView; 

import java.util.ArrayList; 

public class ResultActivityMarketing extends AppCompatActivity { 

public static final int totalQuizCount = 30; 
private ArrayList<QuestionFailed> myFailedQuestions; 

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

    myFailedQuestions = getIntent().getParcelableArrayListExtra("FailedResult"); 
    int failedCount = myFailedQuestions.size(); 

    // get the score 
    int score = 30 - failedCount;   

    // Display the result 
    TextView testResult = (TextView) findViewById(R.id.testResult); 
    testResult.setText("You got " + String.valueOf(score) + " out of " + String.valueOf(numberquestions) + " questions correct"); 
    } 
} 
+0

Это очень полезно, однако я новичок в Java. Я не совсем уверен, с чего начать. Не могли бы вы взглянуть на мой код и дать мне несколько более конкретный ответ? Я очень ценю вашу помощь –

+0

Не могли бы вы помочь мне? Это немного срочно –

+0

эй, если ваша проблема не решена, не отмечайте ее как правильный ответ. @ Pranjan –

Смежные вопросы