简体   繁体   中英

Integrating login with facebook in Android application

Being a beginner, I am trying to implement facebook integration in my application. I got the app to run. However as son as i enter my credentials and it asks for my permission, that app crashes. I dont knw what is wrong. I followed a tutorial here :

Here is my main activity code :

package com.techfrk.facebooktesting;

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

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import facebook.android.DialogError;
import facebook.android.Facebook;
import facebook.android.Facebook.DialogListener;
import facebook.android.FacebookError;

public class MainActivity extends ActionBarActivity 
{
    private Facebook facebook;
    private static final String APP_ID = "758322840932665";
    private static final String[] PERMISSIONS = new String[] { "publish_stream","read_stream"};
    public static final String TOKEN = "access_token";
    public static final String EXPIRES = "expires_in";
    private static final String KEY = "facebook-credentials";
    Button bb;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bb=(Button)findViewById(R.id.btnLoginNPublish);
        bb.setOnClickListener(new OnClickListener() 
        {

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


                //loginToTwitter();
                 //MyTwitterLogin();
        /////////////// Facebook//////////////
                    facebook = new Facebook(APP_ID);

                    LoginToFacebook();
               //     postToWall("Posting from my Eclipse project!!!");
                  //  fetchFacebookFriends();
                    ///////////////////////
                }
                catch(Exception ex)
                {
                 Log.i("Exception:",ex.getMessage());

                }
            }
        });
    }

    @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) 
    {
        // 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();
        if (id == R.id.action_settings) 
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public boolean saveCredentials(Facebook facebook) 
    {
        Editor editor = getApplicationContext().getSharedPreferences(KEY,Context.MODE_PRIVATE).edit();
        editor.putString(TOKEN, facebook.getAccessToken());
        editor.putLong(EXPIRES, facebook.getAccessExpires());
        return editor.commit();
    }

    public boolean restoreCredentials(Facebook facebook) 
    {
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE);
        facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
        facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
        return facebook.isSessionValid();
    }
    public void LoginToFacebook() 
    {
        facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,new LoginDialogListener());
    }
    public void postToWall(String msg) 
    {
        Log.d("Tests", "Testing graph API wall post");
         try 
         {
                String response = facebook.request("me");
                Bundle parameters = new Bundle();
                parameters.putString("message", msg);
                parameters.putString("description", "test test test");
                response = facebook.request("me/feed", parameters,"POST");
                Log.d("Tests", "got response: " + response);
                if (response == null || response.equals("") || response.equals("false")|| response.contains("error")) 
                {
                   Log.v("Error", response.toString());
                }
         } 
         catch(Exception e) 
         {
             e.printStackTrace();
         }
    }

    public void fetchFacebookFriends()
    {
         try {
                String response = facebook.request("me");

                response = facebook.request("me/friends");

                Log.d("Tests", "got response: " + response);
                if (response == null || response.equals("") || response.equals("false")|| response.contains("error")) 
                {
                   Log.v("Error", response.toString());
                }
                else
                {
                        JSONObject jsonObject = new JSONObject(response);
                        try 
                        {
                            JSONArray array = jsonObject.getJSONArray("data");
                            for (int i = 0; i < array.length(); i++) 
                            {
                                JSONObject object = (JSONObject) array.get(i);
                                Log.d( "id = "+object.get("id"),"Name = "+object.get("name"));
                            }
                        } 
                        catch (JSONException e) 
                        {
                            e.printStackTrace();
                        }
                }
         }
         catch(Exception ex1)
         {

         }
}
    public void fetchMyFacebookStatuses()
    {
         try {
                String response = facebook.request("me");

                response = facebook.request("me/statuses");

                Log.d("Tests", "got response: " + response);
                if (response == null || response.equals("") || response.equals("false")) 
                {
                   Log.v("Error", response.toString());
                }
                else
                {
                        JSONObject jsonObject = new JSONObject(response);
                        try 
                        {
                            JSONArray array = jsonObject.getJSONArray("data");
                            for (int i = 0; i < array.length(); i++) 
                            {
                                JSONObject object = (JSONObject) array.get(i);
                                Log.d( "Message id = "+object.get("id"),"Message = "+object.get("message"));
                            }
                        } 
                        catch (Exception e) 
                        {
                            Log.i("Error in Statuses:",e.getMessage());
                        }
                }
         }
         catch(Exception ex1)
         {
             Log.i("Error in Statuses:",ex1.getMessage());
         }
  }

    class LoginDialogListener implements DialogListener 
    {
        public void onComplete(Bundle values) 
        {
            saveCredentials(facebook);
            showToast( "Login Successfull in Facebook");
            //fetchFacebookFriends();
            //postToWall("Another post from Eclipse...");
             fetchMyFacebookStatuses();
            //fetchFriendsFacebookStatuses();    
        }

        @Override
        public void onFacebookError(FacebookError e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void onError(DialogError e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void onCancel() 
        {
            // TODO Auto-generated method stub

        }

    }
    private void showToast(String message) 
    {
           Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }
}

Here is the Log Cat :

04-02 12:16:58.691: A/chromium(16016): [FATAL:jni_android.cc(269)] Check failed: false. Please include Java exception stack in crash report
04-02 12:16:58.691: E/chromium(16016): ### WebView Version 40 (1808730-arm) (code 423501)
04-02 12:16:58.691: A/libc(16016): Fatal signal 6 (SIGABRT), code -6 in tid 16016 (facebooktesting)

You can go with easy way that is SocialAuth. EXAMPLE below

Initialization

Initialize SocialAuth Adapter Object and create a Facebook Button. On clicking the button authorize the adapter.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

   adapter = new SocialAuthAdapter(new ResponseListener());

  facebook_button = (Button)findViewById(R.id.fb_btn);
  facebook_button.setBackgroundResource(R.drawable.facebook);

 facebook_button.setOnClickListener(new OnClickListener() 
 {
    public void onClick(View v) 
    {
        adapter.authorize(ProviderUI.this, Provider.FACEBOOK);
    }
});
}

Receive Authentication response in ResponseListener and initiate calls to get various functionalities. See Examples below:

Update Status

Share your status by calling adapter.updateStatus() and verify response in MessageListener. You can share your status on your Facebook wall in any language.

private final class ResponseListener implements DialogListener 
{
   public void onComplete(Bundle values) {

  adapter.updateStatus(edit.getText().toString(), new MessageListener());                   
}
}

// To get status of message after authentication
private final class MessageListener implements SocialAuthListener {
@Override
public void onExecute(Integer t) {

Integer status = t;
if (status.intValue() == 200 || status.intValue() == 201 ||status.intValue() == 204)
 Toast.makeText(CustomUI.this, "Message posted",Toast.LENGTH_LONG).show();
else
Toast.makeText(CustomUI.this, "Message not posted",Toast.LENGTH_LONG).show();
}
}

Update Story

Share stories by calling adapter.updateStory() and verify response in MessageListener. You need the following fields to share a story: message, caption, link , imageurl.

private final class ResponseListener implements DialogListener 
{
public void onComplete(Bundle values) {

 adapter.updateStory(  "Hello SocialAuth Android" ,  "Google SDK for Android",
         "Build great social apps and get more installs.",
         "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated 
                                         Android apps.",  "https://www.facebook.com",               
                                        "http://carbonfreepress.gr/images/facebook.png", new MessageListener());                
}
}

// To get status of message after authentication
private final class MessageListener implements SocialAuthListener {
@Override
public void onExecute(Integer t) {

Integer status = t;
if (status.intValue() == 200 || status.intValue() == 201 ||status.intValue() == 204)
 Toast.makeText(CustomUI.this, "Message posted",Toast.LENGTH_LONG).show();

Get Profile

Get User profile by getUserprofileAsync() method and receive response in profileDataListener. You can get

User profile ID, first name, last name, email, gender, country, language , location and profile image URL for Facebook.

 private final class ResponseListener implements DialogListener 
{
 public void onComplete(Bundle values) {

  adapter.getUserProfileAsync(new ProfileDataListener());                   
}
}

// To receive the profile response after authentication
private final class ProfileDataListener implements SocialAuthListener {

@Override
public void onExecute(Profile t) {

Log.d("Custom-UI", "Receiving Data");
Profile profileMap = t;
Log.d("Custom-UI",  "Validate ID         = " + profileMap.getValidatedId());
Log.d("Custom-UI",  "First Name          = " + profileMap.getFirstName());
Log.d("Custom-UI",  "Last Name           = " + profileMap.getLastName());
Log.d("Custom-UI",  "Email               = " + profileMap.getEmail());
Log.d("Custom-UI",  "Gender                   = " + profileMap.getGender());
 Log.d("Custom-UI",  "Country                  = " +              profileMap.getCountry());
 Log.d("Custom-UI",  "Language                 = " + profileMap.getLanguage());
Log.d("Custom-UI",  "Location                 = " + profileMap.getLocation());
Log.d("Custom-UI",  "Profile Image URL  = " + profileMap.getProfileImageURL());

Get Contacts

Get User contacts by getContactListAsync() method and receive response in contactDataListener. You can get first name , last name and profile URL for Facebook.

private final class ResponseListener implements DialogListener 
{
public void onComplete(Bundle values) {

  adapter.getContactListAsync(new ContactDataListener());                   
}
}

// To receive the contacts response after authentication
private final class ContactDataListener implements SocialAuthListener> {

@Override
public void onExecute(List t) {

Log.d("Custom-UI", "Receiving Data");
List contactsList = t;
if (contactsList != null && contactsList.size() > 0) {
for (Contact c : contactsList) {
Log.d("Custom-UI", "Contact ID = " + c.getId());
Log.d("Custom-UI", "First Name = " + c.getFirstName());
Log.d("Custom-UI", "Last Name = " + c.getLastName());
 }
 }

Get User Feeds

Get User feeds by getFeedListAsync() method and receive response in feedDataListener. You can get

screen name, message , date of creation and name of user who posted the feed.

private final class ResponseListener implements DialogListener 
{
public void onComplete(Bundle values) {

 adapter.getFeedsAsync(new FeedDataListener());             
}
}

 // To receive the feed response after authentication
 private final class FeedDataListener implements SocialAuthListener> {

 @Override
 public void onExecute(List t) {

 Log.d("Share-Bar", "Receiving Data");

 List feedList = t;
 if (feedList != null && feedList.size() > 0) {
 for (Feed f : feedList) {
 Log.d("Custom-UI ", "Feed ID = " + f.getId());
 Log.d("Custom-UI", "Screen Name = " + f.getScreenName());
 Log.d("Custom-UI", "Message = " + f.getMessage());
 Log.d("Custom-UI ", "Get From = " + f.getFrom());
 Log.d("Custom-UI ", "Created at = " + f.getCreatedAt());
 }
  }                                    
}

Get Albums

Get User albums by getAlbumsAsync() method and receive response in albumDataListener. You can get

album name, cover photo , photos count , array of images with their name and URLs.

private final class ResponseListener implements DialogListener 
{
public void onComplete(Bundle values) {

 adapter.getAlbumsAsync(new AlbumDataListener());   
}
}

 // To receive the album response after authentication
 private final class AlbumDataListener implements SocialAuthListener> {

 @Override
 public void onExecute(List t) {

Log.d("Custom-UI", "Receiving Data");
List albumList = t;
if (albumList != null && albumList.size() > 0) {

// Get Photos inside Album
for (Album a : albumList) {
Log.d("Custom-UI", "Album ID = " + a.getId());
Log.d("Custom-UI", "Album Name = " + a.getName());
Log.d("Custom-UI", "Cover Photo = " + a.getCoverPhoto());
Log.d("Custom-UI", "Photos Count = " + a.getPhotosCount());

photosList = a.getPhotos();
if (photosList != null && photosList.size() > 0) {
for (Photo p : photosList) {
    Log.d("Custom-UI", "Photo ID = " + p.getId());
    Log.d("Custom-UI", "Name     = " + p.getTitle());
    Log.d("Custom-UI", "Thumb Image = " + p.getThumbImage());
    Log.d("Custom-UI", "Small Image = " + p.getSmallImage());
    Log.d("Custom-UI", "Medium Image = " + p.getMediumImage());
    Log.d("Custom-UI", "Large Image = " + p.getLargeImage());
   }}
  }}

Upload Images

Share your images by calling adapter.uploadimageAsync() and verify response in UploadImageListener.

 private final class ResponseListener implements DialogListener 
{
 public void onComplete(Bundle values) {

 adapter.uploadImageAsync("Landscape Images", "icon.png", bitmap, 0,new UploadImageListener());
 }
}

// To get status of image upload after authentication
private final class UploadImageListener implements SocialAuthListener {

@Override
public void onExecute(Integer t) {
Log.d("Custom-UI", "Uploading Data");
Integer status = t;
Log.d("Custom-UI", String.valueOf(status));
Toast.makeText(CustomUI.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
}
}

at last

 <strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px;">Conclusion</strong>

reference link http://www.3pillarglobal.com/insights/part-1-using-socialauth-to-integrate-facebook-api-in-android

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM