Android developers provide R.id.progress links among the built-in resources of available resources.
However, when I issue (in my activity class) a statement:
View pv = getWindow().findViewById(android.R.id.progress);
It returns null.
It returns null even if I use it in conjunction with the ProgressBar
class:
ProgressBar pv = (ProgressBar) getWindow().findViewById(android.R.id.progress);
And it returns null even without getWindow () :
ProgressBar pv = (ProgressBar) findViewById(android.R.id.progress);
Any idea why?
So that I would not hallucinate, I followed the advice of @Geobits and created a new project from scratch containing the exact code specified in the blog post recommended by @ArunGeorge below:
package com.droidworks; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.widget.ProgressBar; public class ProgressBarExampleActivity extends Activity { private ProgressBar mProgress; private MyThread mBgThread; private final Handler mHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mProgress = (ProgressBar) findViewById(android.R.id.progress); mBgThread = (MyThread) getLastNonConfigurationInstance(); if (mBgThread == null) { mBgThread = new MyThread(); mBgThread.start(); } mHandler.post(mThreadWatcher); } @Override public Object onRetainNonConfigurationInstance() { return mBgThread; } @Override protected void onPause() { mHandler.removeCallbacks(mThreadWatcher); super.onPause(); } private Runnable mThreadWatcher = new Runnable() { public void run() { int progress = mBgThread.getProgress(); mProgress.setProgress(progress); if (progress != 100) mHandler.postDelayed(this, 50); } }; static class MyThread extends Thread { private int _progress = 0; public void run() { for (; _progress < 100; _progress++) { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } private int getProgress() { return _progress; } } }
Of course, this code raises a NullPointerException
:
at com.droidworks.ProgressBarExampleActivity$1.run(ProgressBarExampleActivity.java:44) at android.os.Handler.handleCallback(Handler.java:587) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:123) at android.app.ActivityThread.main(ActivityThread.java:4627) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:521) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) at dalvik.system.NativeStart.main(Native Method)
source share