2013-01-06 114 views
1

我已經搜索谷歌和stackoverflow,但我找不到解決方案。 我試圖將facebook整合到我的應用程序中,以便用戶可以直接向我的Facebook粉絲頁面推薦新的啤酒品牌。因爲現在我每天收到3封電子郵件,讓用戶推薦新的啤酒品牌。獲取錯誤張貼到Facebook牆

我做了什麼: - 創建了一個Facebook開發者帳戶,啓用了Native Android應用程序並插入了Key-Hash等。 - 下載並集成了facebook sdk。 - addet上網權限 - 集成了Facebook的以下輔助類:

package com.celticwolf.nsod; //changed 
import com.facebook.android.*; 
import com.facebook.android.Facebook.DialogListener; 
import android.app.Activity; 
import android.content.Context; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.Window; 
import android.widget.Toast; 

public class ShareOnFacebook extends Activity{ 
    private static final String APP_ID = "35253892647899"; // changed 
    private static final String[] PERMISSIONS = new String[] {"publish_stream"}; 
private static final String TOKEN = "access_token"; 
     private static final String EXPIRES = "expires_in"; 
     private static final String KEY = "facebook-credentials"; 

    private Facebook facebook; 
    private String messageToPost; 

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

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     facebook = new Facebook(APP_ID); 
     restoreCredentials(facebook); 

     requestWindowFeature(Window.FEATURE_NO_TITLE); 

     setContentView(R.layout.facebook_dialog); 

     String facebookMessage = getIntent().getStringExtra("facebookMessage"); 
     if (facebookMessage == null){ 
      facebookMessage = "Test wall post"; 
     } 
     messageToPost = facebookMessage; 
    } 

    public void doNotShare(View button){ 
     finish(); 
    } 
    public void share(View button){ 
     if (! facebook.isSessionValid()) { 
      loginAndPostToWall(); 
     } 
     else { 
      postToWall(messageToPost); 
     } 
    } 

    public void loginAndPostToWall(){ 
     facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener()); 
    } 

    public void postToWall(String message){ 
     Bundle parameters = new Bundle(); 
       parameters.putString("message", message); 
       parameters.putString("description", "topic share"); 
       try { 
        facebook.request("me"); // <------ here it fails 
      String response = facebook.request("me/feed", parameters, "POST"); 
      Log.d("Tests", "got response: " + response); 
      if (response == null || response.equals("") || 
        response.equals("false")) { 
       showToast("Blank response."); 
      } 
      else { 
       showToast("Message posted to your facebook wall!"); 
      } 
      finish(); 
     } catch (Exception e) { 
      showToast("Failed to post to wall!"); 
      e.printStackTrace(); 
      finish(); 
     } 
    } 

    class LoginDialogListener implements DialogListener { 
     public void onComplete(Bundle values) { 
      saveCredentials(facebook); 
      if (messageToPost != null){ 
      postToWall(messageToPost); 
     } 
     } 
     public void onFacebookError(FacebookError error) { 
      showToast("Authentication with Facebook failed!"); 
      finish(); 
     } 
     public void onError(DialogError error) { 
      showToast("Authentication with Facebook failed!"); 
      finish(); 
     } 
     public void onCancel() { 
      showToast("Authentication with Facebook cancelled!"); 
      finish(); 
     } 
    } 

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

,我已經addet下面的代碼來訪問輔助類:

private void shareonfb(){ 
     Intent postOnFacebookWallIntent = new Intent(this, ShareOnFacebook.class); 
     postOnFacebookWallIntent.putExtra("facebookMessage", "Teeeeeeeeeeeest"); 
     startActivity(postOnFacebookWallIntent); 
    } 

凡失敗: - 我能夠登錄到Facebook,但當它詢問我是否想分享它時,在以下代碼塊中失敗:

public void postToWall(String message){ 
    Bundle parameters = new Bundle(); 
      parameters.putString("message", message); 
      parameters.putString("description", "topic share"); 
      try { 
       facebook.request("me"); // <------------- here it fails and jups to catch 
     String response = facebook.request("me/feed", parameters, "POST"); 
     Log.d("Tests", "got response: " + response); 
     if (response == null || response.equals("") || 
       response.equals("false")) { 
      showToast("Blank response."); 
     } 
     else { 
      showToast("Message posted to your facebook wall!"); 
     } 
     finish(); 
    } catch (Exception e) { 
     showToast("Failed to post to wall!"); 
     e.printStackTrace(); 
     finish(); 
    } 
} 

這裏是日誌:(我標記了它失敗的部分)

01-06 13:19:53.795: W/ActivityThread(1220): Application com.celticwolf.alex is waiting for the debugger on port 8100... 
01-06 13:19:53.805: I/System.out(1220): Sending WAIT chunk 
01-06 13:19:54.205: I/System.out(1220): Debugger has connected 
01-06 13:19:54.205: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:54.405: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:54.615: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:54.820: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:55.250: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:55.450: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:55.650: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:55.850: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:56.050: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:56.250: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:56.450: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:56.650: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:56.850: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:57.050: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:57.255: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:57.455: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:57.655: I/System.out(1220): waiting for debugger to settle... 
01-06 13:19:57.855: I/System.out(1220): debugger has settled (1373) 
01-06 13:19:58.285: I/dalvikvm-heap(1220): Grow heap (frag case) to 7.205MB for 3502096-byte allocation 
01-06 13:19:58.400: I/dalvikvm-heap(1220): Grow heap (frag case) to 13.139MB for 6224656-byte allocation 
01-06 13:19:58.575: I/MediaPlayer(1220): setLPAflag() in 
01-06 13:19:58.575: I/MediaPlayer(1220): mContext is null, can't getMirrorDisplayStatus!!! 
01-06 13:19:58.575: I/MediaPlayer(1220): setLPAflag() out 
01-06 13:19:58.585: W/MediaPlayer(1220): info/warning (1, 902) 
01-06 13:19:58.585: D/MediaPlayer(1220): [DLNA]contentType = 902 
01-06 13:19:58.585: D/MediaPlayer(1220): doStart() in 
01-06 13:19:58.590: D/MediaPlayer(1220): getIntParameter = 902 
01-06 13:19:58.665: D/MediaPlayer(1220): Mediaplayer receives message, message type: 200 
01-06 13:19:58.665: I/MediaPlayer(1220): Info (1,902) 
01-06 13:19:58.665: D/MediaPlayer(1220): Mediaplayer receives message, message type: 5 
01-06 13:19:58.665: D/MediaPlayer(1220): Mediaplayer receives message, message type: 1 
01-06 13:19:58.745: E/(1220): file /data/data/com.nvidia.NvCPLSvc/files/driverlist.txt: not found! 
01-06 13:19:58.745: I/(1220): Attempting to load EGL implementation /system/lib//egl/libEGL_tegra_impl 
01-06 13:19:58.805: I/(1220): Loaded EGL implementation /system/lib//egl/libEGL_tegra_impl 
01-06 13:19:58.905: I/(1220): Loading GLESv2 implementation /system/lib//egl/libGLESv2_tegra_impl 
01-06 13:19:59.350: D/MediaPlayer(1220): Mediaplayer receives message, message type: 2 
01-06 13:20:00.200: D/MediaPlayer(1220): release() in 
01-06 13:20:00.210: D/MediaPlayer(1220): release() out 
01-06 13:20:00.745: W/MediaPlayer-JNI(1220): MediaPlayer finalized without being released 
01-06 13:20:00.745: I/dalvikvm-heap(1220): Grow heap (frag case) to 15.433MB for 3317776-byte allocation 
01-06 13:20:40.855: D/View(1220): ACTION_DOWN before UnsetPressedState. invoking mUnsetPressedState.run() 
01-06 13:20:40.870: I/Choreographer(1220): Skipped 1158 frames! The application may be doing too much work on its main thread. 
01-06 13:20:43.810: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 
01-06 13:20:43.810: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 
01-06 13:20:43.975: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 
01-06 13:20:43.975: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 
01-06 13:20:45.150: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 
01-06 13:20:45.150: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 
01-06 13:21:40.920: D/Facebook-Util(1220): GET URL: https://graph.facebook.com/me?access_token=AAAFAqIQXNsUBAE18DxmYZCvB9uLEFUSeQEMp3hZASDnjOMllu1Q0BqSTYEoGVEvjZAp8l18eZCt8ZArlPwQ5A08SijSFF00imS2JDO0A9MAZDZD&format=json 
01-06 13:21:51.180: W/System.err(1220): android.os.NetworkOnMainThreadException              <--- at this point it fails 
01-06 13:21:51.215: W/System.err(1220):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1208) 
01-06 13:21:51.215: W/System.err(1220):  at java.net.InetAddress.lookupHostByName(InetAddress.java:388) 
01-06 13:21:51.220: W/System.err(1220):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:239) 
01-06 13:21:51.220: W/System.err(1220):  at java.net.InetAddress.getAllByName(InetAddress.java:214) 
01-06 13:21:51.225: W/System.err(1220):  at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70) 
01-06 13:21:51.225: W/System.err(1220):  at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50) 
01-06 13:21:51.230: W/System.err(1220):  at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340) 
01-06 13:21:51.230: W/System.err(1220):  at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87) 
01-06 13:21:51.235: W/System.err(1220):  at libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 
01-06 13:21:51.235: W/System.err(1220):  at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315) 
01-06 13:21:51.240: W/System.err(1220):  at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461) 
01-06 13:21:51.240: W/System.err(1220):  at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433) 
01-06 13:21:51.245: W/System.err(1220):  at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289) 
01-06 13:21:51.245: W/System.err(1220):  at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239) 
01-06 13:21:51.250: W/System.err(1220):  at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273) 
01-06 13:21:51.255: W/System.err(1220):  at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168) 
01-06 13:21:51.255: W/System.err(1220):  at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271) 
01-06 13:21:51.255: W/System.err(1220):  at com.facebook.android.Util.openUrl(Util.java:219) 
01-06 13:21:51.260: W/System.err(1220):  at com.facebook.android.Facebook.requestImpl(Facebook.java:806) 
01-06 13:21:51.260: W/System.err(1220):  at com.facebook.android.Facebook.request(Facebook.java:732) 
01-06 13:21:51.265: W/System.err(1220):  at com.celticwolf.alex.ShareOnFacebook.postToWall(ShareOnFacebook.java:81) 
01-06 13:21:51.265: W/System.err(1220):  at com.celticwolf.alex.ShareOnFacebook.share(ShareOnFacebook.java:68) 
01-06 13:21:51.265: W/System.err(1220):  at java.lang.reflect.Method.invokeNative(Native Method) 
01-06 13:21:51.265: W/System.err(1220):  at java.lang.reflect.Method.invoke(Method.java:511) 
01-06 13:21:51.270: W/System.err(1220):  at android.view.View$1.onClick(View.java:3603) 
01-06 13:21:51.270: W/System.err(1220):  at android.view.View.performClick(View.java:4101) 
01-06 13:21:51.270: W/System.err(1220):  at android.view.View$PerformClick.run(View.java:17078) 
01-06 13:21:51.275: W/System.err(1220):  at android.os.Handler.handleCallback(Handler.java:615) 
01-06 13:21:51.275: W/System.err(1220):  at android.os.Handler.dispatchMessage(Handler.java:92) 
01-06 13:21:51.275: W/System.err(1220):  at android.os.Looper.loop(Looper.java:155) 
01-06 13:21:51.280: W/System.err(1220):  at android.app.ActivityThread.main(ActivityThread.java:5485) 
01-06 13:21:51.280: W/System.err(1220):  at java.lang.reflect.Method.invokeNative(Native Method) 
01-06 13:21:51.280: W/System.err(1220):  at java.lang.reflect.Method.invoke(Method.java:511) 
01-06 13:21:51.285: W/System.err(1220):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028) 
01-06 13:21:51.285: W/System.err(1220):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:795) 
01-06 13:21:51.285: W/System.err(1220):  at dalvik.system.NativeStart.main(Native Method) 

謝謝!

回答

2

從android 3.0 AFAIK開始,你不能在主線程中進行網絡操作。 發出呼叫的sperate線程,如果你需要更新UI兼用handlersAsyncTask

例如:

class MyAsyncTask extends AsyncTask<String,Void,Boolean> 
{ 
public Boolean doInBackground(String ...message){ 

    Bundle parameters = new Bundle(); 
      parameters.putString("message", message[0]); 
      parameters.putString("description", "topic share"); 
      try { 
       facebook.request("me"); // <------------- here it fails and jups to catch 
     String response = facebook.request("me/feed", parameters, "POST"); 
     Log.d("Tests", "got response: " + response); 
     if (response == null || response.equals("") || 
       response.equals("false")) { 
      return Boolean.FALSE; 
     } 
     else { 
      return Boolean.TRUE; 
     } 
    } catch (Exception e) { 

     e.printStackTrace(); 
     return Boolean.FALSE; 
    } 
} 

public void onPostExecute(Boolean result){ 
     if(result == Boolean.TRUE){ 
showToast("posted successfully"); 
}else{ 
showToast("couldn't post to FB."); 
} 
     finish(); 
} 
} 

看到這個NetworkOnMainThreadException

+0

謝謝!有效 !!如果有人想知道。我用Nammaris解決方案替換了失敗的代碼塊,並通過以下方式調用它:new MyAsyncTask()。execute(message);還有一個問題。你知道如何發佈在Facebook Fanpage上嗎? – LxSwiss