I'm trying to invoke an activity from the MainActivity via a button with OnClickListener
The first activity is responding and works, the second activity doesn't work and crashes the application
Please help me to find the solution
Thanks!!!
here is the code:
class Layout{
public Layout(){
btnStopWatch = (Button)findViewById(R.id.btnStopWatch);
btnTimer = (Button)findViewById(R.id.btnTimer);
}
Button btnStopWatch, btnTimer;
}
class Event{
public Event(){
l.btnStopWatch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), StopWatchActivity.class);
startActivity(i);
}
});
l.btnTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), TimerActivity.class);
startActivity(i);
}
});
}
}
Layout l; Event e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = new Layout(); e = new Event();
}}
First Activity that works:
public class StopWatchActivity extends AppCompatActivity {
class Layout{
public Layout(){
tvHours = (TextView)findViewById(R.id.tvHours);
tvMinutes = (TextView)findViewById(R.id.tvMinutes);
tvSeconds = (TextView)findViewById(R.id.tvSeconds);
tvBack = (TextView)findViewById(R.id.tvBack);
btnStartStop = (Button)findViewById(R.id.btnStartStop);
btnReset = (Button)findViewById(R.id.btnReset);
}
TextView tvHours, tvMinutes, tvSeconds, tvBack;
Button btnStartStop, btnReset;
}
class Event{
public Event(){
l.btnStartStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isStarted){
Stop();
}else {
Start();
}
}
});
l.btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Reset();
}
});
l.tvBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
}
Layout l; Event e;
boolean isStarted = false;
int sec = 0, min = 0, hour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stop_watch);
l = new Layout(); e = new Event();
}
public void Start(){
l.btnStartStop.setText("Stop");
isStarted = true;
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (isStarted){
try{
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(isStarted){
MoveTime();
}
}
});
}catch (InterruptedException e){
}
}
}
});
t.start();
}
public void MoveTime(){
sec++;
if (sec >= 59){
sec = 0;
min++;
if(min >= 59){
min = 0;
hour++;
}
}
UpdateScreen();
}
public void UpdateScreen(){
l.tvHours.setText(Format(hour));
l.tvMinutes.setText(Format(min));
l.tvSeconds.setText(Format(sec));
}
public void CleanScreen(){
l.tvHours.setText("00");
l.tvMinutes.setText("00");
l.tvSeconds.setText("00");
}
public String Format(int i){
if (i<=9){
return "0" + i;
}else{
return Integer.toString(i);
}
}
public void Stop(){
isStarted = false;
l.btnStartStop.setText("Start");
}
public void Reset(){
if(isStarted)
Stop();
CleanScreen();
sec = 0;
min = 0;
hour = 0;
}}
second activity that doesn't work:
public class TimerActivity extends AppCompatActivity {
class Layout {
public Layout() {
etHour = (EditText) findViewById(R.id.etHour);
etHour.setFilters(new InputFilter[]{new InputFilterMinMax("0", "24")});
etMin = (EditText) findViewById(R.id.etMin);
etMin.setFilters(new InputFilter[]{new InputFilterMinMax("0", "59")});
etSec = (EditText) findViewById(R.id.etSec);
etSec.setFilters(new InputFilter[]{new InputFilterMinMax("0", "59")});
btnStartStop = (Button) findViewById(R.id.btnStartStop);
btnReset = (Button) findViewById(R.id.btnReset);
tvBack1 = (TextView)findViewById(R.id.tvBack);
}
EditText etHour, etMin, etSec;
Button btnStartStop, btnReset;
TextView tvBack1;
}
class Event {
public Event() {
l.btnStartStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isStarted) {
Stop();
} else {
Start();
}
}
});
l.btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Reset();
}
});
l.tvBack1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
}
Layout l;
Event e;
boolean isStarted = false;
int sec = 0, min = 0, hour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
l = new Layout();
e = new Event();
}
public void Start() {
l.btnStartStop.setText("Stop");
isStarted = true;
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (isStarted) {
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (isStarted) {
MoveTime();
}
}
});
} catch (InterruptedException e) {
}
}
}
});
t.start();
}
public void MoveTime() {
sec = Integer.valueOf(l.etSec.getText().toString());
min = Integer.valueOf(l.etMin.getText().toString());
hour = Integer.valueOf(l.etHour.getText().toString());
sec--;
if (sec < 0) {
sec = 59;
min--;
if (min < 0) {
min = 59;
hour--;
}
}
UpdateScreen();
if (hour == 0) {
if (min == 0) {
if (sec == 0) {
Stop();
}
}
}
}
public void UpdateScreen(){
l.etHour.setText(Format(hour));
l.etMin.setText(Format(min));
l.etSec.setText(Format(sec));
}
public void CleanScreen(){
l.etHour.setText("00");
l.etMin.setText("00");
l.etSec.setText("00");
}
public String Format(int i){
if (i<=9){
return "0" + i;
}else{
return Integer.toString(i);
}
}
public void Stop(){
isStarted = false;
l.btnStartStop.setText("Start");
}
public void Reset(){
if(isStarted)
Stop();
CleanScreen();
sec = 0;
min = 0;
hour = 0;
}}
Related
My Countdown timer is working fine but when I use back press during running state of the time, my countdown timer did not stop. I have tried everything as follows but none of them is able to stop the countdown timer from running in the background. After searching the forum an applying the results from it to my project I am unable to figure out whats fault in my code. Please anyone help me out and I shall be very thankful.
public class QuizActivity extends AppCompatActivity {
private static final long COUNTDOWN_IN_MILLIS = 30000 ;
List<Questions> mQuestions;
int score = 0;
int qid = 0;
Questions currentQ;
TextView txtQuestions, textViewCountDown;
RadioButton rda, rdb, rdc;
Button btnNext;
private QuestionsViewModel questionsViewModel;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private ColorStateList textColorDefaultCd;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;
private Handler handler;
private Runnable runnable = new Runnable() {
#Override
public void run() {
takeAction();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
textViewCountDown = findViewById(R.id.text_view_countdown);
relativeLayout = (RelativeLayout)findViewById(R.id.profileLoadingScreen);
linearLayout = (LinearLayout) findViewById(R.id.linearView);
textColorDefaultCd = textViewCountDown.getTextColors();
fetchQuestions();
questionsViewModel = ViewModelProviders.of(QuizActivity.this).get(QuestionsViewModel.class);
questionsViewModel.getAllQuestions().observe(this, new Observer<List<Questions>>() {
#Override
public void onChanged(#Nullable final List<Questions> words) {
// Update the cached copy of the words in the adapter.
mQuestions = words;
//Collections.shuffle(mQuestions);
Collections.addAll(mQuestions);
}
});
}
private void fetchQuestions() {
DataServiceGenerator dataServiceGenerator = new DataServiceGenerator();
Service service = DataServiceGenerator.createService(Service.class);
Call<List<QuestionsModel>> call = service.getQuestions();
call.enqueue(new Callback<List<QuestionsModel>>() {
#Override
public void onResponse(Call<List<QuestionsModel>> call, Response<List<QuestionsModel>> response) {
if (response.isSuccessful()){
if (response != null){
List<QuestionsModel> questionsModelList = response.body();
for (int i = 0; i < questionsModelList.size(); i++){
String question = questionsModelList.get(i).getQuestion();
String answer = questionsModelList.get(i).getAnswer();
String opta = questionsModelList.get(i).getOpta();
String optb = questionsModelList.get(i).getOptb();
String optc = questionsModelList.get(i).getOptc();
Questions questions = new Questions(question, answer, opta, optb, optc);
questionsViewModel.insert(questions);
}
handler = new Handler();//add this
handler.postDelayed(runnable,3000);
/* Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
takeAction();
}
}, 3000); */
}
}else{
}
}
#Override
public void onFailure(Call<List<QuestionsModel>> call, Throwable t) {
}
});
}
private void setQuestionView()
{
txtQuestions.setText(currentQ.getQuestion());
rda.setText(currentQ.getOptA());
rdb.setText(currentQ.getOptB());
rdc.setText(currentQ.getOptC());
qid++;
}
private void startCountDown() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
timeLeftInMillis = 0;
updateCountDownText();
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}.start();
}
private void updateCountDownText() {
int minutes = (int) (timeLeftInMillis / 1000) / 60;
int seconds = (int) (timeLeftInMillis / 1000) % 60;
String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
textViewCountDown.setText(timeFormatted);
if (timeLeftInMillis < 10000) {
textViewCountDown.setTextColor(Color.RED);
} else {
textViewCountDown.setTextColor(textColorDefaultCd);
}
}
private void takeAction() {
relativeLayout.setVisibility(View.GONE);
linearLayout.setVisibility(View.VISIBLE);
textViewCountDown.setVisibility(View.VISIBLE);
timeLeftInMillis = COUNTDOWN_IN_MILLIS;
startCountDown();
currentQ = mQuestions.get(qid);
txtQuestions = (TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
btnNext=(Button)findViewById(R.id.button1);
setQuestionView();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
if (grp.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(),
"Please Select an Answer",
Toast.LENGTH_SHORT)
.show();
return;
}else{
// countDownTimer.cancel();
}
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
grp.clearCheck();
//Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getAnswer().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}else{
}
if(qid<10){
currentQ=mQuestions.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onPause() {
super.onPause();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onStop() {
super.onStop();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
public void onBackPressed() {
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
}
Try this code
#Override
public void onBackPressed() {
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
New Activity UI load but does not respond, After running onStop() which trigger submit()
List View with the checkbox is bound by a custom adapter. On touch of the Submit button, an intent is triggered which takes me to HomeActivity and onStop() method is triggered which in return call submit method. All submit method is created under a new thread which interfere with UI.
package com.example.cadur.teacher;
public class Attendace extends AppCompatActivity {
DatabaseReference dref;
ArrayList<String> list=new ArrayList<>();
ArrayList<DeatailAttandance> deatailAttandances;
private MyListAdapter myListAdapter;
private ProgressDialog pb;
String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
int pre_int,abs_int;
ListView listview;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
final String s=sp.getString("Password","");
final String s1=sp.getString("username","");
year=sp.getString("Year","");
branch=sp.getString("Branch","");
subject=sp.getString("Subject","");
final String attend="Attandence";
emailId=sp.getString("emailId","");
if (s!=null&&s!="" && s1!=null&&s1!="") {
setContentView(R.layout.activity_attendace);
deatailAttandances=new ArrayList<>();
listview = findViewById(R.id.list);
TextView detail=findViewById(R.id.lay);
detail.setText(year+" "+branch+" "+" "+subject);
pb =new ProgressDialog(Attendace.this);
pb.setTitle("Connecting Database");
pb.setMessage("Please Wait....");
pb.setCancelable(false);
pb.show();
database=FirebaseDatabase.getInstance();
myRef=database.getReference(year+"/"+branch);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()) {
try {
abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
rollno = ds.getKey().toString();
deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
listview.setAdapter(myListAdapter);
pb.dismiss();
}catch (NullPointerException e){
pb.dismiss();
Intent intent=new Intent(Attendace.this, Login.class);
startActivity(intent);
finish();
}
}
count();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
Button selectAll=findViewById(R.id.selectall);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myListAdapter.setCheck();
count();
}
});
Button submit_attan=findViewById(R.id.submit_attan);
submit_attan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(Attendace.this,HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
Button count=findViewById(R.id.count);
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
});
}else{
SharedPreferences.Editor e = sp.edit();
e.putString("Password", "");
e.putString("username", "");
e.commit();
Intent i=new Intent(Attendace.this,MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected void onStop() {
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
finish();
super.onStop();
}
public void submit(){
View parentView = null;
final Calendar calendar = Calendar.getInstance();
dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
file_name=year+"_"+branch+"_"+dat;
rollno_present=rollno_present+""+year+" "+branch+" "+subject+"\n "+dat+"\n\nList of present Students\n";
rollno_absent=rollno_absent+"\n List of absent Students\n";
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
pre_int=Integer.parseInt(pre_str);
abs_int=Integer.parseInt(abs_str);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
pre_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
rollno_present=rollno_present+"\n"+roll_str+"\n";
}else{
abs_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
rollno_absent=rollno_absent+"\n"+roll_str+"\n";
}
}
// Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
}
});
}
public void count(){
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
private View getViewByPosition(int pos, ListView listview1) {
final int firstListItemPosition = listview1.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listview1.getAdapter().getView(pos, null, listview1);
} else {
final int childIndex = pos - firstListItemPosition;
return listview1.getChildAt(childIndex);
}
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try
{
File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, file_name+".doc");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n");
writer.flush();
writer.close();
// Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Just use
submit();
instead of using
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
and remove finish()
i want to reset the seekbar to start position once the music is played and button showing "play"...The problem with the code is that the seek bar stays at the end position after its done playing the music and button still shows "pause"...
Here's my code
ekdanta.java
public class ekdanta extends AppCompatActivity implements Runnable, View.OnClickListener,SeekBar.OnSeekBarChangeListener {
TextView tv4;
Button b9, b10,but19;
int count = 0;
MediaPlayer play;
SeekBar seek_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ekdanta);
tv4 = (TextView) findViewById(R.id.textView9);
tv4.setTextSize((float)21.5);
tv4.setText(Html.fromHtml(getString(R.string.thirteen)));
b9 = (Button) findViewById(R.id.b9);
b10 = (Button) findViewById(R.id.b10);
seek_bar = (SeekBar) findViewById(R.id.seekBar);
seek_bar.setOnSeekBarChangeListener(this);
seek_bar.setEnabled(false);
but19 = (Button) findViewById(R.id.button19);
but19.setOnClickListener(this);
}
public void run() {
int currentPosition= play.getCurrentPosition();
int total = play.getDuration();
while (play!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= play.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek_bar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(but19)) {
if (play == null) {
play = MediaPlayer.create(getApplicationContext(), R.raw.ekadanta);
seek_bar.setEnabled(true);
}
if (play.isPlaying()) {
play.pause();
but19.setText("Play");
} else {
play.start();
but19.setText("Pause");
seek_bar.setMax(play.getDuration());
new Thread(this).start();
}
}
}
#Override
protected void onPause() {
if(play!=null){
play.stop();
}
super.onPause();
}
public void increase(View inc) {
count++;
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count >= 3) {
count = 3;
tv4.setTextSize(40);
}
}
public void decrease(View dec) {
count--;
if (count <= 0) {
tv4.setTextSize((float)21.5);
count = 0;
}
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count == 3) {
tv4.setTextSize(40);
}
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
try{
if(play.isPlaying()||play!=null){
if (fromUser)
play.seekTo(progress);
}
else if(play==null){
Toast.makeText(getApplicationContext(),"First Play", Toast.LENGTH_SHORT).show();
seek_bar.setProgress(0);
}
}
catch(Exception e){
Log.e("seek bar",""+e);
seek_bar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
MediaPlayer has got onCompletionListener(), you can use that. Your code with handlers is not too reliable, it would be better to refactor it.
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// do whatever you want
}
});
I'm not really experienced in app programming so the solution may be simple...
I'm making an app to show scores for a cards game and I wanted to store certain values in another class, namely Round
public class Round {
int[] score1, score2, roem1, roem2;
public void initialize(){
score1 = new int[4];
score2 = new int[4];
roem1 = new int[4];
roem2 = new int[4];
for(int i = 0; i < 4; i++){
score1[i] = 0;
score2[i] = 0;
roem1[i] = 0;
roem2[i] = 0;
}
}
public void setPoints(int game, int s1, int s2) {
score1[game] = s1;
score2[game] = s2;
}
public void setRoem(int game, int r1, int r2) {
roem1[game] = r1;
roem2[game] = r2;
}
public int getPoints1(int game){
return score1[game];
}
public int getPoints2(int game){
return score2[game];
}
public int getRoem1(int game){
return roem1[game];
}
public int getRoem2(int game){
return roem2[game];
}
}
What happens, however, when I try to create the Round object, my app crashes.
It's about the part of the code from the main class.
public class MainActivity extends AppCompatActivity {
Round[] round;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
#Override
public void run() {
round = new Round[4];
for(int i = 0; i < 4; i++){
round[i].initialize();
}
}
}).start();
}
}
What I think is that using another class in an activity crashes the app, but I don't know how to solve it.
Here is the full main activity class
public class MainActivity extends AppCompatActivity {
TextView roundNr, gameNr;
Button roundPlus, roundMinus;
Button gamePlus, gameMinus;
EditText points1, points2;
Round[] round;
String team1, team2;
int roundNumber = 1, gameNumber = 1;
int score1Total, score2Total, roem1Total, roem2Total;
int p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
#Override
public void run() {
round = new Round[4];
for(int i = 0; i < 4; i++){
round[i].initialize();
}
}
}).start();
roundNr = (TextView) findViewById(R.id.roundNr);
roundNr.setText("1");
gameNr = (TextView) findViewById(R.id.gameNr);
gameNr.setText("1");
roundPlus = (Button) findViewById(R.id.roundPlus);
roundPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
roundNumber++;
if (roundNumber <= 4) {
roundNr.setText(Integer.toString(roundNumber));
}
else {
roundNumber--;
}
}
});
roundMinus = (Button) findViewById(R.id.roundMinus);
roundMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
roundNumber--;
if (roundNumber >= 1) {
roundNr.setText(Integer.toString(roundNumber));
}
else {
roundNumber++;
}
}
});
gamePlus = (Button) findViewById(R.id.gamePlus);
gamePlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gameNumber++;
if (gameNumber <= 4) {
gameNr.setText(Integer.toString(gameNumber));
}
else {
roundNumber++;
if (roundNumber <= 4) {
roundNr.setText(Integer.toString(roundNumber));
gameNumber = 1;
gameNr.setText(Integer.toString(gameNumber));
}
else {
roundNumber--;
gameNumber--;
}
}
}
});
gameMinus = (Button) findViewById(R.id.gameMinus);
gameMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gameNumber--;
if (gameNumber >= 1) {
gameNr.setText(Integer.toString(gameNumber));
}
else {
roundNumber--;
if (roundNumber >= 1) {
roundNr.setText(Integer.toString(roundNumber));
gameNumber = 4;
gameNr.setText(Integer.toString(gameNumber));
}
else {
roundNumber++;
gameNumber++;
}
}
}
});
points1 = (EditText) findViewById(R.id.points1);
points1.setText("0");
points1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals("")){
p = Integer.parseInt(s.toString());
points2.setText(Integer.toString(162 - p));
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
points2 = (EditText) findViewById(R.id.points2);
points2.setText("0");
}
}
The problem is that you initialize round variable array, but not round items.
Here's the correct function:
public class MainActivity extends AppCompatActivity {
Round[] round;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
#Override
public void run() {
round = new Round[4];
for(int i = 0; i < 4; i++){
round[i] = new Round();
round[i].initialize();
}
}
}).start();
}
}
I also suggest to modify initialize function and make it a constructor.
So I am in the middle of a Challenge from a book I am reading. The challenge says that I do some questions at the users of the app and they should answer True or False. Also they have the option to cheat but when they gone back to the question answer must not be acceptable.
So I created a Boolean Array where I save the status of the "cheater". True if he cheats and False if he doesn't cheat. But after one full rotation of the Questions the Array is Wiped. Why is this happening? What I am doing wrong?
Here is my main code for the Quiz Activity:
public class QuizActivity extends Activity {
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mCheatButton;
private TextView mQuestionTextView;
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private static final String CHEATER_BOOLEAN = "cheat";
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true),
};
private boolean[] mCheatBank = new boolean[mQuestionBank.length];
private int mCurrentIndex = 0;
private boolean mIsCheater;
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if(mIsCheater) {
messageResId = R.string.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT)
.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
mQuestionTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
mIsCheater = mCheatBank[mCurrentIndex];
updateQuestion();
}
});
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this,CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivityForResult(i,0);
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
mIsCheater = savedInstanceState.getBoolean(CHEATER_BOOLEAN, false);
}
updateQuestion();
} // End of onCreate(Bundle) method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"onActivityResult called");
if (data == null) {
return;
}
mIsCheater = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN, false);
mCheatBank[mCurrentIndex] = mIsCheater;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
savedInstanceState.putBoolean(CHEATER_BOOLEAN, mIsCheater);
}
Edit 1: Here is the code from the other classes because someone asked.
CheatActivity Code:
public class CheatActivity extends Activity {
public static final String EXTRA_ANSWER_IS_TRUE = "com.bignerrandch.android.geoquiz.answer_is_true";
public static final String EXTRA_ANSWER_SHOWN = "com.bignerdranch.android.geoquiz.answer_shown";
private boolean mAnswerIsTrue;
private boolean mCheater;
private TextView mAnswerTextView;
private Button mShowAnswer;
private void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView)findViewById(R.id.answerTextView);
mCheater = false;
if (savedInstanceState != null) {
mCheater = savedInstanceState.getBoolean(EXTRA_ANSWER_SHOWN, false);
setAnswerShownResult(mCheater);
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
}
else {
mAnswerTextView.setText(R.string.false_button);
}
} else {
setAnswerShownResult(false);
}
mShowAnswer = (Button)findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
}
else {
mAnswerTextView.setText(R.string.false_button);
}
setAnswerShownResult(true);
mCheater = true;
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(EXTRA_ANSWER_SHOWN, mCheater);
}
}
TrueFalse Code:
public class TrueFalse{
private int mQuestion;
private boolean mTrueQuestion;
public TrueFalse(int question, boolean trueQuestion) {
mQuestion = question;
mTrueQuestion = trueQuestion;
}
public int getQuestion() {
return mQuestion;
}
public void setQuestion(int question) {
mQuestion = question;
}
public boolean isTrueQuestion() {
return mTrueQuestion;
}
public void setTrueQuestion(boolean trueQuestion) {
mTrueQuestion = trueQuestion;
}
}
It's not entirely clear what you mean by wiped. But I think your problem is that you are using a member variable to set your array values. So you are setting each element of your array to that value. So essentially the entire array will be set to what ever the final state of mIsCheater is.