0

我正在尝试将字符串值“url”传递给片段以在 Web 视图中显示它。我不断收到以下错误:

java.lang.NullPointerException

这是我的代码:

protected void goToTab1View() {
    if(mTabState != TAB1_STATE){
        mTabState = TAB1_STATE;
        Toast.makeText(getActivity(), "goToTabView1: " + url, Toast.LENGTH_SHORT).show();
        FragmentManager fm = getFragmentManager();
        if(fm!= null){
            //Perform fragment transaction
            FragmentTransaction ft = fm.beginTransaction();
            FragTab1 f = new FragTab1();
            f.setString(url);
            ft.replace(R.id.fragment_content, f);
            ft.commit();
        }
    }
}

我想我没有正确附加片段??我只是对片段不熟悉,所以如果问题很明显,我深表歉意。任何帮助将非常感激。

堆栈跟踪:

 01-11 13:16:06.671: E/AndroidRuntime(23045): FATAL EXCEPTION: main
01-11 13:16:06.671: E/AndroidRuntime(23045): java.lang.NullPointerException
01-11 13:16:06.671: E/AndroidRuntime(23045):    at android.widget.Toast.<init>(Toast.java:92)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at android.widget.Toast.makeText(Toast.java:238)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at com.example.tabdemo.FragTab1.setString(FragTab1.java:57)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at com.example.tabdemo.TabFragment.goToTab1View(TabFragment.java:60)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at com.example.tabdemo.MainActivity$1.onClick(MainActivity.java:34)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at android.view.View.performClick(View.java:4202)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at android.view.View$PerformClick.run(View.java:17340)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at android.os.Handler.handleCallback(Handler.java:725)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at android.os.Looper.loop(Looper.java:137)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at android.app.ActivityThread.main(ActivityThread.java:5039)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at java.lang.reflect.Method.invokeNative(Native Method)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at java.lang.reflect.Method.invoke(Method.java:511)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-11 13:16:06.671: E/AndroidRuntime(23045):    at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

1

看起来您正在FragmentsetString()中显示 Toast。FragTab1这就是你面临的原因NullPointerException

setString()删除里面的Toast DisplayFragTab1并运行它会为你工作的应用程序。

除非 FragTab1 附加到 Fragment Container,否则getActivity()在通过如下设置 String 替换 FragTab1 Fragment 之前,您不会得到您正在访问的内容

f.setString(url);

这将调用 FragTab1 的 setString(),您将在其中显示 Toast,这将导致 NullPointerException,因为它无法获取上下文。

于 2013-01-11T13:20:23.523 回答