片段中的空指针异常

时间:2014-05-19 10:46:39

标签: java android android-fragments gps

片段中的空指针异常。我试图获取坐标并将其放到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)

1 个答案:

答案 0 :(得分:1)

在片段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()

相关问题