How can i randomize question in a quiz app - android

I made a simple quiz on Android Studio which contains 3+ questions. How to make the questions become random without duplicated. This app does not use a database. I'm new to programming so I don't know what to do about this
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView totalQuestionsTextView;
TextView questionTextView;
Button ansA,ansB,ansC,ansD;
Button submitBtn;
int score=0;
int totalQuestions = QuestionAnswer.question.length;
int currentQuestionIndex = 0;
String selectedAnswer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalQuestionsTextView = findViewById(R.id.total_questions);
questionTextView = findViewById(R.id.question);
ansA = findViewById(R.id.ans_A);
ansB = findViewById(R.id.ans_B);
ansC = findViewById(R.id.ans_C);
ansD = findViewById(R.id.ans_D);
submitBtn = findViewById(R.id.submbit_btn);
ansA.setOnClickListener(this);
ansB.setOnClickListener(this);
ansC.setOnClickListener(this);
ansD.setOnClickListener(this);
submitBtn.setOnClickListener(this);
totalQuestionsTextView.setText("Total Questions : "+totalQuestions);
loadNewQuestion();
}
#Override
public void onClick(View view) {
ansA.setBackgroundColor(Color.WHITE);
ansB.setBackgroundColor(Color.WHITE);
ansC.setBackgroundColor(Color.WHITE);
ansD.setBackgroundColor(Color.WHITE);
Button clickedButton = (Button) view;
if(clickedButton.getId()==R.id.submbit_btn){
currentQuestionIndex++;
loadNewQuestion();
}else{
//choices button clicked
selectedAnswer = clickedButton.getText().toString();
clickedButton.setBackgroundColor(Color.MAGENTA);
}
}
void loadNewQuestion(){
if(currentQuestionIndex == totalQuestions){
finishQuiz();
return;
}
questionTextView.setText(QuestionAnswer.question[currentQuestionIndex]);
ansA.setText(QuestionAnswer.choices[currentQuestionIndex][0]);
ansB.setText(QuestionAnswer.choices[currentQuestionIndex][1]);
ansC.setText(QuestionAnswer.choices[currentQuestionIndex][2]);
ansD.setText(QuestionAnswer.choices[currentQuestionIndex][3]);
}
void finishQuiz(){
String passStatus = "";
if (score > totalQuestions*0.60){
passStatus = "Passes";
}else{
passStatus = "Failed";
}
new AlertDialog.Builder(this)
.setTitle(passStatus)
.setMessage("Score is "+score+" out of "+ totalQuestions)
.setPositiveButton("Restart",(dialogInterface, i) -> restartQuiz())
.setCancelable(false)
.show();
}
void restartQuiz(){
score = 0;
currentQuestionIndex = 0;
loadNewQuestion();
}
QuestionAnswer.java
import java.util.Arrays; import java.util.List; import java.util.Random;
public class QuestionAnswer {
public static String[] question = {
"Which company own the android?",
"Which one is not the programming language?",
"Where are you watching this video"
};
public static String choices[][] = {
{"Google", "Apple", "Nokia", "Samsung"},
{"Java", "Kotlin", "Notepad", "Python"},
{"Facebook", "Whatsapp", "Instagram", "Youtube"},
};
public static String correctAnswers[] = {
"Google",
"Notepad",
"Youtube"
};
}
how can i add shuffle.collection or random to make my app show random question instead

You need to find out about Random class first in Java. Thereafter, you will create a random number using Random class in onClick function, then set a question's index to your Random number

Related

java.lang.NullPointerException: Attempt to invoke virtual method android studio [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
i have problem with my android studio i want to passing data with parcel but it cant cause i get this message if i click my list view always get force close, how to fix it?
error
package com.example.moviee;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class MovieDetail extends AppCompatActivity {
String txt_name;
String txt_deskripsi;
int foto;
public static final String EXTRA_MOVIE = "text_extra_movie";
TextView tvName, txt_detail;
ImageView imgposter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
tvName = findViewById(R.id.text_ph);
txt_detail = findViewById(R.id.txt_deksrip);
imgposter = findViewById(R.id.img_poster);
ArrayList<Film> film = new ArrayList<>();
film = this.getIntent().getParcelableArrayListExtra(EXTRA_MOVIE);
txt_name = film.get(0).getNama();
tvName.setText(txt_name);
txt_deskripsi = film.get(0).getDeskripsi();
txt_detail.setText(txt_deskripsi);
foto = film.get(0).getFilm();
imgposter.setImageResource(foto);
}
}
movieDetail.java
package com.example.moviee;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private FilmAdapter adapter;
private String[] dataNama;
private String[] dataDeskrip;
private TypedArray dataPhoto;
private ArrayList<Film> filmed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new FilmAdapter(this);
ListView listView = findViewById(R.id.lv_list);
listView.setAdapter(adapter);
prepare();
addItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this, MovieDetail.class);
ArrayList<Film> movies = new ArrayList<Film>();
Film movie = new Film();
movie.setFilm(dataPhoto.getResourceId(i, -1));
movie.setNama(dataNama[i]);
movie.setDeskripsi(dataDeskrip[i]);
movies.add(movie);
intent.putParcelableArrayListExtra(MovieDetail.EXTRA_MOVIE, movies);
startActivity(intent);
}
});
}
#Override
public void onClick(View v) {
}
private void addItem(){
ArrayList<Film> films = new ArrayList<>();
for (int i = 0; i < dataNama.length; i++){
Film film = new Film();
film.setFilm(dataPhoto.getResourceId(i, -1));
film.setNama(dataNama[i]);
film.setDeskripsi(dataDeskrip[i]);
films.add(film);
}
adapter.setFilms(films);
}
private void prepare(){
dataNama = getResources().getStringArray(R.array.data_film);
dataDeskrip = getResources().getStringArray(R.array.data_deskripsi);
dataPhoto = getResources().obtainTypedArray(R.array.data_foto);
}
}
mainactivity.java
You need to initialize the ArrayList<> first.
ArrayList<Film> film = new ArrayList<>();
film = this.getIntent().getParcelableArrayListExtra(EXTRA_MOVIE);
Then you can access it's value
txt_name = film.get(0).getName();
tvName.setText(txt_name);

If statement depending on the random image shown

I have a imageview that randomly generate 1 out of 2 possibles images clicking on one button.
I want that when one image is showed (R.drawable.aa) and I press other button, a toast is shown.
My problem is that once a random image is shown and click on the other button, nothing happens.
package com.example.isaiasalarcon.menu;
import java.util.Random;
import java.util.jar.Attributes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import static com.example.isaiasalarcon.menu.R.drawable.aa;
public class buho extends Activity {
// UI components
private Button drawButton;
private Button boton2;
private ImageView cardImage;
// Random object
private final static Random random = new Random();
// The card deck
private final static int[] cardDeck = new int[] {
R.drawable.aa,
R.drawable.a2,
};
private Integer q;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buho);
drawButton = (Button)findViewById(R.id.drawButton);
boton2 = (Button)findViewById(R.id.button2);
cardImage = (ImageView)findViewById(R.id.cardImage);
drawButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0)
{
Integer q = cardDeck[random.nextInt(cardDeck.length)];
cardImage.setImageResource(q);
}
});
boton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (q.equals(R.drawable.aa)) {
Toast toast = Toast.makeText(buho.this, "si", Toast.LENGTH_LONG);
toast.show();
} else {
Toast toast = Toast.makeText(buho.this, "no", Toast.LENGTH_LONG);
toast.show();
}
}
});
}
}
two things:
1) Integer q I don't see a reason why this needs to be an Integer. You should be able to int
2) your q inside the onClick is creating a NEW variable called q. You need to update your code to the following: (note how it doesn't have the Type declaration before it, so it means to use the previously declared variable)
drawButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0)
{
q = cardDeck[random.nextInt(cardDeck.length)];
cardImage.setImageResource(q);
}
});

Closing Android Game After 5 Seconds

I'm tring to build an simple android game.
Users answer the questions, when the answer is correct, it is continue..
I want to add time control for each answer.
I tried to add handler function, but I didn't.
My Code;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class EasyGameActivity extends Activity {
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_easygame);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finishScreen();
}
}, 5000);
startGame();
}
private void startGame() {
// TODO Auto-generated method stub
Button b1 = (Button)findViewById(R.id.answer_one);
Button b2 = (Button)findViewById(R.id.answer_two);
Button b3 = (Button)findViewById(R.id.answer_three);
Button b4 = (Button)findViewById(R.id.answer_four);
Random number = new Random();
int first = number.nextInt(100)+1;
int second = number.nextInt(100)+1;
int answer = first + second;
int rnd1 = answer + 1;
int rnd2 = answer + 2;
int rnd3 = answer - 1;
final String a = Integer.toString(answer);
String b = Integer.toString(rnd1);
String c = Integer.toString(rnd2);
String d = Integer.toString(rnd3);
((TextView) findViewById(R.id.display)).setText(Integer.toString(first) + '+' + Integer.toString(second));
List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
List<String> texts = Arrays.asList(a, b, c, d);
Collections.shuffle(texts);
int i = 0;
OnClickListener onClick = new OnClickListener() {
public void onClick(View view) {
Button button = (Button) view;
String value = (String) button.getText();
if(value == a) {
checkTrue();
} else {
finishScreen();
}
}
};
for(Button button : buttons) {
button.setText(texts.get(i++));
button.setOnClickListener(onClick);
}
}
private void checkTrue() {
score++;
((TextView) findViewById(R.id.score)).setText(Integer.toString(score));
startGame();
}
private void finishScreen() {
score = 0;
startActivity (new Intent("com.bsinternet.mathfast.RESTARTGAMESCREEN"));
finish();
}
}
How can I add time control. Thanks.
This bit of code doesn't look right
if(value == a) {
checkTrue();
} else {
finishScreen();
}
You should be using equals() to check for String equality. At the moment you are checking only object equality, which will evaluate to False, and the code will never call checkTrue().
Do this instead:
if(value.equals(a) {
checkTrue();
} else {
finishScreen();
}

LinkedList toArray causes crash

Everytime I tried to run these code the program crashed then I tried to get an Array of Objects from my LinkedList.
Product[] arr = (Product[])produktliste.toArray(); causes the crash
This is the source of the MainActivity:
package at.lamprechtdominik.myfirstlistapp;
import java.util.LinkedList;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
public static LinkedList<Product> produktliste = new LinkedList<Product>();
private Button benutzerAnlegen;
private Button listeAnzeigen;
private EditText nameProdukt;
private EditText preisProdukt;
private CheckBox istVorhanden;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
benutzerAnlegen = (Button) findViewById(R.id.btBenutzerAnlegen);
nameProdukt = (EditText) findViewById(R.id.etProduktname);
preisProdukt = (EditText) findViewById(R.id.etPreis);
istVorhanden = (CheckBox) findViewById(R.id.cbProduktVorhanden);
listeAnzeigen = (Button) findViewById(R.id.btZeigeListe);
benutzerAnlegen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
produktliste.add(neuesProduktAnlegen());
Toast.makeText(getBaseContext(), R.string.anlegen_erfolgreich, Toast.LENGTH_LONG).show();
}
});
listeAnzeigen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Intent i = new Intent(getBaseContext(), Produktauflistung.class);
//startActivity(i);
Product[] arr = (Product[])produktliste.toArray();
}
});
}
private Product neuesProduktAnlegen(){
String name = nameProdukt.toString();
Double preis = Double.parseDouble(preisProdukt.getText().toString());
boolean vorhanden;
if(istVorhanden.isChecked()){
vorhanden = true;
} else {
vorhanden = false;
}
Product neuesProdukt = new Product(name, preis , vorhanden);
return(neuesProdukt);
}
}
class file Product:
package at.lamprechtdominik.myfirstlistapp;
public class Product {
private String name;
private Double preis;
private boolean istVorhanden;
public Product(String name, Double preis, boolean istVorhanden){
this.name = name;
this.preis = preis;
this.istVorhanden = istVorhanden;
}
public String getName(){
return(name);
}
public Double getPreis(){
return(preis);
}
public boolean getIstVorhanden(){
return(istVorhanden);
}
}
Does anyone know how what i did wrong?
Thanks for your help.
You cannot simply cast the result of toArray() to a Product[] array.
Use this:
Product[] meineProdukte = new Product(produktliste.size());
meineProdukte = produktliste.toArray(meineProdukte);
Try to change to
Product[] arr = produktliste.toArray(new Product[produktliste.size()]);

Factorial program in android

Hey guys I know there are many java programs for the factorial of a number...but I am facing problem with android. Following is my code....Thanks
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
public class AptiFactorial extends Activity implements android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;
long factorial = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
calcFactorial();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private void calcFactorial() {
if (number.getText().toString().equals("")) number.setText("0");
int num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
#Override
public void onClick(View v) {
calcFactorial();
answer.setText("Factorial of " + number.getText().toString() + " is : " + factorial);
}
}
This is my code and I need to know a way around for setting the hint instead of 0, but if I remove if (number.getText().toString().equals("")) number.setText("0");
then getting NullPointerException...
Also on the first go its calculating correctly but If I calculate again then getting wrong answer. I think some loop issue because I am directly using the value of factorial.
Please help thanks
Forget all that equal stuff, cover all basis and do it like this:
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
public class AptiFactorial extends Activity implements android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
number.setHint("Enter number to be factorialized :P")
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private long calcFactorial() {
long factorial = 1;
try {
factorial = Long.parseLong(number.getText().toString());
for(int i=factorial-1; i>0; i--){
factorial = i * factorial;
}
} catch (NumberFormatException e) {
Toast.makeText(this, "Incorrect Input", Toast.LENGTH_LONG).show();
} finally {}
return factorial;
}
#Override
public void onClick(View v) {
answer.setText("Factorial of " + number.getText().toString() + " is : " + calcFactorial());
}
Do something like.
private void calcFactorial() {
int num = 0;
if (!number.getText().toString().equals(""))
num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
Rather than using
(number.getText().toString().equals("")) number.setText("0");
Use
(number.getText().length==0) number.setText("0");
** first go its calculating correctly but If I calculate again then getting wrong answer**
try like this
private void calcFactorial() {
factorial = 1;///Check out the line..
int num = 0;
if (!number.getText().toString().equals(""))
num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
You need to make sure variable factorial is reinitialise to 1 .. for getting factorial for next number..
private void fact_isClicked(View view) {
if(textField.length()>0){
int ifac = Integer.parseInt(textField.getText().toString());
int fact = factorial(ifac);
tvsec.setText(String.valueOf(fact));
textField.setText(ifac+"!");
}}

Categories

Resources