2015-04-02 107 views
0

作为一名初学者,我试图在我的应用程序中实现Facebook集成。我有应用程序运行。然而,作为儿子,当我输入我的凭据,并要求我的许可,该应用程序崩溃。我不知道什么是错的。我也跟着教程here在Android应用程序中集成facebook登录

这里是我的主要活动代码:

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

这里是登录猫:

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) 
+0

您添加清单文件中FacebookActivty ?? – bGorle 2015-04-02 06:36:44

+0

@ bGorle是的,我做了... !! – TechFrk 2015-04-02 06:43:30

+0

发布日志猫.. – bGorle 2015-04-02 06:44:00

回答

0

你可以是SocialAuth简单的方法去。 实施例下面

初始化

初始化SocialAuth适配器对象,并创建一个Facebook按钮。点击按钮授权适配器。

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

在ResponseListener中接收认证响应并发起呼叫以获得各种功能。请参见下面的例子:在消息监听

更新状态

分享致电adapter.updateStatus您的状态(),并验证响应。你可以用任何语言在你的Facebook墙上分享你的状态。

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

更新故事

通过调用adapter.updateStory分享故事()和验证消息监听响应。你需要以下字段来分享一个故事:消息,标题,链接,图像。

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

找getUserprofileAsync简介

获取用户简档()方法和接收profileDataListener响应。您可以获得

Facebook的用户个人资料ID,名字,姓氏,电子邮件,性别,国家,语言,位置和个人资料图片URL。

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

获取联系人

获取用户通过getContactListAsync触点()方法和接收contactDataListener响应。您可以获取Facebook的名字,姓氏和个人资料URL。

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

获取用户订阅

获取用户通过getFeedListAsync()方法馈送和接收feedDataListener响应。您可以获得

屏幕名称,消息,创建日期和发布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()); 
} 
    }          
} 

获取相册由getAlbumsAsync

获得用户的相册()方法和接收albumDataListener响应。您可以获得

专辑名称,封面照片,照片数量,图像阵列及其名称和URL。

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

上传图片

分享你的图像通过调用adapter.uploadimageAsync()和验证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(); 
} 
} 

最后

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

参考链接http://www.3pillarglobal.com/insights/part-1-using-socialauth-to-integrate-facebook-api-in-android

相关问题