How to use Timer inside Handler? - android

I want to refresh an adapter every 10 seconds. I'm loading my ListView Adapter inside Handler, so what do I do? How do I use Timer? I want that whenever the value changes, the Adapter automatically refreshes ListView.
#SuppressLint("HandlerLeak")
Handler handle = new Handler() {
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
CommonObjects.hideProgress();
if (msg.what == 1) {
plotadapter = new PlotsAdapter(Plots.this, arrayplot);
plotslist.setAdapter(plotadapter);
}
if (msg.what == 2) {
Toast.makeText(Plots.this, "Server, Not Available!",
Toast.LENGTH_SHORT).show();
finish();
}
}
};
#Override
protected void onRestart() {
if(CommonObjects.getLogoutreject().equals("1") && CommonObjects.logout){
// CommonObjects.logout=false;
finish();
}
super.onRestart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.plots);
plotslist = (ListView) findViewById(R.id.plotslist);
back = (ImageView) findViewById(R.id.plotback);
bottomlayout = (RelativeLayout) findViewById(R.id.bottom_layout);
scroll_down = (ImageView) findViewById(R.id.down);
scroll_up = (ImageView) findViewById(R.id.up);

plotadapter = new PlotsAdapter(Plots.this, arrayplot);
plotslist.setAdapter(plotadapter);
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
#Override
public void run() {
if(condition)
{
// your code to check
plotadapter.notifyDataSetChanged();
}
handler.postDelayed(this, 1000);
}
}, 1000);

Related

Seekbar is still not updating

I made these two method to update seekbar every 100ms:
public void updateSeekBar() {
handler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
#Override
public void run() {
mySeekBar.setMax(mySong.getDuration());
x = mySong.getCurrentPosition();
mySeekBar.setProgress(x);
handler.postDelayed(this, 100);
}
};
and put it inside my playMusic method:
public void playMusic() {
//just a test from intent.getExtra
if(test.equalsIgnoreCase("Jason Mraz")) {
mySong = MediaPlayer.create(MusicClass.this, jm[musicCounter]);
displaySong(jm);
songNumbers = jm.length;
}else if(test.equalsIgnoreCase("fob")) {
mySong = MediaPlayer.create(MusicClass.this, fob[musicCounter]);
displaySong(fob);
songNumbers = fob.length;
}else if(test.equalsIgnoreCase("ed")) {
mySong = MediaPlayer.create(MusicClass.this, ed[musicCounter]);
displaySong(ed);
songNumbers = ed.length;
}
//when the song is completed
mySong.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
nextSong();
}
});
//seekbar update
mySeekBar.setMax(mySong.getDuration());
mySeekBar.setProgress(0);
mySong.start();
updateSeekBar();
}
this is my onCreate method:
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
artistName = (TextView)findViewById(R.id.artistName);
song = (TextView)findViewById(R.id.song);
musicCounter = 0;
ifPlaying = true;
isRandom = false;
random = (ImageButton) findViewById(R.id.random);
stop = (ImageButton)findViewById(R.id.stop);
myImageView = (ImageView)findViewById(R.id.myImageView);
dice = new Random();
mySeekBar = (SeekBar)findViewById(R.id.mySeekBar);
test = getIntent().getStringExtra("test");
if(test.equalsIgnoreCase("Jason Mraz")) {
artistName.setText("Jason Mraz");
displayPP();
songNumbers = jm.length;
myImageView.setImageResource(R.drawable.jason_mraz);
} else if (test.equalsIgnoreCase("fob")) {
artistName.setText("Fall Out Boys");
displayPP();
songNumbers = fob.length;
myImageView.setImageResource(R.drawable.fall_out_boys);
} else if (test.equalsIgnoreCase("ed")) {
artistName.setText("Ed Sheeran");
displayPP();
songNumbers = ed.length;
myImageView.setImageResource(R.drawable.ed_sheeran);
}
playMusic();
mySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b) {
mySong.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mySong.pause();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (ifPlaying == true) {
mySong.start();
} else {
return;
}
}
});
}
My application says Unfortunately stopped. But when I remove the updateSeekbar in playMusic method it works fine, but without the updating seekBar every second. The setOnSeekBarChangeListener works perfectly fine, the only problem is I can't make updateSeekBar method work because it is alwats stopping my application and force exit.
The symptoms you are describing is called an ANR. It means that you is doing to much work in the main thread.
What you need todo is review what you are triggering in your mUpdateTimeTask.
Next make sure your handler is running on the UI since your are updating views:
Handler handler = new Handler(Looper.getMainLooper());

how to restart horizontal progressbar

I've a horizontal progressbar which shows progress from 0 to 100. What I want is to restart the progressbar again from 0 when it reaches 100. I'll be showing this in a Fragmentdialog. For now I'm checking it in activity itself. How to do that?
public class MainActivity extends AppCompatActivity{
private Button startbtn, stopbtn;
ProgressBar pb;
private TextView progressTxt;
int progressBarValue = 0;
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = new CShowProgress(MainActivity.this);
btn = (Button)findViewById(R.id.btn);
startbtn = (Button)findViewById(R.id.startbtn);
stopbtn = (Button)findViewById(R.id.stopbtn);
pb = (ProgressBar)findViewById(R.id.progressBar);
progressTxt = (TextView)findViewById(R.id.progressTxt);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myprogress(true);
}
});
stopbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myprogress(false);
}
});
}
private void myprogress(final Boolean isStart){
handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
if(isStart && progressBarValue<100)
{
progressBarValue+=1;
pb.setProgress(progressBarValue);
progressTxt.setText(String.valueOf(progressBarValue));
handler.sendEmptyMessageDelayed(0, 100);
}
}
};
handler.sendEmptyMessage(0);
}
}
I assume this chunk of code will work for your use case:
private void myprogress(final Boolean isStart) {
handler = new Handler() {
public void handleMessage(Message msg) {
if (isStart && progressBarValue < 100) {
...
} else if (isStart) {
// progressBarValue is equal to 100
// make it zero and do the same thing again
progressBarValue = 0;
progressBarValue += 1;
pb.setProgress(progressBarValue);
progressTxt.setText(String.valueOf(progressBarValue));
handler.sendEmptyMessageDelayed(0, 100);
}
}
};
handler.sendEmptyMessage(0);
}
First, you should use a counter mechanizm (run a delayed handler, timer, thread or something else)to check current progress periodically.
(progressTxt.getProgress == 100)
will do the trick.
Another way is using this answer.

Android code about timer

I have change code to below and my purpose is to set a button
when I click the timer run,how to change the code below? thanks
new code below
I have change code to below and my purpose is to set a button
when I click the timer run,how to change the code below? thanks
new code below
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Handler aHandler;
TextView aTextView;
Button aButton;
EditText aEditText;
Handler aHandler01;
TextView aTextView01;
Button aButton01;
EditText aEditText01;
Boolean checker=false;
int count = 11;
int count01 = 11;
#Override
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.activity_main);
aEditText = (EditText)findViewById(R.id.editText01);
aTextView = (TextView)findViewById(R.id.TextView01);
aEditText01 = (EditText)findViewById(R.id.editText02);
aTextView01 = (TextView)findViewById(R.id.TextView02);
aButton=(Button)findViewById(R.id.button01);
aButton01=(Button)findViewById(R.id.button02);
//第一個計時器
aButton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v){ if(!aEditText.getText().toString().equalsIgnoreCase(""))
{count=Integer.parseInt(aEditText.getText().toString());}
aHandler = new Handler();
if(checker==false){
aHandler.post(runnable);
checker=true;
}
}
});
//第二個計時器
aButton01.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (!aEditText01.getText().toString().equalsIgnoreCase("")) {
count01 = Integer.parseInt(aEditText01.getText().toString());
}
aHandler01 = new Handler();
aHandler01.post(runnable01);
}
});
}
//第一個計時器
final Runnable runnable = new Runnable() {
public void run() { // TODO Auto-generated method stub
if (count> 0) {
aTextView.setText(Integer.toString(count-1));
count--;
aHandler.postDelayed(runnable, 1000);
}else{
aTextView.setText("boom");
}
}
};
//第二個計時器
final Runnable runnable01 = new Runnable() {
public void run() { // TODO Auto-generated method stub
if (count01> 0) {
aTextView01.setText(Integer.toString(count01-1));
count01--;
aHandler01.postDelayed(runnable01, 1000);
}else{
aTextView01.setText("boom");
}
}
};
#Override
protected void onPause() { // TODO Auto-generated method stub
super.onPause();
if (aHandler != null) {
aHandler.removeCallbacks(runnable);
}
}
}
try this
private Handler handler = new Handler();
Boolean checker=false;
#Override
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.activity_main);
aEditText = (EditText)findViewById(R.id.editText01);
aTextView = (TextView)findViewById(R.id.TextView01);
aButton=(Button)findViewById(R.id.button01);
aButton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v){ if(!aEditText.getText().toString().equalsIgnoreCase(""))
{count=Integer.parseInt(aEditText.getText().toString());}
if(!checker){
checker=true;
handler.post(runnable);//to start timer
}
}
});
}
final Runnable runnable = new Runnable() {
public void run() {
// TODO Auto-generated method stub
if(checker)
{
checker=false;
return;
}
if (count> 0) {
aTextView.setText(""+Integer.toString(count-1));
count--;
aHandler.postDelayed(runnable, 1000);
}else{
aTextView.setText("boom");
}
}
};
as you are assigning the value to 'count' variable in OnCreate from editText when editText is empty, it is returning null string which then you are parsing for int value which returns NumberFormatException
try to do it as follows
if (!aEditText.getText().toString().equalsIgnoreCase(""))
{
count = Integer.parseInt(aEditText.getText().toString());
}
OR you can assign a value to 'count' from editText on any button's click or using TextChangedListener(TextWatcher) to monitor and get text from edittext at run time.

How to stop a timer after certain number of times

Trying to use a Timer to do run this 4 times with intervals of 10 seconds each.
I have tried stopping it with a loop, but it keeps crashing. Have tried using the schedule() with three parameters, but I didn't know where to implement a counter variable. Any ideas?
final Handler handler = new Handler();
Timer timer2 = new Timer();
TimerTask testing = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "test",
Toast.LENGTH_SHORT).show();
}
});
}
};
int DELAY = 10000;
for (int i = 0; i != 2 ;i++) {
timer2.schedule(testing, DELAY);
timer2.cancel();
timer2.purge();
}
private final static int DELAY = 10000;
private final Handler handler = new Handler();
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask() {
private int counter = 0;
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
});
if(++counter == 4) {
timer.cancel();
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer.schedule(task, DELAY, DELAY);
}
Why not use an AsyncTask and just have it Thread.sleep(10000) and the publishProgress in a while loop? Here is what it would look like:
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
int i = 0;
while(i < 4) {
Thread.sleep(10000);
//Publish because onProgressUpdate runs on the UIThread
publishProgress();
i++;
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
//This is run on the UIThread and will actually Toast... Or update a View if you need it to!
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
}.execute();
Also as a side note, for longer term repetitive tasks, consider using AlarmManager...
for(int i = 0 ;i<4 ; i++){
Runnable runnableforadd ;
Handler handlerforadd ;
handlerforadd = new Handler();
runnableforadd = new Runnable() {
#Override
public void run() {
//Your Code Here
handlerforadd.postDelayed(runnableforadd, 10000); }
};
handlerforadd.postDelayed(runnableforadd, i);
}

i get the message "Only the original thread that created a view hierarchy can touch its views." after second time of running

hvae very spcieal problem, i read all the post on multithreading in android, but still go the famuse error. but, i got in after the second run of the same thread for exmaple "thGetDevice" from the sourcecode;
hope u can help me.. thnx..
Im get
/** Variable definition*/
CheckBox cbBlueTooth;
BluetoothAdapter mBluetoothAdapter;
AlertDialog.Builder dialog;
ArrayAdapter mArrayAdapter;
ListView MainListView;
ProgressBar prProgressbar;
Thread thGetDevices;
Thread thClearDevices;
Handler handler;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Initial Handler */
handler=new Handler() {
#SuppressWarnings("unchecked")
#Override
public void handleMessage(final Message msg) {
/******************************
*
* this line cuse to the trouble
*/
BlueQuickActivity.this.runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
prProgressbar.incrementProgressBy(msg.arg1);
mArrayAdapter = (ArrayAdapter<String>)msg.obj;
mArrayAdapter.notifyDataSetInvalidated();
mArrayAdapter.notifyDataSetChanged();
prProgressbar.setVisibility(ProgressBar.INVISIBLE);
setListAdapter(mArrayAdapter);
}
});
}
};
/* Set Finalization true */
// System.runFinalizersOnExit(true);
setContentView(R.layout.main);
/* ListView Definition */
TextView tvHeader = new TextView(this);
MainListView = this.getListView();
MainListView.addHeaderView(tvHeader);
mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
//mArrayAdapter.setNotifyOnChange(true);
prProgressbar = (ProgressBar)findViewById(R.id.progressBar1);
prProgressbar.setVisibility(ProgressBar.INVISIBLE);
/* Get Bluetooth driver */
cbBlueTooth = (CheckBox)findViewById(R.id.cbTurnBlueTooth);
dialog = new AlertDialog.Builder(this);
/* initializing Bluetooth adapter **/
mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
/*ShowNotifMessage("Sorry..", "You Don't have Bluetooth Driver");
try {
Thread.sleep(3000);
android.os.Process.killProcess(android.os.Process.myPid());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
// Initial the thGetDeviceThread and thClearDevices
//initGetDevicesThread();
//initClearDevicesThread();
/*Listener for Checkbox*/
cbBlueTooth.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked && !mBluetoothAdapter.isEnabled()) {
prProgressbar.setVisibility(ProgressBar.VISIBLE);
buttonView.setEnabled(false);
BluetoothAdapter.getDefaultAdapter().enable();
initGetDevicesThread();
buttonView.setEnabled(true);
}
else if (!isChecked && mBluetoothAdapter.isEnabled()) {
prProgressbar.setVisibility(ProgressBar.VISIBLE);
buttonView.setEnabled(false);
BluetoothAdapter.getDefaultAdapter().disable();
initClearDevicesThread();
buttonView.setEnabled(true);
}
else
{
prProgressbar.setVisibility(ProgressBar.VISIBLE);
buttonView.setEnabled(false);
BluetoothAdapter.getDefaultAdapter().enable();
initGetDevicesThread();
buttonView.setEnabled(true);
}
}
});
}
/** Gets all paird devices and put them in the Listview */
private void initGetDevicesThread()
{
thGetDevices = new Thread(new Runnable() {
public void run() {
Message msg = handler.obtainMessage();
msg.what = 1;
msg.obj = getDeviceList();
handler.sendMessage(msg);
}
});
(thGetDevices).start();
}
/** clear all paird devices and put them in the Listview */
private void initClearDevicesThread()
{
thClearDevices = new Thread(new Runnable() {
public void run() {
Message msg = handler.obtainMessage();
msg.what = 2;
msg.obj = clearListOfDevices();
handler.sendMessage(msg);
}
});
(thClearDevices).start();
}
public ArrayAdapter<String> getDeviceList()
{
while(BluetoothAdapter.getDefaultAdapter().getState() != BluetoothAdapter.STATE_ON);
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName());
}
}
return mArrayAdapter;
}
private ArrayAdapter<String> clearListOfDevices()
{
while(BluetoothAdapter.getDefaultAdapter().getState() != BluetoothAdapter.STATE_OFF);
mArrayAdapter = new ArrayAdapter<String>(MainListView.getContext(), android.R.layout.simple_list_item_1);
return mArrayAdapter;
}
//** */
private void ShowNotifMessage(String strTitle,String strMsg)
{
dialog.setTitle(strTitle);
dialog.setMessage(strMsg);
dialog.show();
}
}
You cannot Update the UI from a non-UI Thread. To do so you have to use runOnUiThread(). Put your code to update the UI inside the runOnUiThread().
Activity_name.this.runOnUiThread(new Runnable() {
public void run() {
prProgressbar.incrementProgressBy(msg.arg1);
mArrayAdapter = (ArrayAdapter<String>)msg.obj;
mArrayAdapter.notifyDataSetInvalidated();
mArrayAdapter.notifyDataSetChanged();
prProgressbar.setVisibility(ProgressBar.INVISIBLE);
setListAdapter(mArrayAdapter);
}
});
Try using Handler like below
Handler viewUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
~~~~your code~~~
break;
}
}
};

Categories

Resources