Reputation: 239
I recently started to learn JAVA/Android and found something interesting. I wanted to make an App, which by the way works good, but I have one small problem. I made an app which has many operations. So many that GUI freezes (PC/Smartphone). For example I have a while which has 10000 epochs and inside this while are many functions that use fors (Evolutionary algorithm). I am using ProgressBar. The problem is that progressbar freezes when I start the app. I can show you how the app looks like
As you can see, there is a Button. I launch the whole thing with this button. So the question is, Is there any way to make progresbar work? I just want progressbar to show actual epoch and maximum epochs as the final value. I tried to make a thread but didn't work and i tried delegate too but did't work neither.
Thanks for help guys.
Upvotes: 1
Views: 911
Reputation: 3195
Use AsyncTask. As when you long running task in UI Thread, the thread block and the thread will not be able to update the UI, So you will be seeing that the progress bar is not increasing or loading. So do the long running task in background thread using AsyncTask or Thread Pool Executor
package com.test;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class AsyncTaskActivity extends Activity {
Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener((OnClickListener) this);
}
public void onClick(View view){
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
}
Upvotes: 3