i am trying to disable the save button for exactly 1 hour, before the user can save data again. I have come up with some code but since i am still really new to programming i am kind of stuck and any help would be appritiated.
The problem is the button does not lock when i click save.
public void AddData(){
gumb_poslji.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = getActivity();
Calendar calander = Calendar.getInstance();
Integer cDay = calander.get(Calendar.DAY_OF_MONTH);
Integer cHour = calander.get(Calendar.HOUR_OF_DAY);
Integer cDayOfTheWeek = calander.get(Calendar.DAY_OF_WEEK)-1;
Integer cMonth = calander.get(Calendar.MONTH)+1;
int seekBarProgressValue = seekBar.getProgress();
String strI = String.valueOf(seekBarProgressValue);
String poslji_data = strI;
boolean pregled_vnosa = myDb.insertData(poslji_data,cHour,cDay,cDayOfTheWeek,cMonth);
if (pregled_vnosa==true)
Toast.makeText(activity, "Vnos uspešen",Toast.LENGTH_LONG).show();
else
Toast.makeText(activity, "Vnos neuspešen!!!",Toast.LENGTH_LONG).show();
}
});
gumb_poslji.setEnabled(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(3600000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
gumb_poslji.setEnabled(false);
}
});
}
}).start();
}
Handler mHandler= new Handler();
static Runnable mUpdateTimeTask = new Runnable() {
public void run() {
gumb_poslji.setEnabled(false);
mHandler= .removeCallbacks(mUpdateTimeTask);
}
};
mHandler.postDelayed(this, 3600000);
Related
I'm work on crate server and android client
but thread doesn't interrupted by android client
My android Client has request for the RoomList from server
and Server receive, Client Accept
and fill in my ListView used the Adapter
here's problem if Click backButton,
than RoomListAcitivity was close and thread was stop
but thread dosen't stop just alive in my app
first Enter has work on sucessfully
but Press BackButton on and re-Enter this Activity
MyApp just White, No Action
how can i stop this thread?
(and sorry for my English skill...)
i tried .interrupt() method , and handler.removeMessages(0)
but failed thread keep alive
upload this full java code just in case...
ListView roomList;
RoomAdapter roomAdapter;
Socketservice ss;
String msg,rtitle;
String msgs[];
String list[];
Thread listthread,EnterRoomThread,removeV;
boolean staterun = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_room);
roomList = findViewById(R.id.roomList);
roomAdapter = new RoomAdapter();
listthread = new Thread() {
public void run(){
ss.out.println("163|");
ss.out.println("100|");
try {
while (staterun == true) {
msg = ss.in.readLine();
handler.post(new Runnable() {
public void run() {
msgs = msg.split("\\|");
String protocol = msgs[0];
switch (protocol) {
case "163":
list = msgs[1].split(",");
for (int i = 0; i < list.length; i++) {
String list1[] = list[i].split("-");
String listT = list1[0];
int listC = Integer.parseInt(list1[1]);
int listI = Integer.parseInt(list1[2]);
roomAdapter.CreateRoom(listI, listT, listC);
}
roomList.setAdapter(roomAdapter);
msg = "";
msgs = null;
break;
case "200":
Intent i = new Intent(getApplicationContext(), GameWaitingActivity.class);
i.putExtra("tname", rtitle);
staterun = !staterun;
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
startActivity(i);
finish();
break;
case "201":
Toast.makeText(getApplicationContext(), "방이 꽉 찼습니다.", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
} catch (IOException e) {
}
}
};
listthread.start();
roomList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Room item = (Room) roomList.getItemAtPosition(position);
rtitle=item.getTitle();
EnterRoomThread = new Thread() {
public void run() {
ss.out.println("200|" + rtitle);
EnterRoomThread.interrupt();
}
};
EnterRoomThread.start();
}
});
}
Handler handler = new Handler();
#Override
public void onBackPressed() {
removeV = new Thread() {
public void run(){
ss.out.println("101|");
removeV.interrupt();
}
};
removeV.start();
handler.removeMessages(0);
staterun = false;
listthread.interrupt();
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
finish();
}
}
Go ahead with this, write this inside run() method
//use this boolean value to keep track.
boolean shouldRunFlag = true;
while (shouldRunFlag) {
try {
Thread.sleep(10);
//Do your work............
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Interrupted Exception caught");
// change the flag, so that while loop can be broken.
shouldRunFlag = false;
Log.v(TAG, "run: breaking the loop");
break;
}
}
and this is how you interrupt and clean the thread
private void interrupt(Thread currentThread) {
Log.i(TAG, "interrupt");
if (currentThread != null) {
Thread dummyThread = currentThread;
dummyThread.interrupt();
currentThread = null;
}
}
The thread in my application is giving a weird error on the myThread.start() function specifically the start is wrong the error is "Cannot resolve symbol start" . initially i thought it was a bracket issue but when i adjust them it ends up breaking the OnClicklistner. The thread is suppose just suppose to make the user wait before doing a set text and then the following button will take the user to a website. Can any one see my error?
package com.example.trap.york_hw6;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
public class Main3Activity extends AppCompatActivity implements View.OnClickListener {
Button Cheat;
Button NextPage3;
WebView browser3;
#SuppressLint("HandlerLeak")
Handler handler = new Handler() {
public void handleMessage(Message msg) {
TextView statement = (TextView) findViewById(R.id.snitch);
statement.setText("Checking to see if your a cop");
}
;
};
#SuppressLint("HandlerLeak")
Handler handler2 = new Handler() {
public void handleMessage(Message msg) {
browser3.loadUrl("https://www.youtube.com");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
browser3 = (WebView) findViewById(R.id.webkit3);
browser3.getSettings().setJavaScriptEnabled(true);
browser3.getSettings().setDomStorageEnabled(true);
Cheat = (Button) findViewById(R.id.CC);
NextPage3 = (Button) findViewById(R.id.Next3);
NextPage3.setOnClickListener(this);
Cheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Runnable r = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
;
Thread myThread = new Thread(r);
myThread.start();
};
}
});
final Runnable r2 = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 7000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
;
Thread myThread2 = new Thread(r2);
myThread2.start();
};
}
public void onClick(View v) {
Intent i = new Intent(this, Main4Activity.class);
i.putExtra("value", "I got this from MainActivity2");
i.putExtra("value1", 5);
startActivityForResult(i, 3);
}
}
You are starting thread inside wrong block. Try the code below .
final Runnable r2 = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 7000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
};
};
Thread myThread2 = new Thread(r2);
myThread2.start();
AND
Cheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Runnable r = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
};
};
Thread myThread = new Thread(r);
myThread.start();
}
});
You can not initialise and start Runnable inside its block.
You can write like this.
Cheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Runnable r = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
};
Thread myThread = new Thread(r);
myThread.start();
}
});
and second one
final Runnable r2 = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 7000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
};
Thread myThread2 = new Thread(r2);
myThread2.start();
Suggestion : Also i seen your onClick method, i suggest you check clicked button's id before doing any action like. Because if you have multiple buttons having OnClickListener referring to current class, you will need to check.
public void onClick(View v) {
switch (v.getId()){
case R.id.Next3:
Intent i = new Intent(this, Main4Activity.class);
i.putExtra("value", "I got this from MainActivity2");
i.putExtra("value1", 5);
startActivityForResult(i, 3);
break;
}
}
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));
}
}
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;
}
};
I'm testing something and I want print out execution time with this code:
private Runnable runnerLog = new Runnable() {
#Override
public void run() {
String timeStamp = new SimpleDateFormat("HH:mm:ss yyyy-dd-MM").format(Calendar.getInstance().getTime());
System.out.println("Current time: " + timeStamp);
mHandlerLogger.postDelayed(runnerLog, mInterval);
}};
The result should be like:
13:45:10
13:45:12
13:45:14
13:45:16
and so on...
but i noticed that sometimes is not difference 2 seconds, but three:
13:45:10
13:45:12
13:45:15
13:45:17
13:45:19
13:45:21
13:45:24
What is the reason for this situation? Is there better solution for executing something each X seconds?
try this
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread= new Thread(runnable);
myThread.start();
}
public void doWork() {
runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {}
}
});
}
class CountDownRunner implements Runnable{
// #Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
doWork();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
}
}
please try this:
private Handler myhandler ;
private long RETRY_TIME = xx;
private long START_TIME = yy;
//oncreate
myhandler= new Handler();
myhandler.postDelayed(myRunnable, START_TIME);
//your runnable class
private Runnable myRunnable = new Runnable() {
public void run() {
//doing something
myhandler.postDelayed(myRunnable, RETRY_TIME);
}
};