使用片段中的上下文时出错

时间:2014-12-24 05:07:26

标签: android android-context

一切正常。问题 - 我好吗?以及如何调用contexthow来调用这个方法?

在MyActivity中:

@Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }

在我的片段中我称之为方法:

 public void setData(){
        new MyAsincTask(getActivity()){

            @Override
            protected void onPreExecute() {
            }

            @Override
            protected void onPostExecute(Document document) {
                super.onPostExecute(document);
               ........

                getActivity().setTitle("Сотрудники(city:" + city + ",holiday:" + holiday + ")");
            }


        }.execute(link);
    }

它有效。但如果在此过程中移动到应用程序的另一部分崩溃

但是如果你添加

if (getActivity()!=null)
                getActivity().setTitle("Сотрудники(city:" + city + ",holiday:" + holiday + ")");
一切正常。问题 - 我好吗?以及如何调用上下文

12-24 05:18:28.805      460-460/com.managment.pavel.managmentgradle E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.managment.pavel.managmentgradle.fragments.EmployeessList$1.onPostExecute(EmployeessList.java:114)
            at com.managment.pavel.managmentgradle.fragments.EmployeessList$1.onPostExecute(EmployeessList.java:69)
            at android.os.AsyncTask.finish(AsyncTask.java:417)
            at android.os.AsyncTask.access$300(AsyncTask.java:127)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:130)
            at android.app.ActivityThread.main(ActivityThread.java:3683)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)