getActivity == null,尝试onattach

时间:2013-11-24 17:26:26

标签: java android facebook fragment adapter

我尝试启动我的应用程序,我可以看到我的片段正在加载,但每当我的适配器尝试将数据放入我的listview时,我的应用程序崩溃了。这是因为我的getActivity()= null。现在我试着查一下,发现你必须OnAttach吗?但是我尝试了它,或者我做错了..它没有用,任何人都可以帮我恳求吗?

这是错误:

11-24 13:00:27.429: E/AndroidRuntime(31304): FATAL EXCEPTION: main
11-24 13:00:27.429: E/AndroidRuntime(31304): java.lang.NullPointerException
11-24 13:00:27.429: E/AndroidRuntime(31304):    at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:153)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at com.laurenswuyts.witpa.ListEventAdapter.<init>(ListEventAdapter.java:23)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at com.laurenswuyts.witpa.EventFragment.parseEventFromFQLResponse(EventFragment.java:154)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at com.laurenswuyts.witpa.EventFragment$2.onCompleted(EventFragment.java:119)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at com.facebook.Request$4.run(Request.java:1669)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at android.os.Handler.handleCallback(Handler.java:615)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at android.os.Handler.dispatchMessage(Handler.java:92)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at android.os.Looper.loop(Looper.java:137)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at android.app.ActivityThread.main(ActivityThread.java:4944)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at java.lang.reflect.Method.invokeNative(Native Method)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at java.lang.reflect.Method.invoke(Method.java:511)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
11-24 13:00:27.429: E/AndroidRuntime(31304):    at dalvik.system.NativeStart.main(Native Method)

这是我的主要活动:

    public class EventFragment extends Fragment  {

        //Arraylist with event details
        private static List<EventDetails> dataEvent;

        //Adapter to put event details in listview
        ListEventAdapter eventAdapter;

        //Listview with the events
        ListView lvEvents;

        //To show Progress Circle
        LinearLayout linearProgress;

        private static final String TAG = "EventFragment";

        private static final int REAUTH_ACTIVITY_CODE = 100;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

        @Override
        public View onCreateView(LayoutInflater inflater, 
                ViewGroup container, Bundle savedInstanceState) {
            super.onCreateView(inflater, container, savedInstanceState);
            View view = inflater.inflate(R.layout.event, 
                    container, false);
            linearProgress = (LinearLayout) view.findViewById(R.id.linProgress);
            lvEvents = (ListView) view.findViewById(R.id.lvEvent);
            // Check for an open session
            Session session = Session.getActiveSession();
            if (session != null && session.isOpened()) {
                // Get the user's data
                ShowEventsFromFQL();

            }
            return view;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            uiHelper = new UiLifecycleHelper(getActivity(), callback);
            uiHelper.onCreate(savedInstanceState);


        }


        public void ShowEventsFromFQL(){
             // Check for an open session
            Session session = Session.getActiveSession();
            if (session != null && session.isOpened()) {

                //Progressbar active        
                linearProgress.setVisibility(View.VISIBLE);


                // Get the user's data
                // ORDER BY attending_count DESC
                String fqlQuery = ".....";
                Bundle params = new Bundle();
                params.putString("q", fqlQuery);
                Session session2 = Session.getActiveSession();
                Request request = new Request(session2,
                    "/fql",                         
                    params,                         
                    HttpMethod.GET,                 
                    new Request.Callback(){         
                        public void onCompleted(Response response) {
                            Log.i(TAG, "Result: " + response.toString());
                            parseEventFromFQLResponse(response);                                                
                        }                  
                }); 
                Request.executeBatchAsync(request);
        }         
        }

        public final void parseEventFromFQLResponse( Response response )
        {
            dataEvent = new ArrayList<EventDetails>();
            try
            {
                GraphObject graphObj  = response.getGraphObject();
                JSONObject  jsonObj = graphObj.getInnerJSONObject();
                JSONArray   jsonArr = jsonObj.getJSONArray( "data" );

                for ( int i = 0; i < ( jsonArr.length() ); i++ )
                {
                    JSONObject jObject = jsonArr.getJSONObject( i );

                      int attending_count = jObject.getInt("attending_count");
                      String name = jObject.getString("name");
                      String host = jObject.getString("host");
                      String description = jObject.getString("description");
                      String location = jObject.getString("location");        
                      String start_time = jObject.getString("start_time");   
                      String end_time = jObject.getString("end_time"); 


                      dataEvent.add(new EventDetails(attending_count, name, host, description, location, start_time, end_time));


                }
            // if(dataEvent != null){
 if(getActivity() == null){
                Log.i(TAG, "Result: loser" );
            }
            else {
                Log.i(TAG, "Result: nope" );
            }

                 eventAdapter = new ListEventAdapter(getActivity(), R.layout.event_item, dataEvent);

                 lvEvents.setAdapter(eventAdapter);
                 eventAdapter.notifyDataSetChanged();

                //Progressbar gone
                 linearProgress.setVisibility(View.GONE);

             //  }
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }


        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == REAUTH_ACTIVITY_CODE) {
                uiHelper.onActivityResult(requestCode, resultCode, data);
            }
        }


        private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
            if (session != null && session.isOpened()) {
                // Get the user's data.
                ShowEventsFromFQL();

            }
        }

        private UiLifecycleHelper uiHelper;
        private Session.StatusCallback callback = new Session.StatusCallback() {
            @Override
            public void call(final Session session, final SessionState state, final Exception exception) {
                onSessionStateChange(session, state, exception);
            }
        };

        @Override
        public void onResume() {
            super.onResume();
            uiHelper.onResume();
        }

        @Override
        public void onSaveInstanceState(Bundle bundle) {
            super.onSaveInstanceState(bundle);
            uiHelper.onSaveInstanceState(bundle);
        }

        @Override
        public void onPause() {
            super.onPause();
            uiHelper.onPause();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            uiHelper.onDestroy();
        }


    }

提前致谢!!

2 个答案:

答案 0 :(得分:0)

您在片段的onCreateView()方法中做了很多工作。一旦片段创建其用户界面,Android就会调用onCreateView()方法。我建议将执行异步部分的部分移动到onActiviyCreated(),例如:

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


    // Check for an open session
    Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {
        // Get the user's data
        ShowEventsFromFQL();
    }
}

答案 1 :(得分:0)

我实际上没有挖掘源代码以确认这一点,但根据我的经验,当您从XML中膨胀片段或将其添加到活动的onCreate中时,getActivity()onCreateView()之前无效。 }或onActivityCreated()。我通常不会使用onAttached()来表明getActivity()有效。