how to get value through one class to another through intent? - java

i m new to android.i am trying to make a quiz app which has categories. i am passing different int value on click of each category i want to use that value in my Questionactivity class so that when first button is clicked only first 10 questions will run and on click of second button 10 to 20 questions will run.
package com.example.chaitanya.myquiz;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import static java.lang.Integer.parseInt;
public class QuestionActivity extends Activity {
List<Question> quesList;
int score = 0;
Random r = new Random();
Question currentQ;
TextView txtQuestion, times, scored;
Button button1, button2, button3;
CounterClass timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent2 = getIntent();
int qid = intent2.getIntExtra("qid",10);
QuizHelper db = new QuizHelper(this); // my question bank class
quesList = db.getAllQuestions(); // this will fetch all quetonall
questions
currentQ = quesList.get(qid); // the current question
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// the textview in which the question will be displayed
// the three buttons,
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
// the textview in which score will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
// method which will set the things up for our game
setQuestionView();
times.setText("00:00:30");
// A timer of 30 seconds to play for, with an interval of 1 second (1000 milliseconds)
timer = new CounterClass(30000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the anser is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
}
public void getAnswer(String AnswerString) {
Intent intent2 = getIntent();
int qid = intent2.getIntExtra("qid", 10);
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText("Score : " + score);
} else {
// if unlucky start activity and finish the game
timer.cancel();
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
// passing the int value
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
if (qid < 60) {
// if questions are not over then do this
currentQ = quesList.get(qid);
setQuestionView();
} else {
// if over do this
timer.cancel();
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
timer.cancel();
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
-
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
Random r = new Random();
Intent intent2 = getIntent();
int qid = intent2.getIntExtra("qid", 10);
switch (qid) {
case 10:
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid = (r.nextInt(10) + 1);
case 20:
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid = (r.nextInt(20) + 11);
case 30:
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid = (r.nextInt(30) + 21);
}
}
}

You need Internet permission to access network.
Add these permissions to your AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Details: https://developer.android.com/training/basics/network-ops/connecting.html

the exception is raised from null pointer, the starting intent of your activity has no extra bundle
java.lang.NullPointerException: Attempt to
invoke virtual method 'double
android.os.Bundle.getDouble(java.lang.String)' on a null
object reference
at
com.example.chaitanya.calculatornew.
MainActivity.findtheweather(MainActivity.java:27)

Related

How do I transfer data from one activity to another in Android Studio? [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 1 year ago.
I am creating a Pomodoro Timer app. It has 2 activities:
The first one is the home page.
Second is for setting a time.
I want to make a third activity with recent times
I want to create a third activity that takes the input times from the second activity and stores them in a list, but I don't know how to transfer the input-data from the second activity to the third ?
Activity 1:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button newTime = findViewById(R.id.newTime);
Button currentTime = findViewById(R.id.currentTime);
Button recents = findViewById(R.id.recentTime);
newTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent activity2Intent = new Intent(getApplicationContext(), Activity2.class);
startActivity(activity2Intent);
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
// currentTime.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent currentActivityIntent = new Intent(getApplicationContext(), currentActivity.class);
// startActivity(currentActivityIntent);
// overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
// }
// });
}
}
Activity 2:
package com.example.pomotimer;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Locale;
public class Activity2 extends AppCompatActivity {
private TextView TextViewCountdown;
private Button Button_Start_Pause;
private Button Reset;
private Button buttonSet;
private Button select_Time;
private EditText edit_Text_Input;
private CountDownTimer countDownTimer;
public long mStartTimeinMillis;
private long timeLeft = mStartTimeinMillis;
private boolean timerRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
TextViewCountdown = findViewById(R.id.textViewCount);
Button_Start_Pause = findViewById(R.id.bnStartPause);
Reset = findViewById(R.id.reset);
select_Time = findViewById(R.id.selectTime);
edit_Text_Input = findViewById(R.id.edit_Text_Input);
buttonSet = findViewById(R.id.buttonSet);
select_Time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit_Text_Input.setVisibility(View.VISIBLE);
buttonSet.setVisibility(View.VISIBLE);
buttonSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String input = edit_Text_Input.getText().toString();
if (input.length() == 0){
Toast.makeText(Activity2.this, "Field can't be empty", Toast.LENGTH_SHORT).show();
return;
}
long millisInput = Long.parseLong(input)*60000;
if (millisInput == 0){
Toast.makeText(Activity2.this, "Timer cannot be set to 0", Toast.LENGTH_SHORT).show();
return;
}
setTime(millisInput);
edit_Text_Input.setText("");
// Intent res = new Intent(getApplicationContext(), currentActivity.class);
// startActivityForResult(res, (int) millisInput, null);
}
});
}
});
Button_Start_Pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerRunning){
pauseTimer();
}
else{
startTimer();
}
}
});
Reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetTimer();
}
});
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void setTime(long milliseconds){
mStartTimeinMillis = milliseconds;
resetTimer();
}
private void startTimer(){
countDownTimer = new CountDownTimer(timeLeft,1000) {
#Override
public void onTick(long millisUntilFinished) {
// The countdown timer has an automatic method of reducing time by 1s
timeLeft = millisUntilFinished;
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
#Override
public void onFinish() {
timerRunning = false;
Button_Start_Pause.setText("Start");
Button_Start_Pause.setVisibility(View.INVISIBLE);
}
}.start();
timerRunning = true;
Button_Start_Pause.setText("pause");
}
private void pauseTimer(){
countDownTimer.cancel();
timerRunning = false;
Button_Start_Pause.setText("Start");
}
private void resetTimer(){
timeLeft = mStartTimeinMillis;
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
Button_Start_Pause.setVisibility(View.VISIBLE);
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("millisleft", timeLeft);
editor.putBoolean("timerRunning", timerRunning);
editor.apply();
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
timeLeft = prefs.getLong("millisleft",mStartTimeinMillis);
timerRunning = prefs.getBoolean("timeRunning", false);
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
}
We can pass data to another activity using Intent.
Like before startActivity we need to do:
intent.putExtra("Data", data);
and in thirdActivity onCreate we need to do
intent.getStringExtra("Data");
Inside Activity2
You can place data inside the Intent directly or you can put them in a Bundle and then put the inside the Intent. Avoid using both for consistency.
Intent activity3Intent = new Intent(getApplicationContext(), Activity3.class);
//Direct Intent approach
activity3Intent.putExtras("YOUR_STRING_KEY","YOUR_DATA");
//OR Bundle approach
Bundle bundle = new Bundle();
bundle.putString("YOUR_STRING_KEY","YOUR_DATA");
activity3Intent.putExtras(bundle);
startActivity(activity3Intent);
Inside the Activity3 class.
//if direct intent approach
String value = getIntent.getStringExtra("YOUR_STRING_KEY")
//If bundle approach was used.
String value = getIntent().getExtras().getString("YOUR_STRING_KEY");

Intent in condition doesn't work

I have tried searching for this topic but i didn't find anything that would help me, so here I am asking this.
I am a beginner so I don't understand a lot of terms and if you answer my question please try to use simple language so I could understand.
I have a condition in that the elements at same position of two lists are compared and if they aren't equal than it jumps to another activity:
if (randomColors.get(i) != userColors.get(i)) {
Intent i = new Intent( GameActivity.this, GameOverActivity.class);
startActivity(i);
}
and it displays an error in debugging that I cannot solve:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabie212.simonsays/com.gabie212.simonsays.GameOverActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Please help me, I am a beginner and I don't know what's wrong with my code because I have done exactly as they taught us in class...
Here is the complete code
I know its not the best but its a work in proggress
package com.gabie212.simonsays;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
public class GameActivity extends AppCompatActivity implements
View.OnClickListener {
private int i = 0;
private Thread t = new Thread();
private Button greenButton;
private Button redButton;
private Button blueButton;
private Button yellowButton;
private Button startButton;
private ArrayList<Integer> randomColors = new ArrayList<Integer>();
private ArrayList<Integer> userColors = new ArrayList<Integer>();
private GameManger gm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gm = new GameManger(this);
setContentView(R.layout.activity_game);
greenButton = (Button) findViewById(R.id.btnGreen);
redButton = (Button) findViewById(R.id.btnRed);
blueButton = (Button) findViewById(R.id.btnBlue);
yellowButton = (Button) findViewById(R.id.btnYellow);
startButton = (Button) findViewById(R.id.btnStart);
startButton.setOnClickListener(this);
greenButton.setOnClickListener(this);
redButton.setOnClickListener(this);
blueButton.setOnClickListener(this);
yellowButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int num;
num= gm.getColor(4);
randomColors.add(num);
android.os.Handler handler = new android.os.Handler();
//TODO if the start button is pressed multiple times simultaneously it starts the lightup loop multiple times simultaneously
if (v.getId() == startButton.getId()) {
for (i = 0; i < randomColors.size(); i++) //light up loop
{
switch (randomColors.get(i)) {
case 1:
greenButton.setBackgroundResource(R.drawable.greenlightup);
handler.postDelayed(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
greenButton.setBackgroundResource(R.drawable.green);
}
}, 2000);
break;
case 2:
redButton.setBackgroundResource(R.drawable.redlightup);
handler.postDelayed(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
redButton.setBackgroundResource(R.drawable.red);
}
}, 2000);
break;
case 3:
blueButton.setBackgroundResource(R.drawable.bluelightup);
handler.postDelayed(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
blueButton.setBackgroundResource(R.drawable.blue);
}
}, 2000);
break;
case 4:
yellowButton.setBackgroundResource(R.drawable.yellowlightup);
handler.postDelayed(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
yellowButton.setBackgroundResource(R.drawable.yellow);
}
}, 2000);
break;
}
handler.postDelayed(new Runnable()
{
public void run() {
}
}, 2000);
}
for(i=0;i<randomColors.size();i++)
{
if(v.getId()==greenButton.getId())
{
userColors.add(1);
}
else
{
if(v.getId()==redButton.getId()){
userColors.add(2);
}
else
{
if(v.getId()==blueButton.getId())
{
userColors.add(3);
}
else
{
userColors.add(4);
}
}
}
}
for(i=0;i<randomColors.size();i++)
{
if(randomColors.get(i)!=userColors.get(i))
{
Intent i = new Intent( GameActivity.this, GameOverActivity.class);
startActivity(i);
}
}
}
}
}
by the its not a simple null pointer exception, at least i don't think so because there is nothing here to be null, there is only a simple intent in an if statement
here's the code for the game over activity
package com.gabie212.simonsays;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
public class GameOverActivity extends AppCompatActivity implements View.OnClickListener {
private Button againButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_over);
againButton = (Button) findViewById(R.id.btnStart);
againButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent in = new Intent(GameOverActivity.this, GameActivity.class);
startActivity(in);
}
}
Thanks in advance.
In your GameOverActivity, on this line:
againButton = (Button) findViewById(R.id.btnStart);
Your againButton is null as you are referencing btnStart from your main activity layout (activity_game.xml). This can't be found because your GameOverActivity is using activity_game_over.xml for its layout:
setContentView(R.layout.activity_game_over);
Any views need to be defined within the activity_game_over.xml file for them to be used by the activity. You need to reference the ID of the button as defined in layout/activity_game_over.xml
againButton = (Button) findViewById(R.id.btnAgain); // Or whatver you've named it
As for your specific question as to why the Intent is not working, the Intent itself is working fine, it's just that GameOverActivity cannot start up properly due to the above issue, and therefore your app crashes.

Progress bar base on right answer

I create a simple math game and I would like to update my progress bar base on the right question answer.
Examples: every time I answer correctly to a question the progress bar should go bu 10% and so on.
public class QuestionActivity extends Activity
{
List<Question> quesList;
int score = 0;
int qid = 0;
Question currentQ;
TextView txtQuestion, times, scored;
Button button1, button2, button3;
ProgressBar pb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuizHelper db = new QuizHelper(this); // my question bank class
quesList = db.getAllQuestions(); // this will fetch all quetonall
questions
currentQ = quesList.get(qid); // the current question
// the textview in which the question will be displayed
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
//the progress bar in which progress will be displayed
pb = (ProgressBar)findViewById(R.id.progressBar);
// the three buttons,
// the idea is to set the text of three buttons with the options from
question bank
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
// the textview in which score will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
// method which will set the things up for our game
setQuestionView();
times.setText("00:02:00");
// A timer of 60 seconds to play for, with an interval of 1 second (1000
milliseconds)
CounterClass timer = new CounterClass(60000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the answer is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
setProgressBar();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
setProgressBar();
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
setProgressBar();
}
});
}
public void getAnswer(String AnswerString) {
if (currentQ.getAnswer().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText("Score : " + score);
} else {
// if unlucky start activity and finish the game
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
// passing the int value
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
if (qid < 20) {
// if questions are not over then do this
currentQ = quesList.get(qid);
setQuestionView();
} else {
// if over do this
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
}
//#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put all things together
txtQuestion.setText(currentQ.getQuestion());
button1.setText(currentQ.getOptionA());
button2.setText(currentQ.getOptionB());
button3.setText(currentQ.getOptionC());
qid++;
}
private void setProgressBar()
{
}
}
private void setProgressBar()
{
int progress=pb.getProgress();
if(progress<100)
pb.setProgress(progress+10)
}
this should do the trick, it will increase progress by 10 every time you call setProgressBar() method
First :
Set ur Progress bar limit
pb.setMax(Total Quest *10)
later in
For every Correct Answer Inc score++;
private void setProgressBar()
{
pb.setProgress(score*10);
}

Loading random Qid(questions) from database?

I want to load different questions each time. i tried the the following code but it only changes the first question randomly . all other questions come in order.
QuizHelper db = new QuizHelper(this); // my question bank class
quesList = db.getAllQuestions(); // this will fetch all quetonall questions
Random random = new Random(); currentQ = quesList.get(random.nextInt(quesList.size()));
Full code here.
public class QuestionActivity extends Activity {
List<Question> quesList;
int score = 0;
int qid = 0;
Question currentQ;
TextView txtQuestion, times, scored;
Button button1, button2, button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuizHelper db = new QuizHelper(this); // my question bank class
quesList = db.getAllQuestions(); // this will fetch all quetonall questions
Random random = new Random(); currentQ = quesList.get(random.nextInt(quesList.size()));
// currentQ = quesList.get(qid); // the current question
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// the textview in which the question will be displayed
// the three buttons,
// the idea is to set the text of three buttons with the options from question bank
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
// the textview in which score will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
// method which will set the things up for our game
setQuestionView();
times.setText("00:02:00");
// A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
CounterClass timer = new CounterClass(80000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the anser is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
}
public void getAnswer(String AnswerString) {
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText("Score : " + score);
} else {
// if unlucky start activity and finish the game
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
// passing the int value
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
if (qid < 25) {
// if questions are not over then do this
currentQ = quesList.get(qid);
setQuestionView();
} else {
// if over do this
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid++;
}
}
It is due to qid that is incremented only by 1. And using
currentQ = quesList.get(qid);
on your getAnswer(). Make your Random global then try changing the currentQ to
currentQ = quesList.get(random.nextInt(quesList.size()));
And here is how to avoid duplicate random.
[EDIT]
Ok, to make it simpler do this to avoid duplicates. Make a global int position
position = random.nextInt(quesList.size())
currentQ = quesList.get(position);
Then at the end of your setQuestion
quesList.remove(position);
There you go, questions will never repeat. Hope that helps.
currentQ = quesList.get(random.nextInt(quesList.size()));
use this insted of qid

Entered Username won't appear after App title

I'm developing a simple to do list application, where on the welcome page, you enter your name and when you click to goto your tasks (on tasks page) your username which you just entered should appear at the top of the screen (For example: "App: Username") but when I tried this it appeared as "App: null" on the welcome page and "null: null" on the tasks page. Can anyone see why? Thank you.
Welcome.java
package winfield.joe.assignment.two;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.app.ProgressDialog;
import android.widget.CheckBox;
public class Welcome extends Activity {
//global vars
private CheckBox check;
private ProgressDialog progress;
private ToggleButton toggleButton;
private RatingBar ratingBar;
private String givenTitle;
private String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
givenTitle = (String) this.getTitle();
progress = new ProgressDialog(this);
addListenerOnCheck();
addListenerOnButton();
addListenerOnRatingBar();
}
//on click CheckBox displays a toast message - CLICK!
public void addListenerOnCheck() {
check = (CheckBox) findViewById(R.id.check);
check.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("CLICK!");
Toast.makeText(Welcome.this, result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
//on click toggle button displays on/off
public void addListenerOnButton() {
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Toggle = ").append(toggleButton.getText());
Toast.makeText(Welcome.this, result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
//Give a rating - Toast appears of star rating
public void addListenerOnRatingBar() {
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
//if rating value has changed, display the current rating on a toast
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Toast.makeText(Welcome.this, String.valueOf(ratingBar.getRating()), Toast.LENGTH_SHORT).show();
}
});
}
//Onclick - go to About
public void aboutMe(View view) {
Intent intent = new Intent(Welcome.this, About.class);
startActivity(intent);
}
//Onclick - go to Tasks
public void doStuff(View view) {
this.setTitle(givenTitle + ": " + username);
Intent intent = new Intent(Welcome.this, Tasks.class);
startActivity(intent);
//ProgressBarDialog appears saying its finding yours tasks and loads to 100 and changes activity
progress.setMessage("Finding tasks...");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.show();
//Goes to 100
final int totalProgressTime = 100;
final Thread t = new Thread(){
#Override
public void run(){
//Goes from 0 to 100 in jumps of 5 until the total amount of jumps reaches 100/total progress time
int jumpTime = 0;
while(jumpTime < totalProgressTime){
try {
Thread.sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}; t.start();
}
}
Tasks.java
package winfield.joe.assignment.two;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import winfield.joe.assignment.two.database.TaskContract;
import winfield.joe.assignment.two.database.TaskDBHelper;
public class Tasks extends ListActivity {
//add required global variables
private ListAdapter listAdapter;
private TaskDBHelper helper;
private String givenTitle;
private String username;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
updateUI();
this.setTitle(givenTitle + ": " + username);
}
//add in the menu (refers to menu.xml file)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
//to get selected tasks from menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_task:
//create new alert dialog which asks you if you want to make a new task entry
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add a new task");
builder.setMessage("What do you need to do?");
final EditText inputField = new EditText(this);
builder.setView(inputField);
//if 'add' then place it into the db, update it
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Clicking add - stores data in the database
String task = inputField.getText().toString();
helper = new TaskDBHelper(Tasks.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
values.put(TaskContract.Columns.TASK,task);
db.insertWithOnConflict(TaskContract.TABLE,null,values,SQLiteDatabase.CONFLICT_IGNORE);
updateUI();
}
});
//quits out of alert dialog and goes back to the task list if 'cancel'
builder.setNegativeButton("Cancel",null);
builder.create().show();
return true;
default:
return false;
}
}
//Show database entries on the tasks page
private void updateUI() {
helper = new TaskDBHelper(Tasks.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE, new String[]{
TaskContract.Columns._ID, TaskContract.Columns.TASK
},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.task_view,
cursor,
new String[]{TaskContract.Columns.TASK},
new int[]{R.id.taskTextView},
0
);
this.setListAdapter(listAdapter);
}
//Deletes tasks (clicking done next to them)
public void onDoneButtonClick(View view) {
View v = (View) view.getParent();
TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
String task = taskTextView.getText().toString();
//This query deletes the entry associated with the id/button pressed
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
TaskContract.TABLE,
TaskContract.Columns.TASK,
task);
helper = new TaskDBHelper(Tasks.this);
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
updateUI();
}
//onClick finished method assigned to the 'Finished' button
public void finished(View view) {
//Make alert dialog box appear and give it it's title
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.alert));
// set dialog message
builder.setCancelable(false)
//Positive response = return to list (tasks page)
.setPositiveButton(getString(R.string.positive),new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to the Tasks
dialog.cancel();
}
})
//Neutral response = go to about (about page)
.setNeutralButton(getString(R.string.neutral),new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You go to About Activity
Intent intent = new Intent(Tasks.this, About.class);
startActivity(intent);
}
})
//Negative response = exit app (homescreen)
.setNegativeButton(getString(R.string.negative),new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, exit app to homescreen
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
});
//create it and show it
AlertDialog alert = builder.create();
alert.show();
}
}
Username within activity_welcome.xml
<EditText
android:ems="10"
android:hint="#+string/username"
android:id="#+id/username"
android:inputType="text"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_width="match_parent">
<requestFocus/>
</EditText>
Relevant strings from strings.xml
<string name="app_name">ForYouToDo</string>
<string name="username">Username</string>
Go to Android - Pass Data Between Two Activities get NullPointerException
A complete guide(How to pass data between two activity?)
and do in your Tasks Activity
this.setTitle(getResources().getString(R.string.app_name)+ ": " + username);

Categories

Resources