登录facebook里面的片段不起作用

时间:2017-04-18 06:19:50

标签: android android-fragments facebook-graph-api

after login it has to look like this image

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView mBottomNavigationView;
    String[] fragmentTitles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentTitles = getResources().getStringArray(R.array.bottom_nav);
        mBottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        mBottomNavigationView.setOnChildClickedListener(new OnChildClickedListener() {
            @Override
            public void onChildClicked(int child) {
                selectFragment(child);
            }
        });
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));

        if(savedInstanceState == null) {
            selectFragment(0);
            //getSupportActionBar().setTitle("Home");
        }
    }

    private void selectFragment(int child) {
        switch (child){
            case 0:
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
                        .replace(R.id.content, HomeFragment.newInstance(fragmentTitles[child], child))
                        .commit();
                break;
            case 1:
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
                        .replace(R.id.content, SearchFragment.newInstance(fragmentTitles[child], child))
                        .commit();
                break;
            case 2:
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
                        .replace(R.id.content, ProfileFragment.newInstance(fragmentTitles[child], child))
                        .commit();

        }

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                fragment.onActivityResult(requestCode, resultCode, data);
                Log.d("Activity", "ON RESULT CALLED");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("ERROR", e.toString());
        }
    }
} 

Profilefragment.java

    public class ProfileFragment extends Fragment {


    public static final String ARG_TITLE = "titleArg";
    public static final String ARG_INDEX = "indexArg";
    private static final String URL = "http://192.168.0.120:3002/new_user";
    LoginButton loginButton;
    TextView textView;
    CallbackManager callbackManager;

    public static ProfileFragment newInstance(String title, int index) {
        ProfileFragment fragment = new ProfileFragment();
        Bundle args = new Bundle();
        args.putString(ARG_TITLE, title);
        args.putInt(ARG_INDEX, index);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        FacebookSdk.sdkInitialize(getActivity());
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        //((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getArguments().getString(ARG_TITLE));
        // Inflate the layout for this fragment
        loginButton=(LoginButton)view.findViewById(R.id.fb_login_bn);
        loginButton.setReadPermissions(Arrays.asList("user_actions.music", "user_actions.video", "user_actions.news","email,user_hometown","user_religion_politics","user_likes","user_status","user_about_me","user_location","user_tagged_places","user_birthday","user_photos","user_videos","user_education_history","user_posts","user_website","user_friends","user_relationship_details","user_work_history","user_games_activity","user_relationships"));
        textView=(TextView)view.findViewById(R.id.textView);
        callbackManager=CallbackManager.Factory.create();
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
            /*GraphRequestAsyncTask graphRequestAsyncTask = new GraphRequest(loginResult.getAccessToken(),
                        "/me/friends",
                        null,
                        HttpMethod.GET,
                        new GraphRequest.Callback() {
                            @Override
                            public void onCompleted(GraphResponse response) {
                                try {
                                    JSONArray rawName = response.getJSONObject().getJSONArray("data");
                                    textView.setText("Login Success \n" +response);
                                } catch (JSONException e) {

                                }
                            }
                        }).executeAsync();*/
                textView.setText("Login Success \n"+
                        loginResult.getAccessToken().getUserId()+"\n"
                        +loginResult.getAccessToken().getToken()+"\n"+loginResult.getRecentlyGrantedPermissions());


                final String token =  loginResult.getAccessToken().getToken().toString();

                JSONObject jsonBodyObj = new JSONObject();
                try{

                    jsonBodyObj.put("accesstoken", token);

                }catch (JSONException e){
                    e.printStackTrace();
                }
                final String requestBody = jsonBodyObj.toString();

                JsonObjectRequest JOPR = new JsonObjectRequest(Request.Method.POST,
                        URL, null, new Response.Listener<JSONObject>(){
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            VolleyLog.v("Response:%n %s", response.toString(4));
                            System.out.print(URL);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.e("Error: ", error.getMessage());
                    }
                }){
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("Content-Type", "application/json");
                        return headers;
                    }


                    @Override
                    public byte[] getBody() {
                        try {
                            return requestBody == null ? null : requestBody.getBytes("utf-8");
                        } catch (UnsupportedEncodingException uee) {
                            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                                    requestBody, "utf-8");
                            return null;
                        }
                    }


                };
                RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
                requestQueue.add(JOPR);

            }

            @Override
            public void onCancel() {
                textView.setText("Login Canceled");
            }

            @Override
            public void onError(FacebookException error) {

            }
        });
        return view;
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
    Log.d("FRAGMENT", "onResultCalled");
    }

}

更新了Logcat

 W/System.err: java.lang.NullPointerException
W/System.err:     at com.example.prateek.bottomnavigation.MainActivity.onActivityResult(MainActivity.java:74)
W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:5423)
W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:3387)
W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3434)
W/System.err:     at android.app.ActivityThread.access$1300(ActivityThread.java:138)
W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err:     at android.os.Looper.loop(Looper.java:149)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5045)
W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
W/System.err:     at dalvik.system.NativeStart.main(Native Method)
D/ERROR: java.lang.NullPointerException

在运行此内部片段代码时遇到错误,但如果我在任何活动中运行相同的代码,那么它可以正常工作。我正在努力解决问题,但无法获得解决方案,请帮助我。 谢谢

3 个答案:

答案 0 :(得分:3)

您需要在开始时onCreateView初始化Facebook Sdk ..

FacebookSdk.sdkInitialize(getActivity());

您还需要使用

来扩充布局并找到您的元素
View view = inflater.inflate(R.layout.fragment_profile, container, false); 
loginButton=(LoginButton) view.findViewById(R.id.fb_login_bn);

使用此代码:

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        FacebookSdk.sdkInitialize(getActivity());
        callbackManager= CallbackManager.Factory.create();
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        //((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getArguments().getString(ARG_TITLE));
        // Inflate the layout for this fragment
        loginButton=(LoginButton) view.findViewById(R.id.fb_login_bn);
//        loginButton.setReadPermissions(Arrays.asList("user_actions.music", "user_actions.video", "user_actions.news","email,user_hometown","user_religion_politics","user_likes","user_status","user_about_me","user_location","user_tagged_places","user_birthday","user_photos","user_videos","user_education_history","user_posts","user_website","user_friends","user_relationship_details","user_work_history","user_games_activity","user_relationships"));
        textView=(TextView)view.findViewById(R.id.textView);
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
            /*GraphRequestAsyncTask graphRequestAsyncTask = new GraphRequest(loginResult.getAccessToken(),
                        "/me/friends",
                        null,
                        HttpMethod.GET,
                        new GraphRequest.Callback() {
                            @Override
                            public void onCompleted(GraphResponse response) {
                                try {
                                    JSONArray rawName = response.getJSONObject().getJSONArray("data");
                                    textView.setText("Login Success \n" +response);
                                } catch (JSONException e) {

                                }
                            }
                        }).executeAsync();*/
                textView.setText("Login Success \n"+
                        loginResult.getAccessToken().getUserId()+"\n"
                        +loginResult.getAccessToken().getToken()+"\n"+loginResult.getRecentlyGrantedPermissions());


                final String token =  loginResult.getAccessToken().getToken().toString();

                JSONObject jsonBodyObj = new JSONObject();
                try{

                    jsonBodyObj.put("accesstoken", token);

                }catch (JSONException e){
                    e.printStackTrace();
                }
                final String requestBody = jsonBodyObj.toString();

                JsonObjectRequest JOPR = new JsonObjectRequest(Request.Method.POST,
                        URL, null, new Response.Listener<JSONObject>(){
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            VolleyLog.v("Response:%n %s", response.toString(4));
                            System.out.print(URL);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.e("Error: ", error.getMessage());
                    }
                }){
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("Content-Type", "application/json");
                        return headers;
                    }


                    @Override
                    public byte[] getBody() {
                        try {
                            return requestBody == null ? null : requestBody.getBytes("utf-8");
                        } catch (UnsupportedEncodingException uee) {
                            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                                    requestBody, "utf-8");
                            return null;
                        }
                    }


                };
                RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
                requestQueue.add(JOPR);

            }

            @Override
            public void onCancel() {
                textView.setText("Login Canceled");
            }

            @Override
            public void onError(FacebookException error) {

            }
        });
        return view;
    }

此外,onActivityResult()无法使用...您需要添加callbackManager.onActivityResult(requestCode, resultCode, data);

片段中的

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
        Log.d("FRAGMENT", "onResultCalled");
    }

您的父活动添加:否则将不会调用片段的onActivityResult()

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        try {
            for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                fragment.onActivityResult(requestCode, resultCode, data);
                Log.d("Activity", "ON RESULT CALLED");
            }
        } catch (Exception e) {
            Log.d("ERROR", e.toString());
        }
    }

答案 1 :(得分:1)

在活动中使用此代码而非片段

@Override
        public void onActivityResult(int requestCode, int resultCode, Intent data){
            Fragment fragment = getFragmentManager().findFragmentById(R.id.com_facebook_fragment_container);
            fragment.onActivityResult(requestCode, resultCode, data);
        }
片段中的

添加

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (FacebookSdk.isInitialized()) {
            callbackManager.onActivityResult(requestCode, resultCode, data);
        }
    }

答案 2 :(得分:0)

您的错误显示loginButton为空,您使用了container的引用来创建LoginButton的对象,而不是在View处创建onCreateView()的对象{1}}

View view = inflater.inflate(R.layout.fragment_profile, container, false);

现在,只要从xml访问任何控件/窗口小部件,就会引用此view,例如

loginButton=(LoginButton)view.findViewById(R.id.fb_login_bn);

也可以为其他对象创建它,并且你的return语句应该是

return view;