I have a question about the progress bar. There is activity with question and answers. When user click on one of those answers. activity calls itself and generate new question with answers. In the header, I have progress bar, and the progress bar is full for N seconds. Every time the activity calls itself, the progress bar is full for N/2 seconds. I want to the progress bar to be full for N seconds, not for N/2. If you can help me, I'd be grateful. Problem is in the curiProgress function. Here is my code.
{
public class beze2 extends Activity{
String FILENAME = "HighScore";
FileOutputStream fos;
private boolean tocan = false;
private int c, progressStatus=400, id_odgovor, rezultat;
private myCountDownTimer timer;
private static int myProgress=400;
private ProgressBar progressBar;
private Handler myHandler=new Handler();
private TextView text, t;
private int[] b;
private String d, f, strin;
private ArrayList numbers;
private ArrayList<Pitanja> pitanja;
private ArrayList<Odgovor> odgovori;
private TestAdapter mDbHelper;
private Random r;
private LinearLayout ln;
LinearLayout.LayoutParams buttonParams;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getIntents();
initializeVariables();
dodajVrijednostiUb();
postaviPitanje();
postaviOdgovore();
curiProgress();
}
private void getIntents(){
Intent i = getIntent();
String reza = i.getStringExtra("REZULTAT");
strin = i.getStringExtra("EXTRA_M");
rezultat = Integer.parseInt(reza);
}
private void initializeVariables(){
progressBar=(ProgressBar)findViewById(R.id.myProgress);
text = (TextView) findViewById(R.id.vrijeme);
timer = new myCountDownTimer(20*1000,1*1000);
numbers = new ArrayList();
mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
mDbHelper.open();
pitanja = mDbHelper.getPitanje(Integer.parseInt(strin));
b = new int[pitanja.size()];
t = (TextView) findViewById(R.id.text_pitanja);
myProgress=400;
r = new Random();
progressBar.setMax(400);
ln = (LinearLayout) findViewById(R.id.layoutOdgovori);
buttonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
private void curiProgress(){
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(progressStatus>=0)
{
progressStatus=performTask();
myHandler.post(new Runnable()
{
public void run() {
progressBar.setProgress(progressStatus);
}
});
}
myHandler.post(new Runnable() {
#Override
public void run() {
progressStatus=0;
myProgress=0;
}
});
}
private int performTask()
{
try {
//---Do some task---
Thread.sleep(50);
} catch (InterruptedException e)
{
e.printStackTrace();
}
return --myProgress;
}
}).start();
}
private void dodajVrijednostiUb(){
for (int z=0;z<pitanja.size(); z++){
b[z] = pitanja.get(z).getId_pitanja();
numbers.add(b[z]);
}
}
private void postaviPitanje(){
while (!numbers.contains(c)){
c = r.nextInt(22) + 1;
}
for (int i=0;i<pitanja.size(); i++){
if (c==b[i]){
d = pitanja.get(i).getTekst_pitanja();
id_odgovor = pitanja.get(i).getOdgovor();
}
}
t.setText(d);
}
private void postaviOdgovore(){
odgovori = mDbHelper.getOdgovor(c);
for (int i = 0; i<odgovori.size(); i++){
final Button bt = new Button(this);
bt.setId(odgovori.get(i).getId_odgovor());
bt.setBackgroundResource(getResources().getIdentifier("buttoni", "drawable", getPackageName()));
final String text = odgovori.get(i).getOdgovor();
int l = odgovori.get(i).getId_odgovor();
final String s = Integer.toString(l);
bt.setText(text);
buttonParams.setMargins(20, 5, 20, 5);
bt.setLayoutParams(buttonParams);
ln.addView(bt);
bt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
f = Integer.toString(id_odgovor);
if (f.equals(s)){
tocan = true;
bt.setTextColor(Color.GREEN);
} else {
tocan = false;
bt.setTextColor(Color.RED);
Button newbutton = (Button) findViewById(id_odgovor);
newbutton.setTextColor(Color.GREEN);
}
timer.cancel();
if (tocan){
rezultat++;
timer.cancel();
Toast.makeText(beze2.this, "Tocan odgovor, vas score je " + Integer.toString(rezultat), Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), beze2.class);
i.putExtra("REZULTAT", Integer.toString(rezultat));
i.putExtra("EXTRA_M", strin);
startActivity(i);
}
else {
Toast.makeText(beze2.this, "Netocan odgovor, vas konacni score je " + Integer.toString(rezultat), Toast.LENGTH_SHORT).show();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
upisiDatoteku("Guest", rezultat);
Intent i = new Intent(beze2.this, MainActivity.class);
startActivity(i);
}
}
}
});
}
timer.start();
}
private void upisiDatoteku(String s, int rez){
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
String newOne = s + "\t" + Integer.toString(rez);
fos.write(newOne.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class myCountDownTimer extends CountDownTimer{
public myCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
text.setText("Time's up");
myHandler.post(new Runnable(){
#Override
public void run() {
try {
Thread.sleep(3000);
Intent i = new Intent(beze2.this, beze.class);
startActivity(i);
Toast.makeText(beze2.this, "Isteklo vam je vrijeme, Vas score je " + Integer.toString(rezultat), Toast.LENGTH_SHORT).show();
upisiDatoteku("Guest",rezultat);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onTick(long millisUntilFinished) {
int i = (int) millisUntilFinished / 1000;
text.setText(Integer.toString(i));
}
}
Related
I have an alarm clock application, and I've just added code to exit the program when using the Back button from the main activity. However, when I do so, the last action the user took is undone. For example, if the user creates three alarms, then presses the back button, only two alarms will show up.
This is the Back button code, from Main Activity:
#Override
public void onBackPressed() {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
And just in case, here's all the code from both activities I'm testing:
MainActivity.java (The only activity that has this Back button functionality, deliberately)
public class MainActivity extends AppCompatActivity {
ListView alarmListView;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
AlarmAdapter alarmAdapter;
String filename = "alarmList";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
alarmListView = findViewById(R.id.alarmListView);
// Credit to Mitch Woodbright for helping with this section, and other try/catch blocks.
try
{
ArrayList<Alarm> alarm = (ArrayList<Alarm>) getIntent().getSerializableExtra("alarmList");
for(Alarm elements : alarm){
alarmList.add(elements);
}
writeAlarmList(alarmList);
}
catch (NullPointerException e){
System.out.println("AlarmList is empty.");
}
try {
alarmList = readAlarmList();
}
catch (NullPointerException e) {
}
alarmAdapter = new AlarmAdapter(MainActivity.this, alarmList){
#Override
public void onUpdateClick(int position, ArrayList<Alarm> alarmList) {
super.onUpdateClick(position, alarmList);
Intent updateAlarmIntent = new Intent(MainActivity.this,
CreateAlarmActivity.class);
updateAlarmIntent.putExtra("alarmList", alarmList);
updateAlarmIntent.putExtra("position", position);
startActivity(updateAlarmIntent);
}
};
alarmListView.setAdapter(alarmAdapter);
alarmAdapter.notifyDataSetChanged();
alarmListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent updateAlarmIntent = new Intent(MainActivity.this, CreateAlarmActivity.class);
updateAlarmIntent.putExtra("alarmList", alarmList);
updateAlarmIntent.putExtra("position", position);
startActivity(updateAlarmIntent);
}
});
// writeAlarmList(alarmList);
}
protected void onStart() {
super.onStart();
alarmList = readAlarmList();
}
protected void onResume() {
super.onResume();
alarmList = readAlarmList();
}
protected void onPause() {
super.onPause();
writeAlarmList(alarmList);
}
protected void onStop() {
super.onStop();
writeAlarmList(alarmList);
}
#Override
public void onBackPressed() {
// Thanks to Mitch for this line.
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
// Create alarm when user presses FAB on activity_main.xml.
public void createNewAlarm(View view) {
Intent createAlarmIntent = new Intent(this, CreateAlarmActivity.class);
createAlarmIntent.putExtra("alarmList", alarmList);
startActivity(createAlarmIntent);
}
public void testAlarmActivated(View view){
//Intent activateAlarmIntent = new Intent(this, AlarmActivatedActivity.class);
//startActivity(activateAlarmIntent);
while(alarmList.size() > 0){
alarmList.remove(0);
}
Intent deleteEverythingIntent = new Intent(MainActivity.this, MainActivity.class);
deleteEverythingIntent.putExtra("alarmList", alarmList);
startActivity(deleteEverythingIntent);
}
public void writeAlarmList(ArrayList<Alarm> alarmList){
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(alarmList);
oos.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<Alarm> readAlarmList(){
try {
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Alarm> alarmList = (ArrayList<Alarm>) ois.readObject();
ois.close();
return alarmList;
}
catch (FileNotFoundException e) {
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
System.out.println("File not found. Making empty list.");
return alarmList;
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (NullPointerException e) {
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
System.out.println("Null pointer exception. Making empty list.");
return alarmList;
}
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
return alarmList;
}
}
CreateAlarmActivity.java (The activity which does the creating/updating/deleting of alarms)
public class CreateAlarmActivity extends AppCompatActivity {
// If the alarm is being created, position = -1.
int position = -1;
int alarmHour;
int alarmMinute;
boolean isPm;
int snoozeTimer;
int[] daysActive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_alarm);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
alarmList = (ArrayList<Alarm>)getIntent().getSerializableExtra("alarmList");
try {
// If we're updating an alarm, return the position of the alarm to update.
position = (int)getIntent().getSerializableExtra("position");
}
// Else, keep going.
catch (NullPointerException e){
}
Button hourButton = findViewById(R.id.buttonHours);
Button minuteButton = findViewById(R.id.buttonMinutes);
Button isPmButton = findViewById(R.id.buttonAmPm);
Button snoozeTimerButton = findViewById(R.id.buttonSnoozeTimer);
Button sundayButton = findViewById(R.id.buttonSunday);
Button mondayButton = findViewById(R.id.buttonMonday);
Button tuesdayButton = findViewById(R.id.buttonTuesday);
Button wednesdayButton = findViewById(R.id.buttonWednesday);
Button thursdayButton = findViewById(R.id.buttonThursday);
Button fridayButton = findViewById(R.id.buttonFriday);
Button saturdayButton = findViewById(R.id.buttonSaturday);
// If creating a new alarm, initialise data as default.
if (position == -1){
alarmHour = 6;
alarmMinute = 0;
isPm = false;
snoozeTimer = 10;
daysActive = new int[] {0, 0, 0, 0, 0, 0, 0};
}
// If updating an alarm, grab the defaults we already had.
else {
Alarm tempAlarm = alarmList.get(position);
alarmHour = tempAlarm.hour;
alarmMinute = tempAlarm.minute;
isPm = tempAlarm.isPm;
snoozeTimer = tempAlarm.snoozeTimer;
daysActive = tempAlarm.daysActive;
}
// Set buttons to what they should be.
hourButton.setText(Integer.toString(alarmHour));
snoozeTimerButton.setText(Integer.toString(snoozeTimer));
if (alarmMinute < 10){
minuteButton.setText("0" + Integer.toString(alarmMinute));
}
else {
minuteButton.setText(Integer.toString(alarmMinute));
}
if (!isPm){
isPmButton.setText("am");
}
else {
isPmButton.setText("pm");
}
setDayColor(sundayButton, daysActive[0]);
setDayColor(mondayButton, daysActive[1]);
setDayColor(tuesdayButton, daysActive[2]);
setDayColor(wednesdayButton, daysActive[3]);
setDayColor(thursdayButton, daysActive[4]);
setDayColor(fridayButton, daysActive[5]);
setDayColor(saturdayButton, daysActive[6]);
}
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
// Add one to the hour of the alarm.
public void changeHour(View view) {
Button btn = findViewById(R.id.buttonHours);
if (alarmHour == 12){
alarmHour = 0;
}
else {
alarmHour++;
}
btn.setText(Integer.toString(alarmHour));
}
// Add one to the minute of the alarm.
public void changeMinute(View view) {
Button btn = findViewById(R.id.buttonMinutes);
if (alarmMinute == 59) {
alarmMinute = 0;
}
else {
alarmMinute++;
}
if (alarmMinute < 10) {
// Ensure minute 1 becomes 01, e.g, 6:01 am.
btn.setText("0" + Integer.toString(alarmMinute));
}
else {
btn.setText(Integer.toString(alarmMinute));
}
}
public void changeAmPm(View view) {
Button btn = findViewById(R.id.buttonAmPm);
if (isPm == true) {
isPm = false;
btn.setText("am");
}
else {
isPm = true;
btn.setText("pm");
}
}
public void changeSnoozeTimer(View view) {
Button btn = findViewById(R.id.buttonSnoozeTimer);
if (snoozeTimer == 15){
snoozeTimer = 1;
}
else {
snoozeTimer++;
}
btn.setText(Integer.toString(snoozeTimer));
}
public void finishAlarm(View view){
EditText alarmName = findViewById(R.id.alarmName);
String name = alarmName.getText().toString();
Alarm alarm = new Alarm(name, alarmHour, alarmMinute, isPm, daysActive, snoozeTimer);
// If we're creating an alarm.
if (position == -1) {
try {
alarmList.add(alarm);
} catch (Exception e) {
}
}
// Else, we're updating one.
else {
try {
// Set the alarm we're updating to the new alarm.
alarmList.set(position, alarm);
} catch (Exception e) {
}
}
Intent finishAlarmIntent = new Intent(this, MainActivity.class);
finishAlarmIntent.putExtra("alarmList", alarmList);
startActivity(finishAlarmIntent);
}
public void cancelAlarm(View view){
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
public void deleteAlarm(View view) {
// If creating a new alarm, deleting is the same as cancelling.
if (position == -1) {
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
else {
// Remove the alarm.
alarmList.remove(position);
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
}
public void changeSunday(View view) {
Button btn = findViewById(R.id.buttonSunday);
daysActive[0] = switchDay(daysActive[0]);
setDayColor(btn, daysActive[0]);
}
public void changeMonday(View view) {
Button btn = findViewById(R.id.buttonMonday);
daysActive[1] = switchDay(daysActive[1]);
setDayColor(btn, daysActive[1]);
}
public void changeTuesday(View view) {
Button btn = findViewById(R.id.buttonTuesday);
daysActive[2] = switchDay(daysActive[2]);
setDayColor(btn, daysActive[2]);
}
public void changeWednesday(View view) {
Button btn = findViewById(R.id.buttonWednesday);
daysActive[3] = switchDay(daysActive[3]);
setDayColor(btn, daysActive[3]);
}
public void changeThursday(View view) {
Button btn = findViewById(R.id.buttonThursday);
daysActive[4] = switchDay(daysActive[4]);
setDayColor(btn, daysActive[4]);
}
public void changeFriday(View view) {
Button btn = findViewById(R.id.buttonFriday);
daysActive[5] = switchDay(daysActive[5]);
setDayColor(btn, daysActive[5]);
}
public void changeSaturday(View view) {
Button btn = findViewById(R.id.buttonSaturday);
daysActive[6] = switchDay(daysActive[6]);
setDayColor(btn, daysActive[6]);
}
// Helper method to switch the daysActive from 0 to 1 or from 1 to 0.
public int switchDay(int day) {
if (day == 0){
return 1;
}
return 0;
}
// Helper method to set the color of a daysActive button when updating the alarm.
public void setDayColor(Button btn, int day) {
if (day == 1) {
// Source: https://stackoverflow.com/questions/2173936/how-to-set-background-color-of-a-view
// Credit goes to EddieB for the below line.
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
} else {
// Source: https://stackoverflow.com/questions/14802354/how-to-reset-a-buttons-background-color-to-default
// Credit goes to Ivo for the below line.
btn.getBackground().clearColorFilter();
}
}
}
For people from the future:
I ended up solving this by using the following:
#Override
public void onBackPressed() {
this.finishAffinity();
}
Source: How to quit android application programmatically
Everything works fine , except for the TextView and EditText which only update at the end once the camera torch stops flashing. The program is supposed to flash in morse code(which it does)highlight the text as it get to the letter and display the current letter in morse code.
public class TextFlashActivity extends AppCompatActivity {
private TextView textView;
private String morseString;
private String text;
private String iLearnedWhatImmutableMeans;
private EditText editText;
public static HashMap morseCode;
public static Camera cam = null;
public static Camera.Parameters parameters = null;
public static Boolean isLightOn = false;
private Button button;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_flash_layout);
init();
button = (Button) findViewById(R.id.Button_flash);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
morseTextFlash();
}
});
}
#Override
protected void onPause() {
super.onPause();
cam.release();
}
private void morseTextFlash() {
text = editText.getText().toString();
Spannable WordtoSpan = new SpannableString(text);
iLearnedWhatImmutableMeans = text.toLowerCase();
for (int i = 0; i < text.length(); i++) {
WordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 0, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setText(WordtoSpan);
textView.setText((String) morseCode.get(iLearnedWhatImmutableMeans.charAt(i)));
if (iLearnedWhatImmutableMeans.charAt(i) != ' ')
morseString = (String) morseCode.get(iLearnedWhatImmutableMeans.charAt(i));
for (int j = 0; j < morseString.length(); j++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (morseString.charAt(j) == '.') {
try {
flashSwitch();
Thread.sleep(100);
flashSwitch();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
flashSwitch();
Thread.sleep(400);
flashSwitch();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
private void init() {
textView = (TextView) findViewById(R.id.TV_flash);
editText = (EditText) findViewById(R.id.ET_flash);
cam = Camera.open();
parameters = cam.getParameters();
cam.startPreview();
hashMapInit();
}
private void flashSwitch() {
if (isLightOn) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
cam.setParameters(parameters);
isLightOn = false;
} else {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cam.setParameters(parameters);
isLightOn = true;
}
}
private void hashMapInit() {
morseCode = new HashMap<Character, String>();
morseCode.put('a', ".-");
morseCode.put('b', "-...");
morseCode.put('c', "-.-");
morseCode.put('d', "-..");
morseCode.put('e', ".");
morseCode.put('f', "..-.");
morseCode.put('g', "--.");
morseCode.put('h', "....");
morseCode.put('i', "..");
morseCode.put('j', ".---");
morseCode.put('k', "-.");
morseCode.put('l', ".-..");
morseCode.put('m', "--");
morseCode.put('n', "-.");
morseCode.put('o', "---");
morseCode.put('p', ".--.");
morseCode.put('q', "--.-");
morseCode.put('r', ".-.");
morseCode.put('s', "...");
morseCode.put('t', "-");
morseCode.put('u', "..-");
morseCode.put('v', "...-");
morseCode.put('w', ".--");
morseCode.put('x', "-..-");
morseCode.put('y', "-.--");
morseCode.put('z', "--..");
morseCode.put('1', ".----");
morseCode.put('2', "..---");
morseCode.put('3', "...--");
morseCode.put('4', "....-");
morseCode.put('5', ".....");
morseCode.put('6', "-....");
morseCode.put('7', "--...");
morseCode.put('8', "---..");
morseCode.put('9', "----.");
morseCode.put('0', "-----");
}
}
Never use Thread.sleep when running on the main thread, this blocks any UI changes on the screen, and makes the app unresponsive to touch.
You can instead use the Handler that comes built-in with every View in Android, something like this:
editText.setText("hello");
editText.postDelayed(new Runnable() {
#Override
public void run() {
editText.setText("hello again");
// schedule the next change here
}
}, 1000);
Read about postDelayed here: https://developer.android.com/reference/android/view/View.html#postDelayed(java.lang.Runnable, long)
I have two threads, two handlers. From thread i check a random number and send result to handle to update ui. But i am getting the error "only the original thread that created a view hierarchy can touch its views.". I searched some articles, they tell to use handler. I am doing that, yet can not avoid the errors.
After some checking, I found that it crashes when A sends the result. In case of B, it works
Also, can i use one handler for two thread?
public class MainActivity extends Activity implements View.OnClickListener{
Button start;
TextView status_B, status_A;
Boolean isRunning;
Thread Athread, Bthread;
int a, b;
Handler a_Handler, b_Handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize variables
start = (Button) findViewById(R.id.button);
start.setOnClickListener(this);
status_B = (TextView) findViewById(R.id.textView);
status_A = (TextView) findViewById(R.id.textView1);
a_Handler = new Handler() {
public void handleMessage(Message msg)
{
int number = msg.getData().getInt("number");
String winner = msg.getData().getString("winner");
start.setEnabled(true);
isRunning = false;
status_A.setText(winner + number);
}
};
b_Handler = new Handler() {
public void handleMessage(Message msg)
{
int number = msg.getData().getInt("number");
String winner = msg.getData().getString("winner");
start.setEnabled(true);
isRunning = false;
status_B.setText(winner + number);
}
};
}
#Override
protected void onStart() {
super.onStart();
isRunning = false;
}
#Override
public void onClick(View v) {
start.setEnabled(false);
status_B.setText("Guessing...");
if (!isRunning)
{
Athread = new Thread(new Runnable() {
#Override
public void run() {
while (isRunning)
{
try
{
Athread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
a = (int) (Math.random()*1000);
System.out.println("a "+ a);
if(a%7 == 0) {
isRunning = false;
Bundle bundle = new Bundle();
bundle.putString("winner", "A");
bundle.putInt("number", a);
Message msg = a_Handler.obtainMessage();
msg.setData(bundle);
a_Handler.handleMessage(msg);
}
}
}
});
Bthread = new Thread(new Runnable() {
#Override
public void run() {
while(isRunning)
{
try
{
Bthread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
b = (int) (Math.random()*1000);
System.out.println("b "+ b);
if(b%7 == 0) {
isRunning = false;
Bundle bundle = new Bundle();
bundle.putString("winner", "B");
bundle.putInt("number", b);
Message msg = b_Handler.obtainMessage();
msg.setData(bundle);
b_Handler.sendMessage(msg);
}
}
}
});
isRunning = true;
Athread.start();
Bthread.start();
}
}
}
You need put your code to modify views on UI thread:
a_Handler = new Handler() {
public void handleMessage(Message msg)
{
final int number = msg.getData().getInt("number");
final String winner = msg.getData().getString("winner");
runOnUiThread(new Runnable() {
#Override
public void run() {
start.setEnabled(true);
status_A.setText(winner + number);
}
});
isRunning = false;
}
};
b_Handler = new Handler() {
public void handleMessage(Message msg)
{
final int number = msg.getData().getInt("number");
final String winner = msg.getData().getString("winner");
runOnUiThread(new Runnable() {
#Override
public void run() {
start.setEnabled(true);
status_B.setText(winner + number);
}
});
isRunning = false;
}
};
Back press is not responding for my app on micromax A47 and return a dialog with wait and cancel button. while on other sets its working perfectly al-right.Can you help me with my code or a link to a guide on how to implement this correctly?
Here is my code :
public class MainActivity extends Activity implements AnimationListener{
boolean running = true;
boolean isSIM1Ready;
boolean isSIM2Ready;
ProgressWheel pw_two;
TelephonyInfo telephonyInfo;
Handler updateBarHandler;
Context context;
Animation animBlink;
int progress = 0;
private WebView wvPlay;
private WebView wvPlay1;
private TextView tvWait;
private AlertDialog alert;
private DataBaseHandler bdb;
private Runnable r ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
pw_two = (ProgressWheel) findViewById(R.id.progressBarTwo);
pw_two.bringToFront();
tvWait = (TextView) findViewById(R.id.tvWait);
tvWait.setVisibility(View.GONE);
wvPlay = (WebView) findViewById(R.id.wvPlay);
wvPlay.setBackgroundColor(0xffdcffff);
wvPlay.loadUrl("file:///android_asset/progress.gif");
wvPlay.setVisibility(View.GONE);
wvPlay1 = (WebView) findViewById(R.id.wv);
wvPlay1.setBackgroundColor(0xffdcffff);
wvPlay1.loadUrl("file:///android_asset/logo.gif");
animBlink = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.blink);
animBlink.setAnimationListener(this);
telephonyInfo = TelephonyInfo.getInstance(this);
isSIM1Ready = telephonyInfo.isSIM1Ready();
isSIM2Ready = telephonyInfo.isSIM2Ready();
progress = 361;
pw_two.stopSpinning();
pw_two.resetCount();
bdb = new DataBaseHandler(MainActivity.this);
Handler mainHandler = new Handler(Looper.getMainLooper());
r = new Runnable(){
public void run(){
try{
running = true;
while(progress<361) {
pw_two.incrementProgress();
progress++;
try {
Thread.sleep(15);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
running = false;
if(running == false){
pw_two.startAnimation(animBlink);
}
}
catch(Exception e){
Log.e("Exception", "******Exception*****" +e);
}
}
};
mainHandler.post(r);
pw_two.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try{
Log.e("TAG", "***********");
if(!running) {
WindowManager manager = (WindowManager)getApplicationContext() .getSystemService(Context.WINDOW_SERVICE);
Display mDisplay = manager.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(displayMetrics);
switch(displayMetrics.densityDpi)
{
case DisplayMetrics.DENSITY_MEDIUM:
tvWait.setVisibility(View.GONE);
break;
case DisplayMetrics.DENSITY_LOW:
tvWait.setVisibility(View.GONE);
break;
case DisplayMetrics.DENSITY_HIGH:
tvWait.setVisibility(View.VISIBLE);
break;
case DisplayMetrics.DENSITY_XHIGH:
tvWait.setVisibility(View.VISIBLE);
break;
case DisplayMetrics.DENSITY_XXHIGH:
tvWait.setVisibility(View.VISIBLE);
break;
}
wvPlay.setVisibility(View.VISIBLE);
progress = 0;
pw_two.resetCount();
Thread s = new Thread(r);
s.start();
try {
Thread.sleep(300);
sendMessage();
SimpleDateFormat dfDate_day1 = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Calendar cal1 = Calendar.getInstance();
String dt1 = dfDate_day1.format(cal1.getTime());
bdb.insertButtonPresses(1, dt1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thread timer=new Thread(){
public void run(){
try
{
sleep(30000);
showAlert("Its taking time to get the activated VAS Services, please wait for few seconds ...");
}
catch(Exception e){
Log.e("Show Alert Message", "********"+e);
}
}
};
timer.start();
Thread timer1=new Thread(){
public void run(){
try
{
sleep(45000);
showAlert2();
}
catch(Exception e){
Log.e("Show Alert Message", "********"+e);
}
}
};
timer1.start();
}
catch(Exception e){
Log.e("Exception", "******Exception*****" +e);
}
}
});
}
#SuppressLint("ShowToast")
public void sendMessage()
{
SmsManager.getDefault().sendTextMessage("155223", null, "STOP", null, null);
SimpleDateFormat dfDate_day = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Calendar cal = Calendar.getInstance();
String dt = dfDate_day.format(cal.getTime());
bdb.insertSMS("Me","Your request to check activated services has been initiated ",dt,0);
TelephonyManager telephonyManager =((TelephonyManager)MainActivity.this.getSystemService(Context.TELEPHONY_SERVICE));
String operatorName = telephonyManager.getSimOperatorName();
Vector<User> vctNumber = bdb.getPhoneNumber();
String mobile = "";
for(int i = 0; i< vctNumber.size(); i++){
User usr = (User)vctNumber.elementAt(i);
mobile = usr.getNumber();
Log.v("mobile", "**********"+mobile);
}
bdb.insertMsg(mobile, "", "STOP", "", dt, operatorName, "155223", "", "", "", "");
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onAnimationEnd(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated method stub
}
private void showAlert(final String error){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
View al = inflater.inflate(R.layout.title_timeout, null);
builder.setView(al);
alert = builder.create();
alert.setCanceledOnTouchOutside(true);
if(MainActivity.this.isFinishing()){
alert.dismiss();
}else{
alert.show();
}
}
});
}
private void showAlert2(){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
View al = inflater.inflate(R.layout.title_timeout_second, null);
builder.setView(al);
alert = builder.create();
alert.setCanceledOnTouchOutside(true);
Button btnOk = (Button)al.findViewById(R.id.btnOk);
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
tvWait.setVisibility(View.GONE);
wvPlay.setVisibility(View.GONE);
progress = 361;
pw_two.stopSpinning();
pw_two.resetCount();
alert.dismiss();
}
catch(Exception e){
Log.e("MainActivity", "45000 Exception**********"+e);
}
}
});
if(MainActivity.this.isFinishing()){
alert.dismiss();
}else{
alert.show();
}
}
});
}
}
I am trying to display a multiplication table with delay. My code is working fine but I am not able to implement the delay.
Here is My code:
tableButton1 = (Button) findViewById(R.id.Button1);
tableButton1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
str = tableButton1.getText().toString();
a = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++){
sb.append(a + " x " + i + " = " + i * a+ "\n");
}
s = String.valueOf(sb);
Intent intent=new Intent(getApplicationContext(),TextViewActivity.class);
intent.putExtra("MA", s);
startActivity(intent);
}
});
//Toast.makeText(getApplicationContext(), "Hi" +ss, 222).show();
}
});
Any answer is appreciable.
Thank's in advance
Updated-code:- This code is working with help of #theLittleNaruto
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class TestActivity extends Activity{
Button tableButton1;
TextView txtView;
int value = 0;
static int count = 0;
Handler handle = new Handler();
StringBuilder sb = new StringBuilder();
Runnable r = new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "onrunnable" +sb, 222).show();
// TODO Auto-generated method stub
updateTable();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_display);
Toast.makeText(getApplicationContext(), "oncreate" , 222).show();
txtView = (TextView) findViewById(R.id.outputTXT);
tableButton1 = (Button) findViewById(R.id.seven);
tableButton1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "onclick" , 222).show();
value= Integer.parseInt(tableButton1.getText().toString());
updateTable();
}
});
}
public void updateTable(){
count+=1000;
if(count==11000){
//Toast.makeText(getApplicationContext(), "onupdate" , 222).show();
count = 0;
value=0;
handle.removeCallbacks(r);
sb.setLength(0);
}else{
sb.append(value + " x " + count/1000 + " = " + count/1000 * value+ "\n");
handle.postDelayed(r, 1000);
// Toast.makeText(getApplicationContext(), "onupdateElse" +sb, 222).show();
txtView.setText(sb);
}
}
}
Thank you all the supporters and their best try to help me
Why dont you try what the other is saying with this little effort ;)
public class TestActivity extends Activity{
int value = 0;
static int count = 0;
Handler handle = new Handler();
StringBuilder sb = new StringBuilder();
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
updateTable();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.oaot_get);
tableButton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
value= Integer.parseInt(tableButton1.getText().toString());
updateTable();
}
});
}
public void updateTable(){
count+=1000;
if(count==11000){
count = 0;
value=0;
handle.removeCallbacks(r);
sb.setLength(0);
}else{
sb.append(value + " x " + count/1000 + " = " + count/1000 * value+ "\n");
handle.postDelayed(r, 1000);
}
}
}
Try this
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
str = tableButton1.getText().toString();
a = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++){
sb.append(a + " x " + i + " = " + i * a+ "\n");
}
}, 5000);
s = String.valueOf(sb);
Intent intent=new Intent(getApplicationContext(),TextViewActivity.class);
intent.putExtra("MA", s);
startActivity(intent);
Add a handler(). Replace your onClick code with:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
str = tableButton1.getText().toString();
a = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++)
{
sb.append(a + " x " + i + " = " + i * a+ "\n");
}s=String.valueOf(sb);
Intent intent=new Intent(getApplicationContext(),TextViewActivity.class);
intent.putExtra("MA", s);
startActivity(intent);
}
}, 5000);
Repalce 5000 with the time you want it to be delayed for in milliseconds
Add a Handler that will execute your runnable:
Runnable runnable = new Runnable() {
#Override
public void run() {
str = tableButton1.getText().toString();
a = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++){
sb.append(a + " x " + i + " = " + i * a+ "\n");
//--ADDED stuff here------------------------------------------------------------
try {
//Sleep will suspend your Thread for 500 miliseconds and resumes afterwards
Thread.sleep(500);
} catch (InterruptedException e) {
Log.e("error, Thread interrupted", e);
}
}
s = String.valueOf(sb);
Intent intent=new Intent(getApplicationContext(),TextViewActivity.class);
intent.putExtra("MA", s);
startActivity(intent);
}
Handler handler = new Handler();
//this will execute your runnable after 500 milliseconds
handler.postDelayed(runnable, 500);
You can use that :
public class Scheduler {
// DATA
private OnScheduleTimeListener mListener;
private Handler mHandler;
private int mInterval; // Between each executions
private static final int DELAY = 100; // before first execution
private boolean mIsTimerRunning;
public static interface OnScheduleTimeListener {
public void onScheduleTime();
}
public Scheduler(int interval) {
super();
mInterval = interval;
mHandler = new Handler();
}
private final Runnable mRunnable = new Runnable() {
#Override
public void run() {
// Do stuff
mListener.onScheduleTime();
// Repeat
mHandler.postDelayed(mRunnable, mInterval);
}
};
public void setOnScheduleTimeListener(OnScheduleTimeListener listener) {
mListener = listener;
}
public void startTimer() {
mIsTimerRunning = true;
mHandler.postDelayed(mRunnable, DELAY);
}
public void stopTimer() {
mIsTimerRunning = false;
mHandler.removeCallbacks(mRunnable);
}
public boolean isTimerRunning() {
return mIsTimerRunning;
}
}
Now to use it :
private void startTimer() {
mScheduler = new Scheduler(INTERVAL);
mScheduler.setOnScheduleTimeListener(new OnScheduleTimeListener() {
#Override
public void onScheduleTime() {
Log.d(TAG, "update");
});
mScheduler.startTimer();
}
private void stopTimer(){
if (mScheduler != null && mScheduler.isTimerRunning()) {
mScheduler.stopTimer();
mScheduler = null;
}
}
Try this....
do {
try {
try {
response_req_sequence = SimpleHttpClient
.sendresponseSequReqRes(response_send_order);
System.out.println("response of sequence request"
+ response_req_sequence);
System.out.println(" i ma in thread");
if (response_req_sequence.trim().length() != 0) {
System.out.println("response in result of sequ"+ response_req_sequence);
break;
}
Thread.sleep(10000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO: handle exception
}
} while (response_req_sequence.trim().equalsIgnoreCase(""));
This is working fine for me. you can customize according to you.