Stop Watch doesn't work in background mode - android

I have a stop watch, it work right, but when i press home button or button closing bell and reopen it after some time, I see wrong time in my stop watch. Tell me please what I can do to solve this problem ?
public class Stopwatch extends Activity {
Timer mTimer;
int second_f_p = 0, second_s_p = 0, millisecond = 0;
int minute_f_p = 0, minute_s_p;
int hour_f_p = 0, hour_s_p = 0;
int numberOfLap = 0;
TextView tv;
TextView TVlap;
Button btn_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
btn_start = (Button) this.findViewById(R.id.button1);
tv = (TextView) this.findViewById(R.id.tvTime);
btn_start.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View arg0) {
btn_start.setClickable(false);
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
timerMethod();
}
}, 0, 100);
}
});
Button btn_stop = (Button) this.findViewById(R.id.button2);
btn_stop.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
btn_start.setClickable(true);
mTimer.cancel();
}
});
Button btn_reset = (Button) this.findViewById(R.id.button4);
btn_reset.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
second_f_p = 0;
second_s_p = 0;
minute_f_p = 0;
minute_s_p = 0;
millisecond = 0;
hour_f_p = 0;
hour_s_p = 0;
numberOfLap = 0;
TVlap.setText("");
tv.setText(String.valueOf(hour_f_p) + String.valueOf(hour_s_p) + ":" + String.valueOf(minute_f_p) + String.valueOf(minute_s_p) + ":" + String.valueOf(second_f_p) + String.valueOf(second_s_p) + "." + String.valueOf(millisecond));
}
});
TVlap = (TextView) this.findViewById(R.id.tvLap);
Button btn_lap = (Button) this.findViewById(R.id.button3);
btn_lap.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
numberOfLap++;
TVlap.setText(TVlap.getText() + String.valueOf(numberOfLap) + ". " + String.valueOf(hour_f_p) + String.valueOf(hour_s_p) + ":" + String.valueOf(minute_f_p) + String.valueOf(minute_s_p) + ":" + String.valueOf(second_f_p) + String.valueOf(second_s_p) + "." + String.valueOf(millisecond) + "\n");
}
});
}
private void timerMethod() {
this.runOnUiThread(doSomething);
}
private final Runnable doSomething = new Runnable() {#Override
public void run() {
millisecond++;
if (millisecond == 10) {
second_s_p++;
millisecond = 0;
}
if (second_s_p == 10) {
second_f_p++;
second_s_p = 0;
}
if (second_f_p == 6) {
minute_s_p++;
second_f_p = 0;
}
if (minute_s_p == 10) {
minute_f_p++;
minute_s_p = 0;
}
if (minute_f_p == 6) {
hour_s_p++;
minute_f_p = 0;
}
if (hour_s_p == 10) {
hour_f_p++;
hour_s_p = 0;
}
if (hour_f_p == 9 && hour_s_p == 9) {
second_f_p = 0;
second_s_p = 0;
minute_f_p = 0;
minute_s_p = 0;
hour_f_p = 0;
hour_s_p = 0;
}
tv.setText(String.valueOf(hour_f_p) + String.valueOf(hour_s_p) + ":" + String.valueOf(minute_f_p) + String.valueOf(minute_s_p) + ":" + String.valueOf(second_f_p) + String.valueOf(second_s_p) + "." + String.valueOf(millisecond));
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_stopwatch, menu);
return true;
}
}

Related

How to stop the running timer with EditText?

I'm trying to create an app that shows some questions and EditText fields in front of the each of the question for an answer with CountDownTimer, the problem I have is I'm trying to stop the running CountDownTimer on the last entered answer and save those seconds next to user's name but not sure how? I know questionTimer.cancel() would stop the timer but it has to be done on the last entered answer in last EditText.
This is the MainActivity.java file:
public class MainActivity extends AppCompatActivity {
CountDownTimer questionTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setQuestions();
timer();
}
});
}//End of create()
public void timer() {
questionTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
timer = (TextView) findViewById(R.id.timer);
timer.setText("Seconds Remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
timer.setText("Done!");
}
}.start();
}
public void setQuestions() {
ArrayList<Questions> qArrList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
ques = new Questions();
ques.setQuestion("");
qArrList.add(ques);
}
adapter = new AdapterListView(getBaseContext(), R.layout.item_listview, qArrList);
questListView.setAdapter(adapter);
}
}//End of Class
This is the AdapterListView.java file:
public class AdapterListView extends ArrayAdapter<Questions> {
Context mContext;
LayoutInflater inflater;
private ArrayList<Questions> questionsArrayList;
private Questions quesObject;
private ArrayList<String> quesList = new ArrayList<String>();
private int a, b, ab, c, d, cd, e, f, ef, g, h, gh, i, j, ij;
private ArrayList<Integer> answersList = new ArrayList<Integer>();
public AdapterListView(Context context, int resource, ArrayList<Questions> questionsArrayList) {
super(context, resource);
this.mContext = context;
this.setQuestionsArrayList(questionsArrayList);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.questionTextView = convertView.findViewById(R.id.question);
holder.editText = convertView.findViewById(R.id.ans_edit_text);
holder.imgTrue = convertView.findViewById(R.id.ans_true);
holder.imgFalse = convertView.findViewById(R.id.ans_false);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
quesObject = getQuestionsArrayList().get(position);
int count = 0;
if (position == 0) count = 1;
else if (position == 1) count = 2;
else if (position == 2) count = 3;
else if (position == 3) count = 4;
else if (position == 4) count = 5;
Random rand = new Random();
a = (rand.nextInt(15) + 1);
b = (rand.nextInt(10) + 1);
ab = a + b;
c = (rand.nextInt(15) + 1);
d = (rand.nextInt(10) + 1);
cd = c + d;
e = (rand.nextInt(15) + 1);
f = (rand.nextInt(10) + 1);
ef = e + f;
g = (rand.nextInt(15) + 1);
h = (rand.nextInt(10) + 1);
gh = g + h;
i = (rand.nextInt(15) + 1);
j = (rand.nextInt(10) + 10);
ij = i + j;
quesList.add(a + " + " + b);
quesList.add(c + " + " + d);
quesList.add(e + " + " + f);
quesList.add(g + " + " + h);
quesList.add(i + " + " + j);
getAnswersList().add(ab);
getAnswersList().add(cd);
getAnswersList().add(ef);
getAnswersList().add(gh);
getAnswersList().add(ij);
holder.questionTextView.setText("Q " + count + ": \t" + quesList.get(position));
holder.editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (holder.editText.getText().toString().trim().length() > 0) {
int inputNum = Integer.parseInt(String.valueOf(holder.editText.getText().toString().trim()));
if (getAnswersList().get(position) != inputNum) {
holder.imgFalse.setVisibility(View.VISIBLE);
holder.imgTrue.setVisibility(View.GONE);
} else {
holder.imgTrue.setVisibility(View.VISIBLE);
holder.imgFalse.setVisibility(View.GONE);
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
return convertView;
}
#Override
public int getCount() {
return getQuestionsArrayList().size();
}
static class ViewHolder {
TextView questionTextView;
EditText editText;
ImageView imgTrue, imgFalse;
}
}
I have manged to sort this out by setting an int variable against Position and calling this in MainActivity class inside the running Timer. Please see the code below.
public class MainActivity extends AppCompatActivity {
CountDownTimer questionTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setQuestions();
timer();
}
});
}//End of create()
public void timer() {
questionTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
timer = (TextView) findViewById(R.id.timer);
timer.setText("Seconds Remaining: " + millisUntilFinished / 1000);
if (adapter.getEndQuiz() == 5) {
questionTimer.cancel();
}
}
public void onFinish() {
timer.setText("Done!");
}
}.start();
}
public void setQuestions() {
ArrayList<Questions> qArrList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
ques = new Questions();
ques.setQuestion("");
qArrList.add(ques);
}
adapter = new AdapterListView(getBaseContext(), R.layout.item_listview, qArrList);
questListView.setAdapter(adapter);
}
}//End of Class
Adapter
public class AdapterListView extends ArrayAdapter<Questions> {
Context mContext;
LayoutInflater inflater;
private ArrayList<Questions> questionsArrayList;
private Questions quesObject;
private ArrayList<String> quesList = new ArrayList<String>();
private int a, b, ab, c, d, cd, e, f, ef, g, h, gh, i, j, ij;
private ArrayList<Integer> answersList = new ArrayList<Integer>();
private int endQuiz = 0;
public AdapterListView(Context context, int resource, ArrayList<Questions> questionsArrayList) {
super(context, resource);
this.mContext = context;
this.setQuestionsArrayList(questionsArrayList);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.questionTextView = convertView.findViewById(R.id.question);
holder.editText = convertView.findViewById(R.id.ans_edit_text);
holder.imgTrue = convertView.findViewById(R.id.ans_true);
holder.imgFalse = convertView.findViewById(R.id.ans_false);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
quesObject = getQuestionsArrayList().get(position);
int count = 0;
if (position == 0) count = 1;
else if (position == 1) count = 2;
else if (position == 2) count = 3;
else if (position == 3) count = 4;
else if (position == 4) count = 5;
Random rand = new Random();
a = (rand.nextInt(15) + 1);
b = (rand.nextInt(10) + 1);
ab = a + b;
c = (rand.nextInt(15) + 1);
d = (rand.nextInt(10) + 1);
cd = c + d;
e = (rand.nextInt(15) + 1);
f = (rand.nextInt(10) + 1);
ef = e + f;
g = (rand.nextInt(15) + 1);
h = (rand.nextInt(10) + 1);
gh = g + h;
i = (rand.nextInt(15) + 1);
j = (rand.nextInt(10) + 10);
ij = i + j;
quesList.add(a + " + " + b);
quesList.add(c + " + " + d);
quesList.add(e + " + " + f);
quesList.add(g + " + " + h);
quesList.add(i + " + " + j);
getAnswersList().add(ab);
getAnswersList().add(cd);
getAnswersList().add(ef);
getAnswersList().add(gh);
getAnswersList().add(ij);
holder.questionTextView.setText("Q " + count + ": \t" + quesList.get(position));
holder.editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (holder.editText.getText().toString().trim().length() > 0) {
int inputNum = Integer.parseInt(String.valueOf(holder.editText.getText().toString().trim()));
if (getAnswersList().get(position) != inputNum) {
holder.imgFalse.setVisibility(View.VISIBLE);
holder.imgTrue.setVisibility(View.GONE);
} else {
holder.imgTrue.setVisibility(View.VISIBLE);
holder.imgFalse.setVisibility(View.GONE);
}
if(position == 0) setEndQuiz(1);
else if(position == 1) setEndQuiz(2);
else if(position == 2) setEndQuiz(3);
else if(position == 3) setEndQuiz(4);
else if(position == 4) setEndQuiz(5);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
return convertView;
}
#Override
public int getCount() {
return getQuestionsArrayList().size();
}
static class ViewHolder {
TextView questionTextView;
EditText editText;
ImageView imgTrue, imgFalse;
}
}

How to randomize images in the buttons in android

I am developing a game program where I want to store images in the buttons. I want to randomize the images shown in the buttons when the users play the game again, but I don't know how to randomize the images.
public class MainActivity extends Activity {
public static final String COME_FROM = "come_from";
private int[] id_mc = new int[16];
private Integer[][] img_mc = new Integer [16][2];
private Button[] myMcs = new Button[16];
private int mc_counter = 0;
private int firstid = 0;
private int secondid = 0;
private Boolean mc_isfirst = false;
private int correctcounter = 0;
private TextView tFeedback;
private MediaPlayer mp;
private Boolean b_snd_inc, b_snd_cor;
Random r = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
initGame();
}
private void initGame() {
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences("memoryPrefs", 0);
b_snd_cor =settings.getBoolean("play_sound_when_correct", true);
b_snd_inc =settings.getBoolean("play_sound_when_incorrect", true);
mc_counter = 0;
firstid = 0;
secondid = 0;
mc_isfirst = false;
correctcounter = 0;
tFeedback = (TextView) findViewById(R.id.mc_feedback);
// setup button listeners
Button startButton = (Button) findViewById(R.id.game_menu);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startMenu();
}
});
Button settingsButton = (Button) findViewById(R.id.game_settings);
settingsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startPrefs();
}
});
// fill arrays with resources
id_mc[0] = R.id.mc0;
id_mc[1] = R.id.mc1;
id_mc[2] = R.id.mc2;
id_mc[3] = R.id.mc3;
id_mc[4] = R.id.mc4;
id_mc[5] = R.id.mc5;
id_mc[6] = R.id.mc6;
id_mc[7] = R.id.mc7;
id_mc[8] = R.id.mc8;
id_mc[9] = R.id.mc9;
id_mc[10] = R.id.mc10;
id_mc[11] = R.id.mc11;
id_mc[12] = R.id.mc12;
id_mc[13] = R.id.mc13;
id_mc[14] = R.id.mc14;
id_mc[15] = R.id.mc15;
img_mc[0][0] = R.drawable.back1;
img_mc[0][1] = R.drawable.ic_img1;
img_mc[1][0] = R.drawable.back2;
img_mc[1][1] = R.drawable.ic_img2;
img_mc[2][0] = R.drawable.back3;
img_mc[2][1] = R.drawable.ic_img3;
img_mc[3][0] = R.drawable.back4;
img_mc[3][1] = R.drawable.ic_img4;
img_mc[4][0] = R.drawable.back5;
img_mc[4][1] = R.drawable.ic_img5;
img_mc[5][0] = R.drawable.back6;
img_mc[5][1] = R.drawable.ic_img6;
img_mc[6][0] = R.drawable.back7;
img_mc[6][1] = R.drawable.ic_img7;
img_mc[7][0] = R.drawable.back8;
img_mc[7][1] = R.drawable.ic_img8;
img_mc[8][0] = R.drawable.back1;
img_mc[8][1] = R.drawable.ic_img1;
img_mc[9][0] = R.drawable.back2;
img_mc[9][1] = R.drawable.ic_img2;
img_mc[10][0] = R.drawable.back3;
img_mc[10][1] = R.drawable.ic_img3;
img_mc[11][0] = R.drawable.back4;
img_mc[11][1] = R.drawable.ic_img4;
img_mc[12][0] = R.drawable.back5;
img_mc[12][1] = R.drawable.ic_img5;
img_mc[13][0] = R.drawable.back6;
img_mc[13][1] = R.drawable.ic_img6;
img_mc[14][0] = R.drawable.back7;
img_mc[14][1] = R.drawable.ic_img7;
img_mc[15][0] = R.drawable.back8;
img_mc[15][1] = R.drawable.ic_img8;
//Collections.shuffle(Arrays.asList(img_mc));
for (int i = 0; i < 16; i++) {
try{
myMcs[i] = (Button) findViewById(id_mc[i]);
myMcs[i].setBackgroundResource(img_mc[i][0]);
myMcs[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int i = 0;
for (int n = 0; n < 16; n++) {
if (id_mc[n] == view.getId())
i = n;
}
doClickAction(view, i);
}
});
}catch(Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}}
}
private void doClickAction(View v, int i)
{
v.setBackgroundResource(img_mc[i][1]);
mc_isfirst = !mc_isfirst;
// disable all buttons
for (Button b : myMcs) {
b.setEnabled(false);
}
if (mc_isfirst) {
// turning the first card
firstid = i;
// re enable all except this one
for (Button b : myMcs) {
if (b.getId() != firstid) {
b.setEnabled(true);
}
}
} else {
// turning the second card
secondid = i;
doPlayMove();
}
}
private void doPlayMove() {
mc_counter++;
if (img_mc[firstid][1] - img_mc[secondid][1] == 0) {
//correct
if (b_snd_cor) playSound(R.raw.correct);
waiting(200);
myMcs[firstid].setVisibility(View.INVISIBLE);
myMcs[secondid].setVisibility(View.INVISIBLE);
correctcounter++;
} else {
//incorrect
if (b_snd_inc) playSound(R.raw.incorrect);
waiting(400);
}
// reenable and turn cards back
for (Button b : myMcs) {
if (b.getVisibility() != View.INVISIBLE) {
b.setEnabled(true);
b.setBackgroundResource(R.drawable.memory_back);
for (int i = 0; i < 16; i++) {
myMcs[i].setBackgroundResource(img_mc[i][0]);
}
}
}
tFeedback.setText("" + correctcounter + " / " + mc_counter);
if (correctcounter > 7) {
Intent iSc = new Intent(getApplicationContext(), Scoreboard.class);
iSc.putExtra("com.gertrietveld.memorygame.SCORE", mc_counter);
startActivity(iSc);
finish();
}
}
public void playSound(int sound) {
mp = MediaPlayer.create(this, sound);
mp.setVolume((float).5,(float).5);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
public static void waiting(int n) {
long t0, t1;
t0 = System.currentTimeMillis();
do {
t1 = System.currentTimeMillis();
} while ((t1 - t0) < (n));
}
private void startMenu() {
Intent launchMenu = new Intent(this, MenuScreen.class);
launchMenu.putExtra(COME_FROM,"PlayGame");
startActivity(launchMenu);
}
private void startPrefs() {
Intent launchPrefs = new Intent(this, Setting.class);
startActivity(launchPrefs);
}
////////////////////////////////
#Override
protected void onRestart() {
super.onRestart();
//String sender = getIntent().getExtras().getString("SENDER");
//initGame();
Toast.makeText(this, "onRestart-sender is " , Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences("memoryPrefs", 0);
b_snd_cor =settings.getBoolean("play_sound_when_correct", true);
b_snd_inc =settings.getBoolean("play_sound_when_incorrect", true);
Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
}
////////////////////////////////
}
You had the Collections.shuffle() part right, you just need to get the randomized list back into your array:
private Integer[][] img_mc = new Integer [16][2];
...
List<Integer[]> img_mc_list = new ArrayList<Integer[]>();
for (Integer[] img : img_mc) {
img_mc_list.add(img);
}
Collections.shuffle(img_mc_list);
img_mc_list.toArray(img_mc);
Or use this:
private void randomize(Integer[][] array) {
int index;
Integer[] temp;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}

Android playing video fullscreen in a new activity on button click

I'm streaming a video in my app, and it works fine.
The problem is that when I try to make it full screen (in a new activity or otherwise), the screen is blank.
I have tried doing it without starting a new activity, as suggested here:
In my main activity:
butFullScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isFS)
setContentView(R.layout.activity_full_screen_video);
else
setContentView(R.layout.activity_starting_point);
}
});
I've also tried opening it in a new activity (which I prefer):
butFullScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start fs intent
Intent myIntent = new Intent(StartingPoint.this, FullScreenVideo.class);
StartingPoint.this.startActivity(myIntent);
}
});
Where FullScreenVideo:
public class FullScreenVideo extends StartingPoint{
//private VideoView vv;
public FullScreenVideo(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen_video);
vv.start();
}
}
And activity_full_screen_video:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:background="#ff000000">
<VideoView
android:id="#+id/vv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And in my manifest:
<activity
android:name=".FullScreenVideo"
android:label="#string/app_name"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize" />
It doesn't show any error or crash, just a blank screen. Also, I'm not using the media controller, so answers without that would be appreciated :)
Edit::
StartingPoint:
public class PlayVid extends ActionBarActivity {
int play = -1;
int k;
int m = 0;
int where;
int pausePressed = 0;
int displaySub = 0;
String curSub = " ";
ArrayList<Stime> timeArray = new ArrayList<Stime>();
Button but;
Button butStop;
Button butSub;
Button butFS;
TextView subs, log;
VideoView vv;
ProgressBar pBar;
int isFS, space;
String srt = "00:00:01,478 --> 00:00:04,020\n" +
"VimeoSrtPlayer Example\n" +
"\n" +
"00:00:05,045 --> 00:00:09,545\n" +
"Support for <i>italic</i> font\n" +
"\n" +
"00:00:09,378 --> 00:00:13,745\n" +
"Support for <b>bold</b> font\n" +
"\n" +
"00:00:14,812 --> 00:00:16,144\n" +
"Multi\n" +
"Line\n" +
"Support ;)\n" +
"\n" +
"00:00:18,211 --> 00:00:21,211\n" +
"Fonts: DejaVu\n" +
"http://dejavu-fonts.org\n" +
"\n" +
"00:00:22,278 --> 00:00:25,678 \n" +
"END OF EXAMPLE FILE";
subParse sp = new subParse(this, srt);
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point);
pBar = (ProgressBar) findViewById(R.id.progressBar);
subs = (TextView) findViewById(R.id.subtitleBox);
log = (TextView) findViewById(R.id.logBox);
but = (Button) findViewById(R.id.but);
butStop = (Button) findViewById(R.id.butStop);
butSub = (Button) findViewById(R.id.butSub);
butFS = (Button) findViewById(R.id.butFS);
vv = (VideoView) findViewById(R.id.vv);
vv.setVideoPath("#string/video_link");
String[] lines = {" \n", " \n"};
sp.parseSub(srt);
subs.setText("--Click Play to start--\n--Click on SUB to view subtitles--");
final String[] sub2 = log.getText().toString().split(System.getProperty("line.separator"));
final subHelper sob = new subHelper(this, sub2);
final onPauseHelper oph = new onPauseHelper();
final fsHelper fsh = new fsHelper(this);
final playHelper ph = new playHelper();
timeArray.add(new Stime(vv.getDuration(), 0));
but.setOnClickListener(new View.OnClickListener() {
long startTime = 0, trop = 0;
int space = 0;
public void onClick(View v) {
subs.setText(curSub);
fsh.space = space;
if (fsh.isFS == 1) {
//Chill
} else if (play == 0 || play == -1) {
vv.start();
pBar.setVisibility(View.VISIBLE);
if (vv.isPlaying()) {
startTime = Calendar.getInstance().getTimeInMillis();
pBar.setVisibility(View.INVISIBLE);
//Play
if (play == -1) {
sob.setDefaults();
}
oph.putAttr(3, startTime);
but.setText("||");
but.setTextColor(Color.parseColor("#ffaaaaaa"));
if (k < m) {
play = 1;
final Handler handler = new Handler();
final Runnable run = new Runnable() {
#Override
public void run() {
if (k < m && play == 1 && fsh.isFS == 0) {
if (pausePressed == 0) {
oph.putAttr(0, Calendar.getInstance().getTimeInMillis());
} else {
oph.putAttr(0, startTime);
where--;
}
//oph.nextPressed=Calendar.getInstance().getTimeInMillis();
if (space == 0) {
space = 1;
fsh.space = space;
play = sob.subPlay(startTime, 0);
fsh.play = play;
trop = (timeArray.get(k).getTime(1) - timeArray.get(k).getTime(0));
handler.postDelayed(this, Math.abs(trop > 0 ? (trop - oph.done) : 0));
} else if (space == 1) {
space = 0;
fsh.space = space;
play = sob.subPlay(startTime, 1);
fsh.play = play;
trop = timeArray.get(k + 1).getTime(0) - timeArray.get(k).getTime(1);
handler.postDelayed(this, Math.abs(trop > 0 ? (trop - oph.done) : 0));
k++;
}
oph.putAttr(1, Calendar.getInstance().getTimeInMillis());
pausePressed = 0;
sob.pp = 0;
oph.reset();
oph.done = 0;
} else if (k >= m && fsh.isFS == 0) {
final Runnable run = new Runnable() {
#Override
public void run() {
but.setText("↻");
but.setTextColor(Color.parseColor("#ffcdcdcd"));
subs.setText("Play Again?");
handler.removeCallbacks(this);
play = -1;
fsh.play = play;
//ph.saveState(play,0,k,0,curSub,displaySub);
curSub = " ";
}
};
while (vv.isPlaying()) {
}
handler.postDelayed(run, 0);
}
}
};
if (k == 0)
handler.postDelayed(run, (timeArray.get(0).getTime(0)));
else if (k < m) handler.postDelayed(run, 0);
}
}
} else if (play == 1) {
//Pause
vv.pause();
oph.reset();
oph.putAttr(2, Calendar.getInstance().getTimeInMillis());
subs.setText(curSub);
pausePressed = 1;
oph.done = +oph.getProg();
sob.pp++;
but.setText("▶");
but.setTextColor(Color.parseColor("#ffcdcdcd"));
if (k < m) {
if (space == 0) {
space = 1;
fsh.space = space;
} else if (space == 1) {
space = 0;
fsh.space = space;
}
play = sob.subPause(oph.getAttr(2));
fsh.play = play;
}
}
}
});
butStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
vv.stopPlayback();
sob.setDefaults();
play = 0;
fsh.play = play;
but.setText("▶");
subs.setText("--Click Play to start--");
curSub = " ";
}
});
butSub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (displaySub == 0) {
displaySub = 1;
subs.setText(curSub);
butSub.setTextColor(Color.parseColor("#ffaaaaaa"));
} else if (displaySub == 1) {
displaySub = 0;
subs.setText(" ");
butSub.setTextColor(Color.parseColor("#ffcdcdcd"));
}
}
});
butFS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start fs intent
Intent myIntent = new Intent(PlayVid.this, TwoFullScreenVideo.class);
PlayVid.this.startActivity(myIntent);
}
});
}
}
FullScreenVideo:
public class FullScreenVideo extends StartingPoint {
fsHelper fsh;
onPauseHelper oph;
subHelper sob;
playHelper ph;
protected PlayVid context;
TextView subs;
Button but, butStop, butSub, butFS;
public FullScreenVideo(){}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen_video);
subs = (TextView) findViewById(R.id.subtitleBox);
but = (Button) findViewById(R.id.but);
butStop = (Button) findViewById(R.id.butStop);
butSub = (Button) findViewById(R.id.butSub);
butFS = (Button) findViewById(R.id.butFS);
vv = (VideoView) findViewById(R.id.vv);
butFS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FullScreenVideo.this.finish();
}
});
}
}

My activity won't pause when dialog is shown

I have been working on application that displays a problem and 4 possible answers. Answer correctly, and the next problem appears. A wrong answer or letting the timer run out results in a popup that tells the correct answer and that you just lost a "life". Everything works well except that when the popup appears, the countdown timer continues and generates another popup. I can't find a way to get the activity to wait for the button on the dialog to be pressed before continuing to the next problem. I have read many questions/answers here and combed through many pages on the android developers site. Any help with this problem would be greatly appreciated.
public class MainActivity extends Activity {
String problems[][] = {{},{"Q1","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q10"},
{"Q1","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q10"}};
String answers[][] = {{},{"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"},
{"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"}};
public int level;
private int lister[] = {1,1,2,3,4};
Random rand = new Random();
int holder, probcount = 0, score = 0, lives = 5;
String problem, answer1, answer2, answer3, answer4, corrAnswer, l1, l2, l3;
boolean correct = false, changeBG = false, timeup = false, nolives = false, inpopup = false;
MyCount counter;
View lv, lf1, lf2, lf3, lf4, lf5;
MediaPlayer soundright, soundwrong;
final Context context = this;
public 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.main);
lv = findViewById(R.id.quizshow);
lf1 = findViewById(R.id.Life1);
lf2 = findViewById(R.id.Life2);
lf3 = findViewById(R.id.Life3);
lf4 = findViewById(R.id.Life4);
lf5 = findViewById(R.id.Life5);
Log.v("Events","onCreate");
soundright = MediaPlayer.create(this, R.raw.correct1);
soundwrong = MediaPlayer.create(this, R.raw.correct2);
Button btnAnswer1 = (Button)findViewById(R.id.Answer1);
btnAnswer1.setOnClickListener(onAnswer1);
Button btnAnswer2 = (Button)findViewById(R.id.Answer2);
btnAnswer2.setOnClickListener(onAnswer2);
Button btnAnswer3 = (Button)findViewById(R.id.Answer3);
btnAnswer3.setOnClickListener(onAnswer3);
Button btnAnswer4 = (Button)findViewById(R.id.Answer4);
btnAnswer4.setOnClickListener(onAnswer4);
Button btnExit = (Button)findViewById(R.id.btnExit);
btnExit.setOnClickListener(onExit);
Log.v("Events","onCreate2");
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
level = 1;
doNext();
}
protected void onResume() {
Log.d("Events", "onResume");
super.onResume();
}
protected void onPause() {
Log.d("Events", "onPause");
super.onPause();
counter.cancel();
}
protected void onDestroy() {
Log.d("Events", "onDestroy");
super.onDestroy();
}
private View.OnClickListener onAnswer1=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer1");
if (lister[1] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer2=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer2");
if (lister[2] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer3=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer3");
if (lister[3] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer4=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer4");
if (lister[4] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onExit = new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onExit");
finish();
};
};
private void doNext() {
if (changeBG == true) {
l1 = getResources().getString(R.string.LevelDone1);
l2 = getResources().getString(R.string.LevelDone2)+" "+String.valueOf(level);
l3 = getResources().getString(R.string.LevelDone3);
doPopup();
changeBG = false;
level = level + 1;
score = 0;
probcount = 0;
}
Log.v("Events", "DoNext1");
probcount = probcount + 1;
lister[0] = rand.nextInt(9);
holder = rand.nextInt(3);
lister[holder+1] = lister[0];
This is where I have boring code that makes sure that the 4 answers are different.
problem = problems[level][lister[0]];
TextView pr = (TextView) findViewById(R.id.Problem);
pr.setText(problem);
answer1 = answers[level][lister[1]];
TextView a1 = (TextView) findViewById(R.id.Answer1);
a1.setText(answer1);
answer2 = answers[level][lister[2]];
TextView a2 = (TextView) findViewById(R.id.Answer2);
a2.setText(answer2);
answer3 = answers[level][lister[3]];
TextView a3 = (TextView) findViewById(R.id.Answer3);
a3.setText(answer3);
answer4 = answers[level][lister[4]];
TextView a4 = (TextView) findViewById(R.id.Answer4);
a4.setText(answer4);
corrAnswer = answers[level][lister[0]];
if (probcount < 6){
counter = new MyCount(4000, 1);
} else if (probcount < 11) {
counter = new MyCount(3000, 1);
} else if (probcount < 21) {
counter = new MyCount(2500, 1);
} else if (probcount < 31) {
counter = new MyCount(2000, 1);
} else if (probcount < 41) {
counter = new MyCount(1500, 1);
} else if (probcount < 51) {
counter = new MyCount(1000, 1);
} else {
counter = new MyCount(750, 1);
}
counter.start();
}
private void doRight() {
Log.v("Events", "DoRight");
counter.cancel();
soundright.start();
if (probcount < 6){
score = score +10;
} else if (probcount < 11) {
score = score + 20;
} else if (probcount < 21) {
score = score +30;
} else if (probcount < 31) {
score = score +40;
} else if (probcount < 41) {
score = score + 50;
} else if (probcount < 51) {
score = score + 100;
} else {
score = score + 200;
}
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
if (score > 590) {
changeBG = true;
}
doNext();
}
private void doWrong() {
Log.v("Events", "DoWrong");
counter.cancel();
soundwrong.start();
lives = lives - 1;
if (lives != 5) {
if (lives == 4) {
lf5.setVisibility(View.INVISIBLE);
} else if (lives == 3) {
lf4.setVisibility(View.INVISIBLE);
} else if (lives == 2) {
lf3.setVisibility(View.INVISIBLE);
} else if (lives == 1) {
lf2.setVisibility(View.INVISIBLE);
} else if (lives == 0) {
lf1.setVisibility(View.INVISIBLE);
nolives = true;
}
}
if (nolives) {
l1 = getResources().getString(R.string.LivesGone1);
l2 = getResources().getString(R.string.LivesGone2);
l3 = getResources().getString(R.string.LivesGone3);
} else {
if (timeup) {
l1 = getResources().getString(R.string.TimeExpired);
timeup = false;
} else {
l1 = getResources().getString(R.string.WrongChoice);
}
l2 = getResources().getString(R.string.LifeLost);
l3 = getResources().getString(R.string.CorrAnswer)+" "+corrAnswer;
}
doPopup();
if (nolives) {
score = 0;
probcount = 0;
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
lf1.setVisibility(View.VISIBLE);
lf2.setVisibility(View.VISIBLE);
lf3.setVisibility(View.VISIBLE);
lf4.setVisibility(View.VISIBLE);
lf5.setVisibility(View.VISIBLE);
nolives = false;
}
doNext();
}
private void doPopup() {
Log.v("Events", "DoPopup");
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup);
TextView ln1 = (TextView) dialog.findViewById(R.id.Line1);
TextView ln2 = (TextView) dialog.findViewById(R.id.Line2);
TextView ln3 = (TextView) dialog.findViewById(R.id.Line3);
ln1.setText(l1);
ln2.setText(l2);
ln3.setText(l3);
inpopup = true;
dialog.show();
Button dialogButton = (Button) dialog.findViewById(R.id.btnPopup);
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
inpopup = false;
dialog.dismiss();
}
});
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
timeup = true;
doWrong();
}
#Override
public void onTick(long millisUntilFinished) {
double TimeLeft = millisUntilFinished;
TextView timer1 = (TextView) findViewById(R.id.Timer);
timer1.setText(String.valueOf(TimeLeft/1000));
}
}
}
You have a repetitive loop insisde a timer...
Let say, when your timer is is finished, it will call onFinish() and you are calling doWrong() in onFinish(). and doWrong() is calling doPopUp() which will open a Dialog again.(repetitively). To avoid, maintain some flags(like boolean or int) and based on the value of the flag, you decide whether to show PopUp Dialog when timer is finished or cancel the Timer when you are dismissing Diaog...
private void doWrong() {
Log.v("Events", "DoWrong");
counter.cancel();
soundwrong.start();
lives = lives - 1;
if (lives != 5) {
if (lives == 4) {
lf5.setVisibility(View.INVISIBLE);
} else if (lives == 3) {
lf4.setVisibility(View.INVISIBLE);
} else if (lives == 2) {
lf3.setVisibility(View.INVISIBLE);
} else if (lives == 1) {
lf2.setVisibility(View.INVISIBLE);
} else if (lives == 0) {
lf1.setVisibility(View.INVISIBLE);
nolives = true;
}
}
if (nolives) {
l1 = getResources().getString(R.string.LivesGone1);
l2 = getResources().getString(R.string.LivesGone2);
l3 = getResources().getString(R.string.LivesGone3);
} else {
if (timeup) {
l1 = getResources().getString(R.string.TimeExpired);
timeup = false;
} else {
l1 = getResources().getString(R.string.WrongChoice);
}
l2 = getResources().getString(R.string.LifeLost);
l3 = getResources().getString(R.string.CorrAnswer)+" "+corrAnswer;
}
// change here
if(!timeup)
doPopup();
if (nolives) {
score = 0;
probcount = 0;
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
lf1.setVisibility(View.VISIBLE);
lf2.setVisibility(View.VISIBLE);
lf3.setVisibility(View.VISIBLE);
lf4.setVisibility(View.VISIBLE);
lf5.setVisibility(View.VISIBLE);
nolives = false;
}
doNext();
}
I'm adding this answer to be able to mark the question as answered. Please read the comment I left after the question.
Thanks to all that provide help on this site. I have gained much knowledge here.

Displaying an array of values to buttons

I have an array of 12 values and I want to display it one after the other. Initially on application run I am displaying 6 values. On the button click I want to display the other 6 values one by one.
prevbutton-> value1 value2 value3 value4 value5 value6 -> nextbutton
So on next button click it should be like this.
prevbutton-> value2 value3 value4 value5 value6 value7 -> nextbutton
This should be continued up to the 12 values, and the reverse should happen in case of prevbutton.
I have used this code but it's not working:
public void onClick(View v) {
switch (v.getId()) {
case R.id.radionextstn:
forwardtune();
break;
}
}
public void forwardtune(){
Button[] buttons = new Button[5];
buttons[0] = (Button)findViewById(R.id.radiostation1);
buttons[1] = (Button)findViewById(R.id.radiostation2);
buttons[2] = (Button)findViewById(R.id.radiostation3);
buttons[3] = (Button)findViewById(R.id.radiostation4);
buttons[4] = (Button)findViewById(R.id.radiostation5);
buttons[5] = (Button)findViewById(R.id.radiostation6);
if(currentlyDisplayingFromPosition + 6 >= arraySize)
return;
for(int i=0; i<arraySize; i++) {
buttons[i].setText("");
}
for(int i=currentlyDisplayingFromPosition; i<=currentlyDisplayingFromPosition+6; i++){
if (frequency[i] == 0.0)
buttons[i].setText("");
else
buttons[i].setText("" + frequency[0]);
}
}
I am displaying the first 6 values like this:
public void autoTune() {
Log.i("autotune", " called");
if (frequency[0] == 0.0)
station1.setText(""); // station1 is a button
else
station1.setText("" + frequency[0]); // station1 is a button
if (frequency[1] == 0.0)
station2.setText(""); // station2 is a button
else
station2.setText("" + frequency[1]); // station2 is a button
if (frequency[2] == 0.0)
station3.setText(""); // station3 is a button
else
station3.setText("" + frequency[2]); // station3 is a button
if (frequency[3] == 0.0)
station4.setText(""); // station4 is a button
else
station4.setText("" + frequency[3]); // station4 is a button
if (frequency[4] == 0.0)
station5.setText(""); // station5 is a button
else
station5.setText("" + frequency[4]); // station5 is a button
if (frequency[5] == 0.0)
station6.setText(""); // station6 is a button
else
station6.setText("" + frequency[5]); // station6 is a button
}
#Override
protected Boolean doInBackground(Context... params) {
// TODO Auto-generated method stub
Log.i("in autotune", " before freq length");
int[] freq = { 911, 943, 947, 932, 901, 964, 843, 835, 946,904,908,873 };
freqCounter = 0;
Log.i("in autotune", "after freq length : " + freq.length);
frequency = new double[freq.length];
Log.i("in autotune", "after frequency length : " + frequency.length);
for (int k = 0; k < freq.length; k++) {
Log.i("In Radio.java", "Freq : " + freq[k]);
frequency[k] = freq[k];
frequency[k] = frequency[k] / 10;
if (frequency[k] == 0.0)
break;
freqCounter++;
Log.i("In Radio.java", "Frequency : " + frequency[k]);
}
}
first error I see, you declare an array of 5 button and try to put 6 buttons :
Button[] buttons = new Button[5];
you should do:
Button[] buttons = new Button[6];
solution :
if(currentlyDisplayingFromPosition + 6 >= arraySize)
return;
for(int i=0; i<6; i++){
buttons[i].setText("" + frequency[currentlyDisplayingFromPosition+i]);
}
Modify it as per your need.
Button[] btns = new Button[8];
List<String> pages = new ArrayList<String>();
int mStart = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog_activiy);
btns[0] = (Button) findViewById(R.id.pr);
btns[1] = (Button) findViewById(R.id.b1);
btns[2] = (Button) findViewById(R.id.b2);
btns[3] = (Button) findViewById(R.id.b3);
btns[4] = (Button) findViewById(R.id.b4);
btns[5] = (Button) findViewById(R.id.b5);
btns[6] = (Button) findViewById(R.id.b6);
btns[7] = (Button) findViewById(R.id.nt);
btns[0].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rearrangeBy(-1);
}
});
btns[btns.length - 1].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rearrangeBy(1);
}
});
// setup listeners
for (int i = 1; i < btns.length - 1; i++) {
btns[i].setOnClickListener(mClickListener);
}
for (int i = 0; i < 12; i++) {
pages.add((i + 1) + "");
}
setUpButtons();
}
final View.OnClickListener mClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(DialogActiviy.this, v.getTag() + "",
Toast.LENGTH_SHORT).show();
}
};
private void rearrangeBy(int by) {
mStart += by;
setUpButtons();
}
private void setUpButtons() {
// setup previous button
btns[0].setEnabled(!(mStart == 1));
// setup next button
int end = pages.size() - btns.length + 2 + 1;
btns[btns.length - 1].setEnabled(!(mStart == end));
// setup intermediate buttons
for (int i = 1; i < btns.length - 1; i++) {
String text = (mStart + i - 1) + "";
btns[i].setText(text);
btns[i].setTag(text);
}
}

Categories

Resources