2011-05-05 72 views
0

朋友們,我有一個按鈕facebook集成錯誤點擊,它總是返回NullPointerException異常,我不知道爲什麼?請建議我正確的結果......Facebook的整合在Android的

代碼:

package com.ex.softZilla; 

import java.util.List; 

import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.Context; 
import android.content.Intent; 
import android.net.ConnectivityManager; 
import android.os.Bundle; 
import android.os.Handler; 
import android.util.Log; 
import android.view.Display; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.ImageButton; 
import android.util.AttributeSet; 
import android.graphics.Color; 
import com.ex.softZilla.BaseRequestListener; 
import com.ex.softZilla.SessionEvents.AuthListener; 
import com.ex.softZilla.SessionEvents.LogoutListener; 
import com.ex.softZilla.Facebook.DialogListener; 





public class SettingActivity extends Activity{ 
    final String APP_ID = "172619129456913"; 
    String bytesSent; 
    HttpClient httpclient; 
    int count1; 
    // List with parameters and their values 
    List<NameValuePair> nameValuePairs; 

    LoginButton mLoginButton; 
    TextView mText; 
    Facebook mFacebook; 
    AsyncFacebookRunner mAsyncRunner; 
    AlertDialog.Builder alertNetwork; 
    private Facebook mFb; 
    private Handler mHandler; 
    private SessionListener mSessionListener = new SessionListener(); 
    private String[] mPermissions; 
    private Activity mActivity; 
    Button btn_facebook; 
    Button btn_twitter; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.more_setting); 

    btn_facebook = (Button)findViewById(R.id.btn_More_setting_facebook); 
    btn_twitter = (Button)findViewById(R.id.btn_more_setting_twitter); 


      btn_facebook.setOnClickListener(new View.OnClickListener() { 

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

       alertNetwork = new AlertDialog.Builder(SettingActivity.this); 
       ConnectivityManager connMgr = (ConnectivityManager) 
        SettingActivity.this.getSystemService(getApplicationContext().CONNECTIVITY_SERVICE); 

       /* final android.net.NetworkInfo wifi = 
        connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 

       final android.net.NetworkInfo mobile = 
        connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);*/ 

       /*if(!wifi.isAvailable()||mobile.isAvailable()){ 

         alertNetwork.setTitle("Network Error."); 

         alertNetwork.setMessage("Please check your network connection."); 
         alertNetwork.setNeutralButton("Ok",null); 
           alertNetwork.show(); 
           this.onDestroy(); 
         }*/ 

       if (APP_ID == null) { 
        Util.showAlert(SettingActivity.this, "Warning", "Facebook Applicaton ID must be " + 
          "specified before running this example: see Example.java"); 
       } 


       Display display = getWindowManager().getDefaultDisplay(); 
       int width = display.getWidth(); 
       int height = display.getHeight(); 
       System.out.println("Width:"+width); 
       System.out.println("Height:"+height); 


        // setContentView(R.layout.facebookviewlarge); 




       mText = (TextView) SettingActivity.this.findViewById(R.id.txt); 



       mFacebook = new Facebook(APP_ID); 
       mAsyncRunner = new AsyncFacebookRunner(mFacebook); 

       SessionStore.restore(mFacebook, SettingActivity.this); 
       SessionEvents.addAuthListener(new SampleAuthListener()); 
       SessionEvents.addLogoutListener(new SampleLogoutListener()); 

       //login class is calling here 
       // mLoginButton.init(SettingActivity.this, mFacebook); 
       //mLoginButton. 

       if (mFb.isSessionValid()) { 
        SessionEvents.onLogoutBegin(); 
        AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFb); 
        asyncRunner.logout(getApplicationContext(), new LogoutRequestListener()); 
       } else { 
        mFb.authorize(mActivity, mPermissions, 
            new LoginDialogListener()); 
       } 
      } 








      /*Intent intent = new Intent(SettingActivity.this,Example.class); 
      startActivity(intent);*/ 


    }); 
    btn_twitter.setOnClickListener(new View.OnClickListener() { 


     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      Intent intent = new Intent(SettingActivity.this,TwitterViewController.class); 
      startActivity(intent); 


     } 

    }); 
} 
    class SampleAuthListener implements AuthListener { 

      public void onAuthSucceed() { 
       mText.setText("You have logged in! "); 
       mFacebook.dialog(SettingActivity.this, "feed", new SampleDialogListener()); 



      } 

      public void onAuthFail(String error) { 
       mText.setText("Login Failed: " + error); 
      } 
     } 

     class SampleLogoutListener implements LogoutListener { 
      public void onLogoutBegin() { 
       mText.setText("Logging out..."); 
      } 

      public void onLogoutFinish() { 
       mText.setText("You have logged out! "); 

      } 
     } 

     class SampleRequestListener extends BaseRequestListener { 

      public void onComplete(final String response) { 
       try { 
        // process the response here: executed in background thread 
        Log.d("Facebook-Example", "Response: " + response.toString()); 
        JSONObject json = Util.parseJson(response); 
        final String name = json.getString("name"); 

        // then post the processed result back to the UI thread 
        // if we do not do this, an runtime exception will be generated 
        // e.g. "CalledFromWrongThreadException: Only the original 
        // thread that created a view hierarchy can touch its views." 
        SettingActivity.this.runOnUiThread(new Runnable() { 
         public void run() { 
          mText.setText("Hello there, " + name + "!"); 
         } 
        }); 
       } catch (JSONException e) { 
        Log.w("Facebook-Example", "JSON Error in response"); 
       } catch (FacebookError e) { 
        Log.w("Facebook-Example", "Facebook Error: " + e.getMessage()); 
       } 
      } 
     } 


     class WallPostRequestListener extends BaseRequestListener { 

      public void onComplete(final String response) { 
       Log.d("Facebook-Example", "Got response: " + response); 
       String message = "<empty>"; 
       try { 
        JSONObject json = Util.parseJson(response); 
        message = json.getString("message"); 
       } catch (JSONException e) { 
        Log.w("Facebook-Example", "JSON Error in response"); 
       } catch (FacebookError e) { 
        Log.w("Facebook-Example", "Facebook Error: " + e.getMessage()); 
       } 
       final String text = "Your Wall Post: " + message; 
       SettingActivity.this.runOnUiThread(new Runnable() { 
        public void run() { 
         mText.setText(text); 
         //postTotalShare(); 
        } 
       }); 
      } 


     } 

     class SampleDialogListener extends BaseDialogListener { 

      public void onComplete(Bundle values) { 
       final String postId = values.getString("post_id"); 
       if (postId != null) { 
        Log.d("Facebook-Example", "Dialog Success! post_id=" + postId); 
        mAsyncRunner.request(postId, new WallPostRequestListener()); 

       } 
     } 

     } 
    class SessionListener implements AuthListener, LogoutListener { 

      public void onAuthSucceed() { 
       //setImageResource(R.drawable.logout_button); 
       SessionStore.save(mFb, getApplicationContext()); 
      } 

      public void onAuthFail(String error) { 
      } 

      public void onLogoutBegin() {   
      } 

      public void onLogoutFinish() { 
       SessionStore.clear(getApplicationContext()); 
       //setImageResource(R.drawable.login_button); 
      } 
     } 
    public void init(final Activity activity, final Facebook fb) { 
      init(activity, fb, new String[] {}); 
     } 

     public void init(final Activity activity, final Facebook fb, 
         final String[] permissions) { 
      mActivity = activity; 
      mFb = fb; 
      mPermissions = permissions; 
      mHandler = new Handler(); 

      // setBackgroundColor(Color.TRANSPARENT); 
      // setAdjustViewBounds(true); 
      //setImageResource(fb.isSessionValid() ? 
          //R.drawable.logout_button : 
          //R.drawable.login_button); 
      //drawableStateChanged(); 

      SessionEvents.addAuthListener(mSessionListener); 
      SessionEvents.addLogoutListener(mSessionListener); 

     } 

     private final class LoginDialogListener implements DialogListener { 
      public void onComplete(Bundle values) { 
       SessionEvents.onLoginSuccess(); 
      } 

      public void onFacebookError(FacebookError error) { 
       SessionEvents.onLoginError(error.getMessage()); 
      } 

      public void onError(DialogError error) { 
       SessionEvents.onLoginError(error.getMessage()); 
      } 

      public void onCancel() { 
       SessionEvents.onLoginError("Action Canceled"); 
      } 
     } 

     private class LogoutRequestListener extends BaseRequestListener { 
      public void onComplete(String response) { 
       // callback should be run in the original thread, 
       // not the background thread 
       mHandler.post(new Runnable() { 
        public void run() { 
         SessionEvents.onLogoutFinish(); 
        } 
       }); 
      } 
     } 
} 

錯誤:

05-05 15:35:05.351: ERROR/AndroidRuntime(6175): FATAL EXCEPTION: main 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175): java.lang.NullPointerException 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at com.ex.softZilla.Facebook.startSingleSignOn(Facebook.java:221) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at com.ex.softZilla.Facebook.authorize(Facebook.java:190) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at com.ex.softZilla.Facebook.authorize(Facebook.java:114) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at com.ex.softZilla.SettingActivity$1.onClick(SettingActivity.java:127) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at android.view.View.performClick(View.java:2408) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at android.view.View$PerformClick.run(View.java:8816) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at android.os.Handler.handleCallback(Handler.java:587) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at android.os.Handler.dispatchMessage(Handler.java:92) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at android.os.Looper.loop(Looper.java:123) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at android.app.ActivityThread.main(ActivityThread.java:4627) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at java.lang.reflect.Method.invokeNative(Native Method) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at java.lang.reflect.Method.invoke(Method.java:521) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 
05-05 15:35:05.351: ERROR/AndroidRuntime(6175):  at dalvik.system.NativeStart.main(Native Method) 
+2

錯誤發生在哪裏?什麼是堆棧跟蹤?請考慮修剪代碼的牆,只有相關的位。 – 2011-05-05 09:47:37

+0

這可能是一個非常簡單的問題。您只需提供堆棧跟蹤,然後修改代碼即可。 – 2011-05-05 09:49:22

+0

您似乎有兩個Facebook變量,mFacebook和mFb。如果你初始化一個而使用另一個仍然爲空,這可能是原因嗎? – harism 2011-05-05 09:52:59

回答

0

基於the ever so useful list of good Android libraries也許你應該使用Facebook Android API代替(什麼看起來是)滾動你自己的。

編輯:我知道......但依然。

無論如何,我實際上是通過你的代碼看,我相信mPermissions變量從未被設置到任何東西,在爲空時就這樣過去了,被引用,進而創建你的空指針異常。它發生在您調用此函數時:

mFb.authorize(mActivity, mPermissions, new LoginDialogListener()); 

因此,由於mPermissions爲空,所以您有問題。這可能不會發生,如果初始化函數被調用但它commened出來:

// mLoginButton.init(SettingActivity.this, mFacebook); 

也許在代碼中的依賴可能是一個小更平滑;該代碼可能功能不足。

+0

這僅僅是Facebook登錄羅伯特,我需要的職位爲我的Android應用程序,這是註冊在Facebook上 – 2011-05-05 10:10:30

+0

@ user621380:編輯,包括潛在的答案。 – 2011-05-05 10:19:42