开发者

Having problems controlling title bar progress bar in android

I am creating an app that has 4 tabs displaying 4 different feeds from websites. What I wanna do is display a progress bar in a custom title bar every time the user click on a tab and then hide the progress bar once the feed is done loading.

Here's my title bar layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/titlebar"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_height="30dip"
    android:layout_width="fill_parent"
    android:gravity="center_vertical"
    android:padding="0dip"
    android:background="#055843">
    <TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/title"
    android:text="TheGangGreen"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:textColor="#ffffff"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="4dp"
    android:textStyle="bold" />
    <ProgressBar 
    android:id="@+id/progress_bar" style="?android:attr/progressBarStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_marginRight="5dp" />
</RelativeLayout>

main class:

public class Main extends TabActivity {
    private static final String TAG = "MyActivity";
    ProgressBar titleProgressBar;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
        titleProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
        titleProgressBar.setVisibility(ProgressBar.GONE);

        //tab related stuff goes here
   }

   Handler progressHandle = new Handler(){
        public void handleMessage(Message msg){
            Log.d(TAG, "message = " + msg.arg1);
            if(msg.arg1 == 1){ // show progress
                showProgressBar();
            }
            else {
                hideProgressBar();
            }
        }
    };

    public void showProgressBar(){
            Log.d(TAG, "show progress bar");
        titleProgressBar.setVisibility(ProgressBar.VISIBLE);
    }
}

one of the tab classes:

public class NewsTab extends Activity {
    private static final String TAG = "MyActivity";
    private static final String newsURL = "http://blahblah";
    ListView newsList;
    FeedAdapter arrayAdapter;
    ArrayList<news> news = null;
    Main main;

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newsview);

        newsList = (ListView)findViewById(R.id.news_list);

        news = new ArrayList<news>();

        arrayAdapter = new FeedAdapter(NewsTab.this, R.layout.news_item, news);
        newsList.setAdapter(arrayAdapter);
        main = new Main();
        new GetFeedTask().execute(this.newsURL);
    }

    private class GetFeedTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... urls) {
            // TODO Auto-generated method stub
            Random randomizer = new Random(System.currentTimeMillis());
            String responseBody = "";
            try {
                URL feedUrl = new URL(urls[0] + "?" + randomizer.nextInt(10000));
                URLConnection tc = feedUrl.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
                String line;

                while ((line = in.readLine()) != null) {
                    responseBody += line;
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            return responseBody;
        }

        protected void onPreExecute(){
            Message msg = new Message();
            msg.arg1 = 1;
            main.progressHandle.sendMessage(msg);
        }

        protected void onPostExecute(String response) {
            try {
                Type collectionType = new TypeToken<ArrayList<news>>(){}.getType();
                List<news> lst = new Gson().fromJson(response, collectionType);
                Message msg = new Message();
                msg.arg1 = 2;
                main.progressHandle.sendMessage(msg);
                news.clear(); // clear the adapter array so an updated list won't be appended to the existing one
 开发者_运维问答               for(news l : lst)
                {
                    news.add(l);
                }
                arrayAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }
}

So, the message from onPreExecute is being sent correctly, but titleProgressBar.setVisibility(ProgressBar.VISIBLE); in showProgressBar results in a NullPointerException.

Thank you

Here's my LogCat:

D/AndroidRuntime(  423): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<

D/AndroidRuntime(  423): CheckJNI is ON

D/AndroidRuntime(  423): --- registering native functions ---

I/ActivityManager(   59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.tgg.test/.SplashScreen }

D/AndroidRuntime(  423): Shutting down VM

D/dalvikvm(  423): Debugger has detached; object registry had 1 entries

I/ActivityManager(   59): Start proc com.tgg.test for activity com.tgg.test/.SplashScreen: pid=430 uid=10047 gids={3003}

I/AndroidRuntime(  423): NOTE: attach of thread 'Binder Thread #3' failed

I/ActivityManager(   59): Displayed activity com.tgg.test/.SplashScreen: 1725 ms (total 420542 ms)

I/ActivityManager(   59): Starting activity: Intent { cmp=com.tgg.test/.Main }

D/MyActivity(  430): resume

D/MyActivity(  430): message = 1

D/AndroidRuntime(  430): Shutting down VM

W/dalvikvm(  430): threadid=1: thread exiting with uncaught exception (group=0x4001d800)

E/AndroidRuntime(  430): FATAL EXCEPTION: main

E/AndroidRuntime(  430): java.lang.NullPointerException

E/AndroidRuntime(  430):    at com.tgg.test.Main.showProgressBar(Main.java:76)

E/AndroidRuntime(  430):    at com.tgg.test.Main$1.handleMessage(Main.java:67)

E/AndroidRuntime(  430):    at android.os.Handler.dispatchMessage(Handler.java:99)

E/AndroidRuntime(  430):    at android.os.Looper.loop(Looper.java:123)

E/AndroidRuntime(  430):    at android.app.ActivityThread.main(ActivityThread.java:4627)

E/AndroidRuntime(  430):    at java.lang.reflect.Method.invokeNative(Native Method)

E/AndroidRuntime(  430):    at java.lang.reflect.Method.invoke(Method.java:521)

E/AndroidRuntime(  430):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)

E/AndroidRuntime(  430):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

E/AndroidRuntime(  430):    at dalvik.system.NativeStart.main(Native Method)

W/ActivityManager(   59):   Force finishing activity com.tgg.test/.Main

W/ActivityManager(   59): Activity pause timeout for HistoryRecord{450a2a20 com.tgg.test/.Main}

I/global  (  430): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.

I/Process (  430): Sending signal. PID: 430 SIG: 9

I/WindowManager(   59): WIN DEATH: Window{450aa2a8 com.tgg.test/com.tgg.test.SplashScreen paused=true}

I/ActivityManager(   59): Process com.tgg.test (pid 430) has died.


In your parent activity, before you do anything, you need to do the requestWindowFeature call, and then in your child activity you call

 getParent().setProgressBarIndeterminateVisibility(true/false);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜