簡體   English   中英

片段中的空指針異常

[英]Null Pointer Exception in fragment

空指針異常在片段中。 我試圖獲取坐標並將其放入TextView。 GPS正常工作。 但是不能設置文字。 這里有什么問題? 可能我必須使用適配器嗎? 我能做什么?

    tv.setText(g); // error (is null)




public class TwoFragment extends Fragment {
LocationService ls;
double s;
TextView tv;
String g;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Creating view correspoding to the fragment
    View v = inflater.inflate(R.layout.two_fragment, container, false);

    // Updating the action bar title
    getActivity().getActionBar();
    Log.w("MY_TAG", "One fragment");

   return v;

}

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

    ls  = new LocationService(getActivity());
    s   = ls.getLocation().getLatitude();
    tv  = (TextView) getView().findViewById(R.id.tv_two_fragment);
    g   = Double.toString(s);
    tv.setText(g);
}

}

錯誤日志

   05-19 10:36:01.052    2418-2418/com.example.projectx E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at com.fotoman.prox.app.MainFragments.TwoFragment.onCreate(TwoFragment.java:48)
        at android.app.Fragment.performCreate(Fragment.java:1673)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:854)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
        at android.app.BackStackRecord.run(BackStackRecord.java:682)
        at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
        at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
        at android.os.Handler.handleCallback(Handler.java:730)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5103)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

在Fragment的onCreateView中初始化textview。

View v = inflater.inflate(R.layout.two_fragment, container, false);
tv  = (TextView) v.findViewById(R.id.tv_two_fragment);
ls  = new LocationService(getActivity());
s   = ls.getLocation().getLatitude();
g   = Double.toString(s);
tv.setText(g);

getView()返回null。

http://developer.android.com/reference/android/app/Fragment.html#getView()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM