Android async task usage - android

On click of a button, I want to open a dialog box. On that dialog box I want to set the text dynamically (somewhat like a stopwatch) with the text which will come via a loop. Could someone please guide me with sample code? I tried many examples given on the net but not able to successfully achieve the result.
//Button where the action starts
public void onClickStart(View v) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.activity_details);
dialog.setTitle("Your Step Details");
dialog.show();
DisplayTask dd= new DisplayTask();
dd.execute();
}
public void doWork(){
final Handler handler=new Handler();
new Thread(new Runnable (){
boolean isRunning=true;
#Override
public void run() {
while(isRunning){
try{
handler.post(new Runnable(){
#Override
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.txtLeft);
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) {}
}
});
}catch(Exception e){
}
}
}
}).start();
}
public class DisplayTask extends AsyncTask<Void , Void, Void> {
protected void onPostExecute(){
MainActivity main= new Mai`enter code here`nActivity();
main.doWork();
}
#Override
protected Void doInBackground(Void... params) {
onPostExecute();
return null;
}
}

If you want to do something on a timer, AsyncTask isn't the right method. Use a Handler, and post a message to it using postMessageDelayed. This will let you do something in a few milliseconds/seconds, but it will happen on the UI thread.

Related

How to load new values of JSON after every 10 seconds

Hi people I am getting problem in getting my latest JSON value after every 10 seconds. I have developed this code and now I am stucked in this. When I run this code it shows the value after second and did not get updated the second time. I have implemented the handler but it is also not working here.
public class MainActivity extends AppCompatActivity {
TextView a,b,c,d,e,f,g,h;
String result = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a=(TextView) findViewById(R.id.a);
b=(TextView) findViewById(R.id.b);
c=(TextView) findViewById(R.id.c);
DownloadTask task = new DownloadTask();
task.execute("https://api.thingspeak.com/channels/12345/feeds.json?results=1");
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
new Handler().postDelayed(new Runnable() {
public void run() {
search(result);
}
}, 10000);
}
public void search(String result){
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray weatherInfo = jsonObject.getJSONArray("feeds");
JSONObject legsobject = weatherInfo.getJSONObject(0);
a.setText(legsobject.getString("field1"));
b.setText(legsobject.getString("field2"));
c.setText(legsobject.getString("field3"));
}catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I want to get my value refreshed after every 10 seconds and it is not doing it.
Can any one guide me that how can I make it possible.
Try this code ..
private final int INTERVAL_MILLI = 60000; // define your time..
Handler mHandler;
#Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacks(SyncData);
}
Runnable SyncData = new Runnable() {
#Override
public void run() {
// call your code here..
Log.e(TAG, "SyncData1: " + new java.sql.Date(System.currentTimeMillis()).toString());
final String Token = AppSetting.getStringSharedPref(mContext, Constants.USER_KEY_TOKEN, "");
if (!TextUtils.isEmpty(Token) && !CommonUtils.isServiceRunning(mContext)) {
Log.e(TAG, "SyncData2: " + new java.sql.Date(System.currentTimeMillis()).toString());
startService(new Intent(mContext, SyncService.class));
}
callSyncData();
}
};
public void callSyncData()
{
mHandler.postDelayed(SyncData, INTERVAL_MILLI);
}
and callSyncData() method called in activity onCreate method and run method.
To begin with, I don't like the idea of hammering the server with a request every 10s even nothing changes really. If you can move to a solution with notification from the server it will be better.
If you still need to do that you can use three common solutions to fire a repeating task with a period:
1- Use Timer & TimerTask
For this solution you need to declare your timer task to run:
final TimerTask repeatedTask = new TimerTask() {
#Override
public void run() {
//you stuff here
}
};
Then you need to schedule your task using a timer like below:
final Timer timer = new Timer();
timer.scheduleAtFixedRate(repeatedTask,0, 10 * 1000);
==> Don't forget to call timer.cancel(); when your are done (or activity pause, stop, ...)
2- Use ScheduledThreadPoolExecutor
This is basically a replacing for Timer task starting android 5.0. The setup is more easy and straightforward like below:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
//you stuff here
}
}, 0, 10, TimeUnit.SECONDS);
==> don't forget to shutdown your executor when you are done by calling : executor.shutdown();
3- Use Handler
The tip here is to repost the runnable after downloading your json like mentionned in the previous answer.
You can use TimerTask and Timer. If you need to update UI components you should run it on UI thread.
final TimerTask yourRepeatedTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code here
}
});
}
};
And the Timer which schedules your task in a given interval. In your case, it is 10s. Make sure to give the interval in milliseconds.
final Timer timer = new Timer();
timer.scheduleAtFixedRate(yourRepeatedTask ,0, 10 * 1000);
At last call timer.cancel() to stop the timer.
#Override
protected void onPause() {
if (timer != null) {
timer.cancel();
}
super.onPause();
}

Android: ProgressDialog not progressing inside a Thread

I'm calling several AsyncTasks to do a job. In order to know when they are done. I have an object (synchronized) with a numerator that holds the number of current running AsyncTasks.
After deploying all of them I do the following:
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage(getString(R.string.please_wait));
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setProgress(0);
pd.setMax(Utils.getAsyncs());
pd.show();
new Thread(new Runnable() {
#Override
public void run() {
while (Utils.getAsyncs() > 0)
pd.setProgress(pd.getMax() - Utils.getAsyncs());
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
}
});
}
}).start();
When the dialog shows, it starts progressing but at some point it gets stuck til the end of everything and then dismisses (as expected).
I tried to put
pd.setProgress(pd.getMax() - Utils.getAsyncs());
also inside a runOnUiThread but that made things worse and I'm sure I'm missing something else. hence my question. Thanks
edited by request:
public static int getAsyncs() {
return asyncs;
}
edit 2: I did the following based on a comment
while (Utils.getAsyncs() > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
runOnUiThread(new Runnable() {
public void run() {
pd.setProgress(pd.getMax() - Utils.getAsyncs());
}
});
}
and it seems to be better
In your class fields
private Handler progressHandler = new Handler();
private Runnable progressRunnable = new Runnable() {
#Override
public void run() {
progressDialog.setProgress(progressValue);
progressHandler.postDelayed(this, 1000);
}
};
When the time consuming thread is started
// Here start time consuming thread
// Here show the ProgressDialog
progressHandler.postDelayed(progressRunnable, 1000);
When the time consuming thread ends
progressHandler.removeCallbacks(progressRunnable);
/// Here dismiss the ProgressDialog.
ADDED:
Instead new Thread(new Runnable) that you probably use for your time consuming code I propose to do this:
To initialize the task :
MyTask task = new MyTask();
task.execute();
// Here show the PorgressDialog
progressHandler.postDelayed(progressRunnable, 1000);
Add this private class inside your main class:
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
//Here do your time consuming work
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
// This will be called on the UI thread after doInBackground returns
progressHandler.removeCallbacks(progressRunnable);
progressDialog.dismiss();
}
}
do something lik this
new Thread(new Runnable() {
public void run() {
while (prStatus < 100) {
prStatus += 1;
handler.post(new Runnable() {
public void run() {
pb_2.setProgress(prStatus);
}
});
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(prStatus == 100)
prStatus = 0;
}
}
}).start();

Android listview timer run in every second

I have a issue with using a timer on a listview.
In the list item I showed using sqlite values. There is a textview which showing time difference of last updated time of the data and current time. i have to show it in every one second. so the user can know how long he updated the record.
I tried this in several ways.
First way
I tried to add timer in adapter class. so for every item new timer is created. so application crashed because of many timers run simultaneously.
Second way
I tried using adapter.notifyDataSetChanged() way. Like as this.
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
if (adapterChatThread != null) {
adapter.notifyDataSetChanged();
}
timerHandler.postDelayed(this, 1000); // run every second
}
};
timerRunnable.run();
I move to another activity when click on list item and user can come back to this Activity.
so in Onresume I used
timerHandler.postDelayed(timerRunnable, 500);
and OnPause
timerHandler.removeCallbacks(timerRunnable);
Issue is data is not showing well. I mean in every second data difference is not one second. some time differnce is 2sec, 5 sec, .. etc.
means timer is not working as I expected.
Third way
I used a asynctask and call it in every second using a timer.
class ThreadTimer extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
if (adapter != null)
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
I called this as in here
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
new ThreadTimer().execute();
timerHandler.postDelayed(this, 1000); // run every second
}
};
timerRunnable.run();
previous issue triggered. (data not showing well)
Fourth way
Using AsyncTask as this
class ThreadTimer extends AsyncTask<Void, Void, Void> {
void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
}
}
#Override
protected Void doInBackground(Void... params) {
while (threadRun) {
Sleep(1000);
return null;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
I called this class in OnResume.
In on pause I set threadRun= false;
issue is same.
please help me.
My requirement is update list item in every second.
Thank you.
edit
here is my adapter class textview update code.
Date lastUpdatedTime;
final ChatThreadDAO ctd = new ChatThreadDAO();
long timeForNextResponse = ctd.getLastRespondedTime(vct.get(position).getThread_id());
try {
if (vct.get(position).getThread_read_status() == 1 && timeForNextResponse > 0) {
final long respTime = timeForNextResponse;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
lastUpdatedTime = formatter.parse(vct.get(position).getLast_updated_time());
final long timeDiff = (new Date()).getTime() - lastUpdatedTime.getTime();
if (timeDiff <= respTime) {
timeForNextResponse = respTime - timeDiff;
ctd.updateTimeRespondToLastMsg(vct.get(position).getThread_id(), timeForNextResponse);
holder.tvChatTimer.setVisibility(View.VISIBLE);
holder.tvChatTimer.setText(timeForNextResponse / 1000 + "");
} else {
ctd.updateTimeRespondToLastMsg(vct.get(position).getThread_id(), 0);
}
} else {
holder.tvChatTimer.setVisibility(View.INVISIBLE);
}
} catch (ParseException e) {
e.printStackTrace();
}
here vct is
Vector vct;
I assign the values to vector in adapter class constructer.
Here is an example similar to your case.
private class connectionControl extends Thread {
boolean stop_ = false;
public void stop_() {
this.stop_ = true;
}
public void run() {
System.out.println("Thread started:" + getClass().getSimpleName());
while(!this.stop_) {
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Calendar c = Calendar.getInstance();
int rightNow = c.get(Calendar.SECOND) + c.get(Calendar.MINUTE)*60;
if(rightNow - lastUpdatedTime > 10) {
wirelessIcon.setImageResource(R.drawable.wirelessred);
}
else if(rightNow - lastUpdatedTime > 5) {
wirelessIcon.setImageResource(R.drawable.wirelessyellow);
}
else {
wirelessIcon.setImageResource(R.drawable.wirelessgreen);
}
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Thread stoped:" + getClass().getSimpleName());
}
}
You set your lastUpdatedTime the same way you created rightNow whenever you call notifyDataSetChanged() method of your adapter.

Display Current Time using Fragment in Android

I am currently working on displaying current time on my Android application. I already got the current time but I need it to be dynamic; it should update every second. I have found this solution but there's something wrong:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Thread timerThread = null;
Runnable runnable = new CountDownRunner();
timerThread = new Thread(runnable);
timerThread.start();
}
public void doWork() {
runOnUiThread(new Runnable() {
public void run() {
try {
Date dt = new Date();
int day = dt.getDate();
int month = dt.getMonth();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
time.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) {
}
}
}
}
The error is on this line:
runOnUiThread(new Runnable() {
I think the reason for this error is because I'm implementing it in Fragment. It does not extend to an Activity which is necessary to implement Thread.
I tried to search and found a possible answer wherein I should need an activity to extend it on runOnUiThread but I haven't found any implementation how to do it. I'm somehow confused and stucked at the moment.
Try this: getActivity().runOnUiThread(new Runnable...
It's because:
1) the implicit this in your call to runOnUiThread is referring to AsyncTask, not your fragment.
2) Fragment doesn't have runOnUiThread
getActivity().runOnUiThread(new Runnable() {
If you are using Fragment then try to use:
getActivity().runOnUiThread(new Runnable(){
}
And if you are using this in Activity then use:
YourActivity.this.runOnUiThread(new Runnable() {
}

Stop a service and timer after fixed interval of time, android?

In my app, I have a service implementing timer task through which i am getting user's location after every 10 seconds.
The thing I am stuck with is I would like to stop this service as well as timer after say 1 or 2 minutes.
I am not able to put behind the logic for it.
Please help me out.
public class TimeService extends Service {
// constant
public static final long NOTIFY_INTERVAL = 20 * 1000; // 10 seconds
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
int i=0;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
// cancel if already existed
if(mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
Toast.makeText(getApplicationContext(), getDateTime(),
Toast.LENGTH_SHORT).show();
new LongOperation().execute("");
}
});
}
private String getDateTime() {
// get date time in custom format
SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
return sdf.format(new Date());
}
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
System.out.println("bgnotification Long operation doinbackground called----> ");
return "";
}
#Override
protected void onPostExecute(String result) {
System.out.println("bgnotification Long operation post execute called----> ");
if(i<3){
GPSTracker mGPS = new GPSTracker(getApplicationContext());
onLocationChanged(mGPS);i++;
Toast.makeText(getApplicationContext(), "HEllo Post execute called",
}
#Override
protected void onPreExecute() {
System.out.println("bgnotification Long operation pre execute called----> ");
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public void onLocationChanged(GPSTracker track) {
// Getting latitude
double latitude = track.getLatitude();
// Getting longitude
double longitude = track.getLongitude();
System.out.println( latitude);
System.out.println( longitude);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
Log.e("Addresses","-->"+addresses);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
#Wishy to stop service and timer task at certain time you need to make an other timer task which going to execute one time and execution time duration will be whatever you specify. In run method u need to write mTimer.purge(); mTimer.cancel() and stopService(newIntent(class.this,yourservice.class));
An easier solution is making timer public static.
public class TimeService extends Service {
//...
private Timer mTimer = null;
//...
}
another Activity:
//...
if(TimeService.mTimer!=null) TimeService.mTimer.cancel();
//...
Override onDestroy() method in service class like thus:
#Override
public void onDestroy() {
super.onDestroy();
if (mTimer != null) {
mTimer.cancel();
}
}
Call stopService() there where you want to stop your service, like thus:
stopService(serviceIntent);
That's all.

Categories

Resources