尝试将EditText中的URL传递给Fragment

时间:2013-01-11 13:13:29

标签: android webview fragment

我正在尝试传递一个字符串值" 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();
        }
    }
}

我认为我没有正确附加片段?我只是片段的新手,所以如果问题很明显,我道歉。任何帮助将不胜感激。

STACK TRACE:

 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)

1 个答案:

答案 0 :(得分:1)

看起来您正在setString()片段的FragTab1内显示Toast。这就是您面对NullPointerException

的原因

删除setString() FragTab1内的Toast显示,然后运行适合您的应用。

除非FragTab1附加到Fragment Container,否则在更换FragTab1片段之前,您不会得到getActivity(),而是将String设置为如下所示

f.setString(url);

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