android中的tabHost.addTab()

时间:2012-03-15 16:33:37

标签: android android-intent

我正在尝试使用main来启动3个选项卡,并且每个选项卡都指向一个单独的java / xml文件。我成功地使用#deprecation为4.0平台创建了它,并且它在2.3.3中正常工作但是一段时间后它已停止工作。我已经完成调试,无法弄清问题是什么。任何帮助,将不胜感激。 附件是main.java / main.xml和日志。如果您还需要,请告诉我。

Main.java

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;

public class Main extends TabActivity {

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

        Resources res = getResources(); // Resource object to get Drawables
        TabHost tabHost = getTabHost(); // The activity TabHost
        TabHost.TabSpec spec; // Resusable TabSpec for each tab
        Intent intent; // Reusable Intent for each tab

        // Create an Intent to launch an Activity for the tab (to be reused)
        intent = new Intent().setClass(this, Joke.class);

        // Initialize a TabSpec for each tab and add it to the TabHost
        spec = tabHost.newTabSpec("Joke")
                .setIndicator("", res.getDrawable(R.drawable.ic_tab_joke))
                .setContent(intent);
        tabHost.addTab(spec);

        // Do the same for the other tabs
        intent = new Intent().setClass(this, Picture.class);
        spec = tabHost.newTabSpec("Picture")
                .setIndicator("", res.getDrawable(R.drawable.ic_tab_picture))
                .setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass(this, Video.class);
        spec = tabHost.newTabSpec("Video")
                .setIndicator("", res.getDrawable(R.drawable.ic_tab_video))
                .setContent(intent);
        tabHost.addTab(spec);

        tabHost.setCurrentTab(1);
    }
}

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="0dp" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:tabStripEnabled="false" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="5dp" />
    </LinearLayout>

</TabHost>

LOG

03-15 16:26:49.625: I/ActivityManager(61): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.example.oftheday/.Main } from pid 132
03-15 16:26:49.805: I/ActivityManager(61): Start proc com.example.oftheday for activity com.example.oftheday/.Main: pid=345 uid=10035 gids={3003}
03-15 16:26:50.365: I/ARMAssembler(61): generated scanline__00000177:03515104_00001002_00000000 [ 87 ipp] (110 ins) at [0x444ea6f0:0x444ea8a8] in 423460 ns
03-15 16:26:50.964: D/AndroidRuntime(345): Shutting down VM
03-15 16:26:50.964: W/dalvikvm(345): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-15 16:26:50.984: E/AndroidRuntime(345): FATAL EXCEPTION: main
03-15 16:26:50.984: E/AndroidRuntime(345): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.oftheday/com.example.oftheday.Main}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.oftheday/com.example.oftheday.Joke}: java.lang.NullPointerException
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.os.Looper.loop(Looper.java:123)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.ActivityThread.main(ActivityThread.java:3683)
03-15 16:26:50.984: E/AndroidRuntime(345):  at java.lang.reflect.Method.invokeNative(Native Method)
03-15 16:26:50.984: E/AndroidRuntime(345):  at java.lang.reflect.Method.invoke(Method.java:507)
03-15 16:26:50.984: E/AndroidRuntime(345):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-15 16:26:50.984: E/AndroidRuntime(345):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-15 16:26:50.984: E/AndroidRuntime(345):  at dalvik.system.NativeStart.main(Native Method)
03-15 16:26:50.984: E/AndroidRuntime(345): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.oftheday/com.example.oftheday.Joke}: java.lang.NullPointerException
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.ActivityThread.startActivityNow(ActivityThread.java:1487)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:654)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.widget.TabHost.setCurrentTab(TabHost.java:326)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.widget.TabHost.addTab(TabHost.java:216)
03-15 16:26:50.984: E/AndroidRuntime(345):  at com.example.oftheday.Main.onCreate(Main.java:27)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-15 16:26:50.984: E/AndroidRuntime(345):  ... 11 more
03-15 16:26:50.984: E/AndroidRuntime(345): Caused by: java.lang.NullPointerException
03-15 16:26:50.984: E/AndroidRuntime(345):  at java.io.Reader.<init>(Reader.java:65)
03-15 16:26:50.984: E/AndroidRuntime(345):  at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
03-15 16:26:50.984: E/AndroidRuntime(345):  at java.io.InputStreamReader.<init>(InputStreamReader.java:59)
03-15 16:26:50.984: E/AndroidRuntime(345):  at com.example.oftheday.Joke.DownloadText(Joke.java:62)
03-15 16:26:50.984: E/AndroidRuntime(345):  at com.example.oftheday.Joke.onCreate(Joke.java:19)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-15 16:26:50.984: E/AndroidRuntime(345):  ... 20 more
03-15 16:26:50.994: W/ActivityManager(61):   Force finishing activity com.example.oftheday/.Main

从我能理解的是它指向main.java的第27行但是该行是         tabHost.addTab(SPEC);我看不出任何问题。

感谢帮助:D

编辑1 - Joke.java

package com.example.oftheday;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Joke extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String str = DownloadText("test.com/text.txt"); // line 19
        TextView jokeview = new TextView(this);
        jokeview.setText(str);

        TextView textview = new TextView(this);
        textview.setText("" + str);
        setContentView(R.layout.joke);

    }

    private InputStream OpenHttpConnection(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }

    private String DownloadText(String URL) {
        int BUFFER_SIZE = 2000;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "";
        }
        InputStreamReader isr = new InputStreamReader(in); // line 62
        int charRead;
        String str = "";
        char[] inputBuffer = new char[BUFFER_SIZE];
        try {
            while ((charRead = isr.read(inputBuffer)) > 0) {
                // ---convert the chars to a String---
                String readString = String
                        .copyValueOf(inputBuffer, 0, charRead);
                str += readString;
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
        return str;
    }
}

Joke.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/jotd"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

异常一直级联到main.java,但异常的原因在堆栈跟踪中较低:

03-15 16:26:50.984: E/AndroidRuntime(345): Caused by: java.lang.NullPointerException
03-15 16:26:50.984: E/AndroidRuntime(345):  at java.io.Reader.<init>(Reader.java:65)
03-15 16:26:50.984: E/AndroidRuntime(345):  at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
03-15 16:26:50.984: E/AndroidRuntime(345):  at java.io.InputStreamReader.<init>(InputStreamReader.java:59)
03-15 16:26:50.984: E/AndroidRuntime(345):  at com.example.oftheday.Joke.DownloadText(Joke.java:62)
03-15 16:26:50.984: E/AndroidRuntime(345):  at com.example.oftheday.Joke.onCreate(Joke.java:19)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-15 16:26:50.984: E/AndroidRuntime(345):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-15 16:26:50.984: E/AndroidRuntime(345):  ... 20 more

所以问题是在com.example.oftheday.Joke.DownloadText内你能发布该类的代码吗?您还可以在Eclipse上设置断点。了解如何操作here


<强>更新

好的,首先看一下naming conventions。有些位难以阅读。

其次,我认为问题是你试图打开不存在的“test.com/text.txt”,因此,在OpenHttpConnection()内,条件response == HttpURLConnection.HTTP_OK永远不会成立,因此返回的InputStream保持为空(为您提供NullPointerException

希望它有所帮助。