I am trying to show horizontal progress bar "Not ProgressDialog" on my activity like this
here is what my xml file contains
<ProgressBar
android:id="#+id/pdialog"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
/>
I am trying to update its status using AsyncTask Class by setting pdialog.setProgress() but its not showing any progress, it works with progressdialog but not with horizontal progress bar.
public class MainActivity extends Activity {
private SQLiteDatabase db;
private Cursor cursor;
private ProgressBar pdialog;
private ImageButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
btn = (ImageButton) findViewById(R.id.startbtn);
pbar = (ProgressBar) findViewById(R.id.progressBar1);
pdialog = (ProgressBar) findViewById(R.id.pdialog);
pdialog.setMax(100);
pdialog.setProgress(20);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdialog.setVisibility(View.VISIBLE);
new DownloadFilesTask().execute();
}
});
}
private class DownloadFilesTask extends AsyncTask<Void, Integer, Integer> {
int load = 1;
protected Integer doInBackground(Void... params) {
try {
load = 10 * i;
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
pdialog.setProgress(load);
}
});
}
} catch (Exception e) {
}
}
protected void onProgressUpdate(Integer... progress) {
if (progress[0] == 100) {
pdialog.setVisibility(View.INVISIBLE);
}
}
protected void onPostExecute(Integer params) {
}
}
}
If load variable gets changed correctly:
Instead of this:
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
pdialog.setProgress(load);
}
});
You could use:
publishProgress(load);
which would automatically call on UI Thread:
protected void onProgressUpdate(Integer... progress) {
int p = progress[0];
if (p >= 100) {
pdialog.setVisibility(View.INVISIBLE);
}else{
pdialog.setProgress(p);
}
}
UPDATE:
remove android:indeterminate="true" as pointed out in other answer.
In your layout file please remove the following attribute android:indeterminate="true" from ProgressBar element.
I had the same question, but
I found the problem is the interface View.OnClickListener().
When the pbar was put out of the btn.setOnClickListener(new View.OnClickListener() {}), it worked well. Otherwise, it did not update.
Then, I made a constructor which passed the pbar into the OnXXXClickListener.
private class OnXXXClickListener implements View.OnClickListener() {
private ProgressBar bar;
public OnXXXClickListener(ProgressBar bar) {
this.bar = bar;
}
#Override
public void onClick(View v) {
bar.setProgess(50);
new DownloadFilesTask().execute();
}
}
Then the pbar could work well.
Related
I am trying to use RxAndroid to do the same work which is AsyncTask exactly does. I coded a simple example, where I enter a n integer in an edittext and when I press
a button, I make the hread to sleep for 3 seconds using "SystemClock.sleep" and while the thread is sleeping I show a progressbar and when the three seconds
elapsed the progresssbar will adisappear and the value entered in the edittext will be multiplied by 10 and displayed in atextview.
normally, when I use AsyncTask, I show the progressbar in onPreExecute and make it to disappear in onPostExecute. but when I run the below code I receive the
following error:
Only the original thread that created a view hierarchy can touch its views.
how to handle it properly in RxAndroid?
code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private EditText mEditTextValueToProcess = null;
private Button mButtonGoAsynchronous = null;
private TextView mTextViewProcessedValue = null;
private ProgressBar mProgressBar = null;
private rx.Observable<String> mAsyncObservable = null;
Subscriber mAsyncSubscriber = new Subscriber<String>() {
#Override
public void onCompleted() {
Log.w(TAG, "onCompleted");
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onError(Throwable e) {
Log.w(TAG, "onError: " + e.getMessage().toString());
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onNext(String o) {
Log.w(TAG, "onNext:->after processing " + o);
mTextViewProcessedValue.setText(o);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intiViews();
mAsyncObservable = rx.Observable.create(new rx.Observable.OnSubscribe<String>() {
#Override
public void call(Subscriber<? super String> subscriber) {
mProgressBar = (ProgressBar) findViewById(R.id.progressDialog);
mProgressBar.setVisibility(View.VISIBLE);
SystemClock.sleep(3000);
subscriber.onNext("" + Integer.valueOf(mEditTextValueToProcess.getText().toString()) * 10);
subscriber.onCompleted();
}
});
}
private void intiViews() {
mEditTextValueToProcess = (EditText) findViewById(R.id.edittext);
mButtonGoAsynchronous = (Button) findViewById(R.id.button_go_asynchronous);
mTextViewProcessedValue = (TextView) findViewById(R.id.textview_processed_value);
//mProgressBar = (ProgressBar) findViewById(R.id.progressDialog);
mButtonGoAsynchronous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAsyncObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mAsyncSubscriber);
}
});
}
}
Have you tried
private Observable<String> createObservable(final int number) {
return rx.Observable.create(new rx.Observable.OnSubscribe<String>() {
#Override
public void call(Subscriber<? super String> subscriber) {
SystemClock.sleep(3000);
subscriber.onNext("" + number * 10);
subscriber.onCompleted();
}
});
}
private void intiViews() {
mEditTextValueToProcess = (EditText) findViewById(R.id.edittext);
mButtonGoAsynchronous = (Button) findViewById(R.id.button_go_asynchronous);
mTextViewProcessedValue = (TextView) findViewById(R.id.textview_processed_value);
mProgressBar = (ProgressBar) findViewById(R.id.progressDialog);
mButtonGoAsynchronous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProgressBar.setVisibility(View.VISIBLE);
createObservable(Integer.valueOf(mEditTextValueToProcess.getText().toString()))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext((ignored) -> {
mProgressBar.setVisibility(View.GONE);
})
.subscribe(mAsyncSubscriber);
}
});
}
?
You need to change few things to achieve this. Look at mAsyncSubscriber initialization, onStart() method & progressBar initialization. The reason why you are getting the error is you are initializing & making your progressbar visible in another thread then your UI thread (because you specified this -> subscribeOn(Schedulers.io()).
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private EditText mEditTextValueToProcess = null;
private Button mButtonGoAsynchronous = null;
private TextView mTextViewProcessedValue = null;
private ProgressBar mProgressBar = null;
private rx.Observable<String> mAsyncObservable = null;
Subscriber mAsyncSubscriber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intiViews();
mAsyncSubscriber = new Subscriber<String>() {
// Override onStart method
#Override
public void onStart() {
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onCompleted() {
Log.w(TAG, "onCompleted");
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onError(Throwable e) {
Log.w(TAG, "onError: " + e.getMessage().toString());
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onNext(String o) {
Log.w(TAG, "onNext:->after processing " + o);
mTextViewProcessedValue.setText(o);
}
};
mAsyncObservable = rx.Observable.create(new rx.Observable.OnSubscribe<String>() {
#Override
public void call(Subscriber<? super String> subscriber) {
SystemClock.sleep(3000);
subscriber.onNext("" + Integer.valueOf(mEditTextValueToProcess.getText().toString()) * 10);
subscriber.onCompleted();
}
});
}
private void intiViews() {
// Init your progressbar
mProgressBar = (ProgressBar) findViewById(R.id.progressDialog);
mEditTextValueToProcess = (EditText) findViewById(R.id.edittext);
mButtonGoAsynchronous = (Button) findViewById(R.id.button_go_asynchronous);
mTextViewProcessedValue = (TextView) findViewById(R.id.textview_processed_value);
//mProgressBar = (ProgressBar) findViewById(R.id.progressDialog);
mButtonGoAsynchronous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAsyncObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mAsyncSubscriber);
}
});
}
I tried to dismiss(); progressbar dialog when the load by using a method onPostExecute in webview when finished process.
my problem is when i run onPostExecute method in AsynTask is never executed ?
Note : i've read
public class MainActivity extends AppCompatActivity {
WebView webView;
EditText edInput;
Button btnCari;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
edInput = (EditText) findViewById(R.id.editText);
btnCari = (Button) findViewById(R.id.button);
btnCari.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
asynCaller myTask = new asynCaller();
myTask.execute();
}
});
}
private void loadWeb(String url){
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://"+url);
}
public class asynCaller extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
url = edInput.getText().toString();
progressDialog.show(MainActivity.this,"Pesan","Memuat . . .",true);
}
#Override
protected String doInBackground(String... params) {
publishProgress();
return url;
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
loadWeb(url);
}
}
}
I am using progress bar for showing progress. But when I'm pressing the back button it keep showing progress bar.I don't want it. how to remove it.
My code for calling Progress circle is-
public void onClick(final View v) {
ProgressCircle progressBar = new ProgressCircle();
progressBar.start(v.getContext());
click(v);
if(progressBarStatus==1)
{
progressBar.stop();
}
}
Following is the click(View) method:
Intent intent = new Intent(AddFriend.this, AddFriendSend.class);
startActivity(intent);
Following is the Progress Circle class:
public class ProgressCircle {
private ProgressDialog progressBar;
public void start(Context context) {
ProgressDialog progressBar = new ProgressDialog(context);
progressBar.setCancelable(true);
progressBar.setMessage("Processing...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
}
public void stop() {
if (progressBar != null) {
progressBar.dismiss();
}
}
}
Please help me out.
In your Activity you override the onBackPressed method like this:
#Override
public void onBackPressed() {
progressBar.stop();
super.onBackPressed();
}
Try to override back button in android as below -
#Override
public void onBackPressed() {
super.onBackPressed();
progressBar.stop();
}
Don't forget to declare progressBar as class member.
No Like this:
ProgressCircle progressBar = null;
public void onClick(final View v) {
progressBar = new ProgressCircle();
progressBar.start(this);
click(v);
if(progressBarStatus==1)
{
progressBar.stop();
}
}
#Override
public void onBackPressed() {
if(progressBar!=null)
progressBar.stop();
else
super.onBackPressed();
}
It was a simple mistake-
we can do this by following code -
ProgressCircle progressBar = null;
public void onClick(final View v) {
progressBar = new ProgressCircle();
progressBar.start(this);
click(v);
if(progressBarStatus==1)
{
progressBar.stop();
}
}
#Override
public void onBackPressed() {
if(progressBar!=null)
progressBar.stop();
else
super.onBackPressed();
}
I have a simple class which extends activiy like this
public class About extends Activity
{
private ProgressDialog pdia;
private TextView tvAbout;
private WebView vwAbout;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
vwAbout = (WebView)findViewById(R.id.vwViewAbout);
String content = new String();
try {
URL url = new URL("http://xxx.prodevAbout.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null)
{
content+=str + "\n";
vwAbout.loadData(content, "text/html", null);
}
in.close();
} catch (Exception e)
{
vwAbout.loadData("error message", "text/html", null);
}
}
}
and what I want to do is I want to add a progressbar while loading content from website and I found this code
private ProgressDialog pdia;
#Override
protected void onPreExecute(){
super.onPreExecute();
pdia = new ProgressDialog(yourContext);
pdia.setMessage("Loading...");
pdia.show();
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pdia.dismiss();
}
and added this code but onPreExecute method cannot be resolved What should I do ?
Thanks;
The way which I am adding progress dialogs in my apps (and I've never had any problems till now) is like this :
Runnable runable = new Runnable() {
#Override
public void run() {
SofiaLiveCafeActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB){
progressDialog = new ProgressDialog(SofiaLiveCafeActivity.this, ProgressDialog.THEME_HOLO_LIGHT);
} else {
progressDialog = new ProgressDialog(SofiaLiveCafeActivity.this);
}
progressDialog.setMessage("Loading! Pleasе wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
});
// CONNECT TO SERVER AND DOWNLOAD DATA
SofiaLiveCafeActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
});
}
}
};
new Thread(runable).start();
added this code but onPreExecute method cannot be resolved What should
I do ?
onPreExecute not resolved because this is method from AsyncTask so will need to extends AsyncTask class to use onPreExecute change your current code using AsyncTask as :
public class About extends Activity
{
[...your code here...]
public void onCreate(Bundle savedInstanceState)
{
[...your code here...]
// execute AsyncTask as
new LongOperation(About.this).execute("");
}
[...your code here...]
public class WebapiOperation extends AsyncTask<String, Void, String> {
Context context;
WebapiOperation(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
// show ProgressDialog here
pdia = new ProgressDialog(context);
}
#Override
protected String doInBackground(String... params) {
// make web service access task here
return null;
}
#Override
protected void onPostExecute(String result) {
// ProgressDialog here
}
}
I'm trying to dismiss dialog in AsyncTask's onPostExecute() and also set text in textview, but textview doesn't change and I get the "Window already focused, ignoring focus gain of...".
Here's the code:
protected void onPreExecute() {
dialog = ProgressDialog.show(mContext, "","Loading...", true);
}
protected void onPostExecute(Object result) {
dialog.dismiss();
tv.setText("some text");
}
Progress dialog is shown and when my background work is complete, it is dismissed but there's no change to textview. Without progress dialog, text view is updated.
Any idea, solution to this problem?
Thanks!
Try this code snippet after you have called dialog.dismiss().
if (!dialog.isShowing())
{
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText("some text");
}
public class MyActivity extends Activity
{
/**
* Called when the activity is first created.
*/
ProgressBar progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.pb);
TextView view=(TextView) findViewById(R.id.myt);
new Task(view).execute();
}
by passing TextView instance in constructor we can use in progressbar
private class Task extends AsyncTask<Void, Integer, Void> {
TextView view;
private Task(TextView textView) {
this.view= textView;
}
int myProgress;
#Override
protected void onPreExecute() {
myProgress = 0;
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(MyActivity.this,
"onPostExecute", Toast.LENGTH_LONG).show();
super.onPostExecute(aVoid);
}
#Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
view.setText("Value"+myProgress);
super.onProgressUpdate(values);
}
#Override
protected void onCancelled() {
super.onCancelled(); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
protected Void doInBackground(Void... voids) {
while (myProgress < 100) {
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}
}
}