Facebook最友好的是没有检索

时间:2014-12-16 11:00:09

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

我正在使用美味的文档向正在使用我的应用程序的朋友展示。我已按照这里的教程

https://developers.facebook.com/docs/android/scrumptious/show-friends?locale=en_GB

我已经尝试了所有组合,但它没有检索使用我的应用程序的朋友

我使用了三个班级

scrumptious.java 


    public class ScrumptiousApplication extends Application  {

    private List<GraphUser> selectedUsers;

    public List<GraphUser> getSelectedUsers() {
        return selectedUsers;
    }

    public void setSelectedUsers(List<GraphUser> selectedUsers) {
        this.selectedUsers = selectedUsers;
    }



}


Selectionfragment.java 

package com.example.facebooknew;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.internal.SessionTracker;
import com.facebook.internal.Utility;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.ProfilePictureView;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
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.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SelectionFragment extends Fragment{



    /* In this fragment the data from the user profile is  returned like profile , name etc  
     * (non-Javadoc)
     * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
     */
    private static final String TAG = "SelectionFragment";
    private static final List<String> PERMISSIONS = Arrays.asList(
            "email","user_location");
    private static final int REAUTH_ACTIVITY_CODE = 100;
    private ProfilePictureView profilePictureView;
    private TextView userNameView;
    private TextView firstName;
    private TextView lastName;
    private TextView Location;
    private UiLifecycleHelper uiHelper;
    private List<GraphUser> selectedUsers;
    private ListView listView;
    private List<BaseListElement> listElements;
    private static final String FRIENDS_KEY = "friends";
    private TextView userInfoTextView;
    private Button sendRequestButton;
    private String requestId;
    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 onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Check for an incoming notification. Save the info
        Uri intentUri = getActivity().getIntent().getData();
        if (intentUri != null) {
            String requestIdParam = intentUri.getQueryParameter("request_ids");
            if (requestIdParam != null) {
                String array[] = requestIdParam.split(",");
                requestId = array[0];
                Log.i(TAG, "Request id: "+requestId);


                Toast.makeText(getActivity().getApplicationContext(),requestId, Toast.LENGTH_LONG).show();
            }
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, 
            ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.selection, container, false);

     // 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);
     firstName= (TextView) view.findViewById(R.id.selection_first_name);
     //lastName = (TextView) view.findViewById(R.id.selection_last_name);
     //Location = (TextView) view.findViewById(R.id.selection_location);
     //userInfoTextView = (TextView) view.findViewById(R.id.userInfoTextView);
     sendRequestButton=(Button) view.findViewById(R.id.sendRequestButton);
     uiHelper = new UiLifecycleHelper(getActivity(), callback);

     uiHelper.onCreate(savedInstanceState);

        Session session = Session.getActiveSession();
        if (session != null && session.isOpened()) {
            // Get the user's data



            makeMeRequest(session);


        }





        sendRequestButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub


                sendRequestDialog();

            }



        });


     // Find the list view
        listView = (ListView) view.findViewById(R.id.selection_list);

        // Set up the list view items, based on a 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));

        if (savedInstanceState != null) {
            // Restore the state for each list element
            for (BaseListElement listElement : listElements) {
                listElement.restoreState(savedInstanceState);
            }   

        }



        return view;
    }


    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());
                        //firstName.setText(user.getFirstName());
                        //lastName.setText(user.getLastName());
                        //Location.setText(user.getProperty("email").toString());





                    }
                }
                if (response.getError() != null) {
                    // Handle errors, will do so later.
                }
            }


        });
        request.executeAsync();

    }


    @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
        }else if (resultCode == Activity.RESULT_OK && 
                requestCode >= 0 && requestCode < listElements.size()) {
            listElements.get(requestCode).onActivityResult(data);
        }
    }



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

             if (state.isOpened() && requestId != null) {
                 getRequestData(requestId);
                }

            if (state.isOpened()) {
                sendRequestButton.setVisibility(View.VISIBLE);
            } else if (state.isClosed()) {
                sendRequestButton.setVisibility(View.INVISIBLE);
            }

            makeMeRequest(session);




        }
    }


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

    @Override
    public void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        for (BaseListElement listElement : listElements) {
            listElement.onSaveInstanceState(bundle);
        }

        uiHelper.onSaveInstanceState(bundle);
    }

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

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





    private interface MyGraphLanguage extends GraphObject {
        // Getter for the ID field
        String getId();
        // Getter for the Name field
        String getName();
    }


    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);
            }
        }

        @Override
        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());
                }

                else{

                    Toast.makeText(getActivity().getApplicationContext(),"No data received " ,Toast.LENGTH_LONG).show();

                }
            }
            return view;
        }

    }

    /* It is private class used to populate the friend and bring up the friends list*/
    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);
        }
/* this  event will trigger the picker activity*/ 
        @Override
        protected View.OnClickListener getOnClickListener() {
            return new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Do nothing for now
                     startPickerActivity(PickerActivity.FRIEND_PICKER, getRequestCode());


                }
            };
        }
        private void setUsersText() {
            String text = null;
            if (selectedUsers != null) {
                    // If there is one friend
                if (selectedUsers.size() == 1) {
                    text = String.format(getResources()
                            .getString(R.string.single_user_selected),
                            selectedUsers.get(0).getName());
                } else if (selectedUsers.size() == 2) {
                    // If there are two friends 
                    text = String.format(getResources()
                            .getString(R.string.two_users_selected),
                            selectedUsers.get(0).getName(), 
                            selectedUsers.get(1).getName());
                } else if (selectedUsers.size() > 2) {
                    // If there are more than two friends 
                    text = String.format(getResources()
                            .getString(R.string.multiple_users_selected),
                            selectedUsers.get(0).getName(), 
                            (selectedUsers.size() - 1));
                }   
            }   
            if (text == null) {
                // If no text, use the placeholder text
                text = getResources()
                .getString(R.string.action_people_default);
            }   
            // Set the text in list element. This will notify the 
            // adapter that the data has changed to
            // refresh the list view.
            setText2(text);
        }   
        @Override
        protected void onActivityResult(Intent data) {
            selectedUsers = ((ScrumptiousApplication) getActivity()
                     .getApplication())
                     .getSelectedUsers();
            setUsersText();
            notifyDataChanged();
        }

        @Override
        protected void onSaveInstanceState(Bundle bundle) {
            if (selectedUsers != null) {
                bundle.putByteArray(FRIENDS_KEY,
                        getByteArray(selectedUsers));
            }   
        }
        private byte[] getByteArray(List<GraphUser> users) {
            // convert the list of GraphUsers to a list of String 
            // where each element is the JSON representation of the 
            // GraphUser so it can be stored in a Bundle
            List<String> usersAsString = new ArrayList<String>(users.size());

            for (GraphUser user : users) {
                usersAsString.add(user.getInnerJSONObject().toString());
            }   
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                new ObjectOutputStream(outputStream).writeObject(usersAsString);
                return outputStream.toByteArray();
            } catch (IOException e) {
                Log.e(TAG, "Unable to serialize users.", e); 
            }   
            return null;
        }


        private List<GraphUser> restoreByteArray(byte[] bytes) {
            try {
                @SuppressWarnings("unchecked")
                List<String> usersAsString =
                        (List<String>) (new ObjectInputStream
                                        (new ByteArrayInputStream(bytes)))
                                        .readObject();
                if (usersAsString != null) {
                    List<GraphUser> users = new ArrayList<GraphUser>
                    (usersAsString.size());
                    for (String user : usersAsString) {
                        GraphUser graphUser = GraphObject.Factory
                        .create(new JSONObject(user), 
                                        GraphUser.class);
                        users.add(graphUser);
                    }   
                    return users;
                }   
            } catch (ClassNotFoundException e) {
                Log.e(TAG, "Unable to deserialize users.", e); 
            } catch (IOException e) {
                Log.e(TAG, "Unable to deserialize users.", e); 
            } catch (JSONException e) {
                Log.e(TAG, "Unable to deserialize users.", e); 
            }   
            return null;
        }


        @Override
        protected boolean restoreState(Bundle savedState) {
            byte[] bytes = savedState.getByteArray(FRIENDS_KEY);
            if (bytes != null) {
                selectedUsers = restoreByteArray(bytes);
                setUsersText();
                return true;
            }   
            return false;
        } 


        } 


    /* This function is responsible for launching the freind picker activity*/

    private void startPickerActivity(Uri data, int requestCode) {
         Intent intent = new Intent();
         intent.setData(data);
         intent.setClass(getActivity(), PickerActivity.class);
         startActivityForResult(intent, requestCode);
     }


    public void facebookSession(Session session){

         //session= Session.getActiveSession();

        Session.OpenRequest request = new Session.OpenRequest(this);
        request.setPermissions(Arrays.asList("basic_info","email","location"));
        request.setCallback( new Session.StatusCallback() {
                 // callback when session changes state
                 @Override
                 public void call(Session session, SessionState state, Exception exception) {
                     if (session.isOpened()) {
                         Request.newMeRequest(session, new Request.GraphUserCallback() {
                                 @Override
                                 public void onCompleted(GraphUser user, Response response) {
                                     if (user != null) {
                                         Toast.makeText(SelectionFragment.this.getActivity(), "User email is:"+user.getProperty("email"), Toast.LENGTH_SHORT).show(); }
                                     else {
                                         Toast.makeText(SelectionFragment.this.getActivity(), "Error User Null", Toast.LENGTH_SHORT).show();
                                     }
                                 }
                         }).executeAsync();
                     } 
                 }
        }); //end of call;

        session.openForRead(request); //now do the request above

    }

    private void sendRequestDialog() {
        Bundle params = new Bundle();

        params.putString("message", "Learn how to make your Android apps social");
        params.putString("data",
                "https://play.google.com/store/apps/details?id=de.j4velin.mapsmeasure&hl=en");
        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_SHORT).show();
                            } else {
                                Toast.makeText(getActivity().getApplicationContext(), 
                                    "Network Error", 
                                    Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            final String requestId = values.getString("request");
                            if (requestId != null) {
                                Toast.makeText(getActivity().getApplicationContext(), 
                                    "Request sent",  
                                    Toast.LENGTH_SHORT).show();
                                Toast.makeText(getActivity().getApplicationContext(), requestId, Toast.LENGTH_SHORT).show();

                            } else {
                                Toast.makeText(getActivity().getApplicationContext(), 
                                    "Request cancelled", 
                                    Toast.LENGTH_SHORT).show();
                            }
                        }   
                    }



                })
                .build();
        requestsDialog.show();
    }


    private void getRequestData(final String inRequestId) {
        // Create a new request for an HTTP GET with the
        // request ID as the Graph path.
        Request request = new Request(Session.getActiveSession(), 
                inRequestId, null, HttpMethod.GET, new Request.Callback() {

                    @Override
                    public void onCompleted(Response response) {
                        // Process the returned response
                        GraphObject graphObject = response.getGraphObject();
                        FacebookRequestError error = response.getError();
                        // Default message
                        String message = "Incoming request";
                        if (graphObject != null) {
                            // Check if there is extra data
                            if (graphObject.getProperty("data") != null) {
                                try {
                                    // Get the data, parse info to get the key/value info
                                    JSONObject dataObject = 
                                    new JSONObject((String)graphObject.getProperty("data"));
                                    // Get the value for the key - badge_of_awesomeness
                                    String badge = 
                                        dataObject.getString("badge_of_awesomeness");
                                    // Get the value for the key - social_karma
                                    String karma = 
                                        dataObject.getString("social_karma");
                                    // Get the sender's name
                                    JSONObject fromObject = 
                                        (JSONObject) graphObject.getProperty("from");
                                    String sender = fromObject.getString("name");
                                    String title = sender+" sent you a gift";
                                    // Create the text for the alert based on the sender
                                    // and the data
                                    message = title + "\n\n" + 
                                        "Badge: " + badge + 
                                        " Karma: " + karma;
                                } catch (JSONException e) {
                                    message = "Error getting request info";
                                }
                            } else if (error != null) {
                                message = "Error getting request info";
                            }
                        }
                        Toast.makeText(getActivity().getApplicationContext(),
                                message,
                                Toast.LENGTH_LONG).show();
                    }
            });
        // Execute the request asynchronously.
        Request.executeBatchAsync(request);
    }


}

And I have an abstarct baselist element class 

0 个答案:

没有答案