我正在完成facebook android sdk教程: https://developers.facebook.com/docs/android/scrumptious/show-friends 一切都很顺利,直到我进入Step3c。它运行,但当我点击按钮,它会显示一个视图,视图是空白而没有朋友列表。有谁知道这是什么造成的? 谢谢 爱德华
我的清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.my2ndandroidapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".PickerActivity"
android:label="@string/app_name"
></activity>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/>
<activity android:label="@string/app_name" android:name="com.facebook.LoginActivity">
</activity>
</application>
</manifest>
我的基本列表元素类:
public abstract class BaseListElement {
private Drawable icon;
private String text1;
private String text2;
private int requestCode;
private BaseAdapter adapter;
protected abstract View.OnClickListener getOnClickListener();
public void setAdapter(BaseAdapter adapter) {
this.adapter = adapter;
}
public BaseListElement(Drawable icon, String text1, String text2, int requestCode){
super();
this.icon = icon;
this.text1 = text1;
this.text2 = text2;
this.requestCode = requestCode;
}
public int getRequestCode() {
return requestCode;
}
public String getText1() {
return text1;
}
public void setText1(String text1) {
this.text1 = text1;
if(adapter != null){
adapter.notifyDataSetChanged();
}
}
public String getText2() {
return text2;
}
public void setText2(String text2) {
this.text2 = text2;
if(adapter != null){
adapter.notifyDataSetChanged();
}
}
public Drawable getIcon() {
return icon;
}
}
我的选择器活动:
package com.example.my2ndandroidapp;
import com.facebook.FacebookException;
import com.facebook.widget.FriendPickerFragment;
import com.facebook.widget.PickerFragment;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public class PickerActivity extends FragmentActivity {
public static final Uri FRIEND_PICKER = Uri.parse("picker://friend");
private FriendPickerFragment friendPickerFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pickers);
Bundle args = getIntent().getExtras();
FragmentManager manager = getSupportFragmentManager();
Fragment fragmentToShow = null;
Uri intentUri = getIntent().getData();
if(FRIEND_PICKER.equals(intentUri)){
if(savedInstanceState == null){
friendPickerFragment = new FriendPickerFragment(args);
}else{
friendPickerFragment =
(FriendPickerFragment)manager.findFragmentById(R.id.picker_fragment);
}
// set the listener to handle errors
friendPickerFragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
@Override
public void onError(PickerFragment<?> fragment,
FacebookException error) {
PickerActivity.this.onError(error);
}
});
// set the listener to handle button clicks
friendPickerFragment.setOnDoneButtonClickedListener(
new PickerFragment.OnDoneButtonClickedListener() {
@Override
public void onDoneButtonClicked(
PickerFragment<?> fragment) {
finishActivity();
}
});
fragmentToShow = friendPickerFragment;
}else{
// nothing to do, finish
setResult(RESULT_CANCELED);
finish();
return;
}
manager.beginTransaction()
.replace(R.id.picker_fragment, fragmentToShow)
.commit();
}
private void onError(Exception error){
onError(error.getLocalizedMessage(), false);
}
private void onError(String error, final boolean finishActivity){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.error_dialog_title)
.setMessage(error)
.setPositiveButton(R.string.error_dialog_button_text,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if(finishActivity){
finishActivity();
}
}
});
builder.show();
}
private void finishActivity(){
setResult(RESULT_OK, null);
finish();
}
protected void onStart(){
super.onStart();
if(FRIEND_PICKER.equals(getIntent().getData())){
try{
friendPickerFragment.loadData(false);
}catch(Exception ex){
onError(ex);
}
}
}
}
我的选择片段:
public class SelectionFragment extends Fragment {
private static final String TAG = "SelectionFragment";
private ProfilePictureView profilePictureView;
private TextView userNameView;
private UiLifecycleHelper uiHelper;
private ListView listView;
private List<BaseListElement> listElements;
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private static final int REAUTH_ACTIVITY_CODE = 100;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.selection, container, false);
listView = (ListView)view.findViewById(R.id.selection_list);
// set up the list view items, based on list of
// BaseListElement items
listElements = new ArrayList<BaseListElement>();
// add an item for the friend picker
listElements.add(new PeopleListElement(0));
// set the list view adapter
listView.setAdapter(new ActionListAdapter(getActivity(),
R.id.selection_list, listElements));
// find the user's profile picture custom view
profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
profilePictureView.setCropped(true);
// find the user's name view
userNameView = (TextView)view.findViewById(R.id.selection_user_name);
// check for an open session
Session session = Session.getActiveSession();
if( session != null && session.isOpened() ){
// get the user's data
makeMeRequest(session);
}
//announceButton = (TextView) view.findViewById(R.id.announce_text);
//messageButton = (TextView) view.findViewById(R.id.message_text);
//listView = (ListView) view.findViewById(R.id.selection_list);
//photoThumbnail = (ImageView) view.findViewById(R.id.selected_image);
//if (FacebookDialog.canPresentOpenGraphMessageDialog(activity)) {
// messageButton.setVisibility(View.VISIBLE);
//}
//announceButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// handleAnnounce(false);
// }
//});
//messageButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// handleAnnounce(true);
// }
//});
//init(savedInstanceState);
return view;
}
@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);
}else if(resultCode == Activity.RESULT_OK){
// do nothing for now
}
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
private void makeMeRequest(final Session session){
// make an api call to get user data and define a
// new callback to handle the response
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
// if the response is successful
if( session == Session.getActiveSession() ){
if( user != null ){
// set the id for the ProfilePictureView
// view that in turn displays the profile picture.
profilePictureView.setProfileId(user.getId());
// set the TextView's text to the user's name.
userNameView.setText(user.getName());
}
}
if( response.getError() != null ){
// handle errors, will do so later.
}
}
});
request.executeAsync();
}
private void onSessionStateChange(final Session session, SessionState state, Exception exception)
{
if( session != null && session.isOpened() ){
// get the user's data.
makeMeRequest(session);
}
}
private class ActionListAdapter extends ArrayAdapter<BaseListElement>{
private List<BaseListElement> listElements;
public ActionListAdapter(Context context, int resourceId, List<BaseListElement> listElements)
{
super(context, resourceId, listElements);
this.listElements = listElements;
// set up as an observer for list item changes to
// refresh the view.
for(int i = 0; i < listElements.size(); i++){
listElements.get(i).setAdapter(this);
}
}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
if(view == null){
LayoutInflater inflater =
(LayoutInflater)getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.listitem, null);
}
BaseListElement listElement = listElements.get(position);
if(listElement != null){
view.setOnClickListener(listElement.getOnClickListener());
ImageView icon = (ImageView)view.findViewById(R.id.icon);
TextView text1 = (TextView)view.findViewById(R.id.text1);
TextView text2 = (TextView)view.findViewById(R.id.text2);
if(icon != null){
icon.setImageDrawable(listElement.getIcon());
}
if(text1 != null){
text1.setText(listElement.getText1());
}
if(text2 != null){
text2.setText(listElement.getText2());
}
}
return view;
}
}
private class PeopleListElement extends BaseListElement {
public PeopleListElement(int requestCode){
super(getActivity().getResources().getDrawable(R.drawable.add_friends),
getActivity().getResources().getString(R.string.action_people),
getActivity().getResources().getString(R.string.action_people_default),
requestCode);
}
protected View.OnClickListener getOnClickListener(){
return new View.OnClickListener() {
@Override
public void onClick(View v) {
startPickerActivity(PickerActivity.FRIEND_PICKER, getRequestCode());
}
};
}
}
private void startPickerActivity(Uri data, int requestCode){
Intent intent = new Intent();
intent.setData(data);
intent.setClass(getActivity(), PickerActivity.class);
startActivityForResult(intent, requestCode);
}
我的主要活动:
public class MainActivity extends FragmentActivity {
private MainFragment mainFragment;
private static final String TAG = "MainFragment";
private static final int SPLASH = 0;
private static final int SELECTION = 1;
private static final int SETTINGS = 2;
private static final int FRAGMENT_COUNT = SETTINGS + 1;
private MenuItem settings;
private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
private boolean isResumed = false;
private boolean userSkippedLogin = false;
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback =
new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
//userSkippedLogin = savedInstanceState.getBoolean(USER_SKIPPED_LOGIN_KEY);
}
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentManager fm = getSupportFragmentManager();
SplashFragment splashFragment = (SplashFragment) fm.findFragmentById(R.id.splashFragment);
fragments[SPLASH] = splashFragment;
fragments[SELECTION] = fm.findFragmentById(R.id.selectionFragment);
fragments[SETTINGS] = fm.findFragmentById(R.id.userSettingsFragment);
FragmentTransaction transaction = fm.beginTransaction();
for(int i = 0; i < fragments.length; i++) {
transaction.hide(fragments[i]);
}
transaction.commit();
splashFragment.setSkipLoginCallback(new SplashFragment.SkipLoginCallback() {
@Override
public void onSkipLoginPressed() {
userSkippedLogin = true;
showFragment(SELECTION, false);
}
});
}
private void onSessionStateChange(Session session, SessionState state, Exception exception){
// only make changes if the activity is visible
if(isResumed){
FragmentManager manager = getSupportFragmentManager();
// get the number of entries in the back stack
int backStackSize = manager.getBackStackEntryCount();
// Clear the back stack
for(int i = 0; i < backStackSize; i++){
manager.popBackStack();
}
if(state.isOpened()){
// if the session state is open:
// show the authenticated fragment
showFragment(SELECTION, false);
}else if(state.isClosed()){
// if the session state is closed:
// show the login fragment
showFragment(SPLASH, false);
}
}
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
Session session = Session.getActiveSession();
if(session != null && session.isOpened()){
// if the session is already open,
// try to show the selection fragment
showFragment(SELECTION, false);
}else{
// otherwise present the splash screen
// and ask the person to login.
showFragment(SPLASH, false);
}
}
@Override
protected void onPause() {
super.onPause();
uiHelper.onPause();
isResumed = false;
}
@Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
isResumed = true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.equals(settings)){
showFragment(SETTINGS, true);
return true;
}
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
// from previous tutorials
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private void showFragment(int fragmentIndex, boolean addToBackStack) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
for (int i = 0; i < fragments.length; i++) {
if (i == fragmentIndex) {
transaction.show(fragments[i]);
} else {
transaction.hide(fragments[i]);
}
}
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.commit();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// only add the menu when the selection fragment is showing
if(fragments[SELECTION].isVisible()){
if(menu.size() == 0){
settings = menu.add(R.string.settings);
}
return true;
}else{
menu.clear();
settings = null;
}
return false;
}
}
我的主要片段:
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
private Button sendRequestButton;
private Button shareButton;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
//uiHelper = new UiLifecycleHelper(getActivity(), null);
//uiHelper.onCreate(savedInstanceState);
}
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);
//shareButton = (Button)view.findViewById(R.id.shareButton);
//shareButton.setOnClickListener(new View.OnClickListener() {
//
// @Override
// public void onClick(View v) {
// publishStory();
//
// }
//});
//sendRequestButton = (Button)view.findViewById(R.id.sendRequestButton);
//sendRequestButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// sendRequestDialog();
// }
//});
if(savedInstanceState != null){
pendingPublishReauthorization = savedInstanceState.getBoolean(PENDING_PUBLISH_KEY,
false);
}
return view;
}
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state, Exception exception){
if(state.isOpened()){
sendRequestButton.setVisibility(View.VISIBLE);
shareButton.setVisibility(View.VISIBLE);
if(pendingPublishReauthorization && state.equals(SessionState.OPENED_TOKEN_UPDATED)){
pendingPublishReauthorization = false;
publishStory();
}
}else if(state.isClosed()){
sendRequestButton.setVisibility(View.INVISIBLE);
shareButton.setVisibility(View.INVISIBLE);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//uiHelper.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
@Override
public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data)
{
Log.e("Activity", String.format("Error: %s", error.toString()));
}
@Override
public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
Log.i("Activity", "Success!");
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@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. Triggered 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 onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
private void sendRequestDialog(){
Bundle params = new Bundle();
params.putString("message", "Learn how to make your Android apps social");
WebDialog requestsDialog = (
new WebDialog.RequestsDialogBuilder(getActivity(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener(){
@Override
public void onComplete(Bundle values,
FacebookException error) {
if(error != null){
if(error instanceof FacebookOperationCanceledException){
Toast.makeText(getActivity().getApplicationContext(),
"Request cancelled",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity().getApplicationContext(),
"Network Error",
Toast.LENGTH_LONG).show();
}
}else{
final String requestId = values.getString("request");
if(requestId != null){
Toast.makeText(getActivity().getApplicationContext(),
"Request sent",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity().getApplicationContext(),
"Request cancelled",
Toast.LENGTH_LONG).show();
}
}
}
})
.build();
requestsDialog.show();
}
private void publishStory(){
Session session = Session.getActiveSession();
if(session != null){
// check for publish permissions
List<String> permissions = session.getPermissions();
if(!isSubsetOf(PERMISSIONS, permissions)){
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new
Session.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("name", "Facebook SDK for Android");
postParams.putString("caption", "Build great social apps and get more installs");
postParams.putString("description", "The Facebook SDK for Android makes it easier and
faster to develop Facebook integrated Android apps.");
postParams.putString("link", "https://developers.facebook.com/android");
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-
howtos/master/Images/iossdk_logo.png");
Request.Callback callback = new Request.Callback() {
@Override
public void onCompleted(Response response) {
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try{
postId = graphResponse.getString("id");
}catch(JSONException e){
Log.i(TAG, "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
if(error != null){
Toast.makeText(getActivity().getApplicationContext(),
error.getErrorMessage(), Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity().getApplicationContext(), postId,
Toast.LENGTH_SHORT).show();
}
}
};
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset){
for(String string : subset){
if(!superset.contains(string)){
return false;
}
}
return true;
}
}
答案 0 :(得分:0)
只需添加FriendPickerFragment
即可friendPickerFragment.setFriendPickerType(FriendPickerFragment.FriendPickerType.TAGGABLE_FRIENDS);