有人可以帮助我如何将Facebook用户个人资料存储到解析库吗?我做了一个Android应用程序。我想要的是用户登录Facebook后,用户的信息(如电子邮件,姓名,性别)存储到解析库,然后应用程序显示新的活动。但是,我的应用程序在验证facebook登录后陷入登录对话框并且不存储任何解析库。有人能帮我吗?非常感谢
这是MainActivity.java
package com.contoh.mutia.persistentlogin;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseUser;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends Activity {
public Dialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check if there is a currently logged in user
// and they are linked to a Facebook account.
ParseUser currentUser = ParseUser.getCurrentUser();
if ((currentUser != null) && ParseFacebookUtils.isLinked(currentUser)) {
// Go to the user info activity
showwelkamActivity();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.finishAuthentication(requestCode, resultCode, data);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onLoginClick(View v) {
MainActivity.this.progressDialog = ProgressDialog.show(
MainActivity.this, "", "Logging in...", true);
List<String> permissions = Arrays.asList("public_profile", "email");
ParseFacebookUtils.logIn(permissions, this, new LogInCallback() {
@Override
public void done(ParseUser user, ParseException err) {
MainActivity.this.progressDialog.dismiss();
if (user == null) {
Log.d(IsianParse.TAG,
"Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d(IsianParse.TAG,
"User signed up and logged in through Facebook!");
showwelkamActivity();
} else {
Log.d(IsianParse.TAG,
"User logged in through Facebook!");
showwelkamActivity();
}
}
});
}
private void showwelkamActivity() {
Intent intent = new Intent(this, welkampage.class);
startActivity(intent);
}
}
这是welkampage.java我想在登录facebook成功后显示的新活动
package com.contoh.mutia.persistentlogin;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.facebook.FacebookRequestError;
import com.facebook.LoginActivity;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.parse.ParseFacebookUtils;
import com.parse.ParseUser;
import org.json.JSONException;
import org.json.JSONObject;
public class welkampage extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welkampage);
// Fetch Facebook user info if the session is active
Session session = ParseFacebookUtils.getSession();
if (session != null && session.isOpened()) {
makeMeRequest();
}
}
@Override
public void onResume() {
super.onResume();
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
// Check if the user is currently logged
// and show any cached content
showwelkamActivity();
} else {
// If the user is not logged in, go to the
// activity showing the login view.
startLoginActivity();
}
}
private void showwelkamActivity() {
Intent intent = new Intent(this, welkampage.class);
startActivity(intent);
}
private void makeMeRequest() {
Request request = Request.newMeRequest(ParseFacebookUtils.getSession(),
new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// Create a JSON object to hold the profile info
JSONObject userProfile = new JSONObject();
try {
// Populate the JSON object
userProfile.put("facebookId", user.getId());
userProfile.put("name", user.getName());
if (user.getProperty("gender") != null) {
userProfile.put("gender", user.getProperty("gender"));
}
if (user.getProperty("email") != null) {
userProfile.put("email", user.getProperty("email"));
}
// Save the user profile info in a user property
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.put("profile", userProfile);
currentUser.saveInBackground();
} catch (JSONException e) {
Log.d(IsianParse.TAG, "Error parsing returned user data. " + e);
}
} else if (response.getError() != null) {
if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY) ||
(response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {
Log.d(IsianParse.TAG, "The facebook session was invalidated." + response.getError());
logout();
} else {
Log.d(IsianParse.TAG,
"Some other error: " + response.getError());
}
}
}
}
);
request.executeAsync();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_welkampage, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onLogoutClick(View v) {
logout();
}
private void logout() {
// Log the user out
ParseUser.logOut();
// Go to the login view
startLoginActivity();
}
private void startLoginActivity() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
这是Isianparse.java
package com.contoh.mutia.persistentlogin;
import android.app.Application;
import com.parse.Parse;
public class IsianParse extends Application {
static final String TAG = "MyApp";
@Override
public void onCreate() {
super.onCreate();
Parse.initialize(this,"appid","mykey");
}}
答案 0 :(得分:2)
我在同一条船上,我是使用解析的新手,这对我有用。
//Make sure that a session is opened and that you asked for the required permission
if(ParseFacebookUtils.getSession().isOpened())
{
Request.newMeRequest(ParseFacebookUtils.getSession(), new Request.GraphUserCallback()
{
@Override
public void onCompleted(GraphUser user, Response response)
{
if (user != null)
{
String Name = user.getName;
String email = user.getEmail;
//Use the get Method to get the info from facebook
//Then save it to the parse DB
ParseObject post = new ParseObject("post");
post.put("name", Name);
post.saveInBackground();
}
}
}).executeAsync();
}
答案 1 :(得分:0)
我的LoginFragment看起来像这样,并将用户的Facebook名称存储到共享首选项。我使用https://developers.facebook.com/docs/android/login-with-facebook/v2.1来实现登录,使用https://developers.facebook.com/docs/graph-api/reference/v2.2/来从登录用户获取数据。
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.*;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginFragment extends Fragment {
private static final String TAG = "LoginFragment";
private UiLifecycleHelper uiHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
return view;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
final SharedPreferences prefs = getActivity().getSharedPreferences(
"fbInfo", Context.MODE_PRIVATE);
if (session != null && session.getState().isOpened()) {
Log.i("sessionToken", session.getAccessToken());
Log.i("sessionTokenDueDate", session.getExpirationDate().toLocaleString());
}
Bundle params = new Bundle();
params.putString("access_token", session.getAccessToken());
new Request(session, "/me", params, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
try {
prefs.edit().putString("name", graphResponse.getString("name")).commit();
//Toast.makeText(getActivity(), "Welcome " + graphResponse.getString("name"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.i(TAG, "JSON error " + e.getMessage());
}
}
}
).executeAsync();
Request.newMeRequest(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
try {
String userId = user.getId();
prefs.edit().putString("id", userId).commit();
prefs.edit().putString("profile_url", "https://graph.facebook.com/"
+ user.getId() + "/picture?type=large").commit();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
Intent i = new Intent(getActivity(), MainPage.class);
startActivity(i);
Log.i(TAG, "Logged in...");
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
@Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(getActivity(), requestCode,
resultCode, data);
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}