gpt4 book ai didi

android - 使用 fragment 中的 Facebook 登录无法正常工作

转载 作者:太空狗 更新时间:2023-10-29 16:29:13 25 4
gpt4 key购买 nike

after login it has to look like this image

主 Activity .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

虽然在 fragment 代码中运行此代码时出现错误,但如果我在任何 Activity 中运行相同的代码,则它可以正常工作。我正在努力解决问题,但无法获得解决方案,请帮助我。谢谢你

最佳答案

一开始需要在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);

在您的 fragment 中:

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

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

并且你的父activity添加:否则不会调用fragment的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());
}
}

关于android - 使用 fragment 中的 Facebook 登录无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43464964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com