2011-07-12 91 views
0

我跟着這個教程在線設置我的android應用程序的Facebook SDK。它的工作原理,直到在用戶登錄,然後當它崩潰我得到的logcat此錯誤Facebook的Android SDK NullPointerException

07-12 16:59:29.783: ERROR/AndroidRuntime(556): FATAL EXCEPTION: main 
07-12 16:59:29.783: ERROR/AndroidRuntime(556): java.lang.NullPointerException 
07-12 16:59:29.783: ERROR/AndroidRuntime(556):  at com.outfit.first.FBConnectionActivity$IDRequestListener$1.run(FBConnectionActivity.java:129) 
07-12 16:59:29.783: ERROR/AndroidRuntime(556):  at android.os.Handler.handleCallback(Handler.java:587) 
07-12 16:59:29.783: ERROR/AndroidRuntime(556):  at android.os.Handler.dispatchMessage(Handler.java:92) 
07-12 16:59:29.783: ERROR/AndroidRuntime(556):  at android.os.Looper.loop(Looper.java:123) 
07-12 16:59:29.783: ERROR/AndroidRuntime(556):  at android.app.ActivityThread.main(ActivityThread.java:3839) 
07-12 16:59:29.783: ERROR/AndroidRuntime(556):  at java.lang.reflect.Method.invokeNative(Native Method) 
07-12 16:59:29.783: ERROR/AndroidRuntime(556):  at java.lang.reflect.Method.invoke(Method.java:507) 
07-12 16:59:29.783: ERROR/AndroidRuntime(556):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 
07-12 16:59:29.783: ERROR/AndroidRuntime(556):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 
07-12 16:59:29.783: ERROR/AndroidRuntime(556):  at dalvik.system.NativeStart.main(Native Method) 

我的整個代碼波紋管,我出演的是logcat的說叫錯誤的線,在這條線:

username.setText("Welcome: " + name+"\n ID: "+id); 

任何人都可以幫我弄清楚我做錯了什麼?我感覺自己很靠近它的工作。

import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.net.MalformedURLException; 

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

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.preference.PreferenceManager; 
import android.util.Log; 
import android.widget.ProgressBar; 
import android.widget.TextView; 

import com.facebook.android.AsyncFacebookRunner; 
import com.facebook.android.DialogError; 
import com.facebook.android.Facebook; 
import com.facebook.android.FacebookError; 
import com.facebook.android.Util; 
import com.facebook.android.AsyncFacebookRunner.RequestListener; 
import com.facebook.android.Facebook.DialogListener; 

public abstract class FBConnectionActivity extends Activity { 
    public static final String TAG = "FACEBOOK"; 
    private Facebook mFacebook; 
    public static final String APP_ID = "IDHERE"; 
    private AsyncFacebookRunner mAsyncRunner; 
    private static final String[] PERMS = new String[] { "read_stream" }; 
    private SharedPreferences sharedPrefs; 
    private Context mContext; 

    private TextView username; 
    private ProgressBar pb; 

    public void setConnection() { 
      mContext = this; 
      mFacebook = new Facebook(APP_ID); 
      mAsyncRunner = new AsyncFacebookRunner(mFacebook); 
    } 

    public void getID() { 
     if (isSession()) { 
      Log.d(TAG, "sessionValid"); 
      mAsyncRunner.request("me", new IDRequestListener()); 
     } else { 
      // no logged in, so relogin 
      Log.d(TAG, "sessionNOTValid, relogin"); 
      mFacebook.authorize(this, PERMS, new LoginDialogListener()); 
     } 
    } 

    public void getID(TextView txtUserName, ProgressBar progbar) { 
      username = txtUserName; 
      pb = progbar; 
      if (isSession()) { 
        Log.d(TAG, "sessionValid"); 
        mAsyncRunner.request("me", new IDRequestListener()); 
      } else { 
        // no logged in, so relogin 
        Log.d(TAG, "sessionNOTValid, relogin"); 
        mFacebook.authorize(this, PERMS, new LoginDialogListener()); 
      } 
    } 

    public boolean isSession() { 
      sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext); 
      String access_token = sharedPrefs.getString("access_token", "x"); 
      Long expires = sharedPrefs.getLong("access_expires", -1); 
      Log.d(TAG, access_token); 

      if (access_token != null && expires != -1) { 
        mFacebook.setAccessToken(access_token); 
        mFacebook.setAccessExpires(expires); 
      } 
      return mFacebook.isSessionValid(); 
    } 

    private class LoginDialogListener implements DialogListener { 

      @Override 
      public void onComplete(Bundle values) { 
        Log.d(TAG, "LoginONComplete"); 
        String token = mFacebook.getAccessToken(); 
        long token_expires = mFacebook.getAccessExpires(); 
        Log.d(TAG, "AccessToken: " + token); 
        Log.d(TAG, "AccessExpires: " + token_expires); 
        sharedPrefs = PreferenceManager 
            .getDefaultSharedPreferences(mContext); 
        sharedPrefs.edit().putLong("access_expires", token_expires) 
            .commit(); 
        sharedPrefs.edit().putString("access_token", token).commit(); 
        mAsyncRunner.request("me", new IDRequestListener()); 
      } 

      @Override 
      public void onFacebookError(FacebookError e) { 
        Log.d(TAG, "FacebookError: " + e.getMessage()); 
      } 

      @Override 
      public void onError(DialogError e) { 
        Log.d(TAG, "Error: " + e.getMessage()); 
      } 

      @Override 
      public void onCancel() { 
        Log.d(TAG, "OnCancel"); 
      } 
    } 

    private class IDRequestListener implements RequestListener { 

      @Override 
      public void onComplete(String response, Object state) { 
        try { 
          Log.d(TAG, "IDRequestONComplete"); 
          Log.d(TAG, "Response: " + response.toString()); 
          JSONObject json = Util.parseJson(response); 

          final String id = json.getString("id"); 
          final String name = json.getString("name"); 
          FBConnectionActivity.this.runOnUiThread(new Runnable() { 
            public void run() { 
            //!!!line 129!!!  username.setText("Welcome: " + name+"\n ID: "+id); 
              pb.setVisibility(ProgressBar.GONE); 

            } 
          }); 
        } catch (JSONException e) { 
          Log.d(TAG, "JSONException: " + e.getMessage()); 
        } catch (FacebookError e) { 
          Log.d(TAG, "FacebookError: " + e.getMessage()); 
        } 
      } 

      @Override 
      public void onIOException(IOException e, Object state) { 
        Log.d(TAG, "IOException: " + e.getMessage()); 
      } 

      @Override 
      public void onFileNotFoundException(FileNotFoundException e, 
          Object state) { 
        Log.d(TAG, "FileNotFoundException: " + e.getMessage()); 
      } 

      @Override 
      public void onMalformedURLException(MalformedURLException e, 
          Object state) { 
        Log.d(TAG, "MalformedURLException: " + e.getMessage()); 
      } 

      @Override 
      public void onFacebookError(FacebookError e, Object state) { 
        Log.d(TAG, "FacebookError: " + e.getMessage()); 
      } 

    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
      mFacebook.authorizeCallback(requestCode, resultCode, data); 
    } 
} 

編輯: 所以這是我的活動,從一個按鈕,點擊開始Facebook的代碼:

ImageButton combine = (ImageButton) findViewById(R.id.CompressImg); 
     combine.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View view) { 
       setConnection(); 
       getID(); 
       //createoneimage("final.png");   
      } 
      }); 

這是我main.java類即時通訊真的不知道它做什麼:

public class main extends FBConnectionActivity { 
    private TextView txtUserName; 
    private ProgressBar pbLogin; 
    private Button btnLogin; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.mainfb); 

    txtUserName = (TextView) findViewById(R.id.textFacebook); 
    pbLogin = (ProgressBar) findViewById(R.id.progressLogin); 
    btnLogin = (Button) findViewById(R.id.buttonLogin); 
      btnLogin.setOnClickListener(new OnClickListener() { 
        @Override 
        public void onClick(View arg0) { 
          pbLogin.setVisibility(ProgressBar.VISIBLE); 
          setConnection(); 
          getID(txtUserName, pbLogin); 
        } 
      }); 
} 
} 

最後,這是我mainfb.xml文件

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:orientation="vertical" android:layout_width="fill_parent" 
     android:layout_height="fill_parent"> 
     <TextView android:layout_width="fill_parent" android:id="@+id/textFacebook" 
       android:gravity="center_horizontal" android:layout_height="wrap_content" 
       android:text="@string/welcome" android:layout_alignParentTop="true" /> 
     <Button android:text="@string/enter" android:id="@+id/buttonLogin" 
       android:layout_below="@+id/textFacebook" 
       android:layout_centerHorizontal="true" android:layout_width="wrap_content" 
       android:layout_height="wrap_content" android:layout_marginTop="30dip"></Button> 
     <ProgressBar android:id="@+id/progressLogin" 
       android:layout_centerInParent="true" android:layout_width="wrap_content" 
       android:visibility="gone" android:layout_height="wrap_content"></ProgressBar> 
</RelativeLayout> 

編輯2: 因爲我一直在使用這個代碼ive認識到,每當我第一次登錄應用程序崩潰時使用此代碼,然後第二次登錄時它已經保存了fb用戶信息。 Bellow是我在碰撞時得到的logcat錯誤。我不確定它是否真的第二次工作,因爲我沒有得到任何錯誤,但是當我嘗試發佈到我的fb牆時,它會得到錯誤。

07-16 21:46:16.720: ERROR/AndroidRuntime(818): FATAL EXCEPTION: main 
07-16 21:46:16.720: ERROR/AndroidRuntime(818): java.lang.NullPointerException 
07-16 21:46:16.720: ERROR/AndroidRuntime(818):  at com.outfit.first.FBConnectionActivity$IDRequestListener$1.run(FBConnectionActivity.java:169) 
07-16 21:46:16.720: ERROR/AndroidRuntime(818):  at android.os.Handler.handleCallback(Handler.java:587) 
07-16 21:46:16.720: ERROR/AndroidRuntime(818):  at android.os.Handler.dispatchMessage(Handler.java:92) 
07-16 21:46:16.720: ERROR/AndroidRuntime(818):  at android.os.Looper.loop(Looper.java:123) 
07-16 21:46:16.720: ERROR/AndroidRuntime(818):  at android.app.ActivityThread.main(ActivityThread.java:3839) 
07-16 21:46:16.720: ERROR/AndroidRuntime(818):  at java.lang.reflect.Method.invokeNative(Native Method) 
07-16 21:46:16.720: ERROR/AndroidRuntime(818):  at java.lang.reflect.Method.invoke(Method.java:507) 
07-16 21:46:16.720: ERROR/AndroidRuntime(818):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 
07-16 21:46:16.720: ERROR/AndroidRuntime(818):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 
07-16 21:46:16.720: ERROR/AndroidRuntime(818):  at dalvik.system.NativeStart.main(Native Method) 
+0

一個可能的問題是,您在IDRequestListener中獲取的JSON不包含「name」對象 - 這會導致json.getString(「name」)返回null。你在log.d中看到了什麼(TAG,「Response:」+ response.toString())行? – Torid

+0

@Torid - JSON確實返回一個名稱對象,它是來自Facebook的標準響應的一部分。 @Peter - 您可以發佈佈局xml和代碼實現此類的活動.FBConnectionActivity類沒有問題,因此您的錯誤必須來自其他類。 – Kenny

+0

你也可以在你的代碼中標記什麼行是數字129,我認爲它是username.setText(....或pb。setVisibility(....讓我知道哪一個。 – Kenny

回答

2

行,所以我覺得你的問題是,你的getID()方法使用,然後試圖設置一個TextView的用戶名和ID是null,因爲您的通話getID(),而沒有經過的TextView或進度作爲該IDRequestListener參數。所以,你有兩個選擇,一是你可以只添加此功能,您FBConnectionActivity類:

public void login(){ 
    if (!isSession()) { 
     // no logged in, so relogin 
     Log.d(TAG, "login"); 
     mFacebook.authorize(this, PERMS, new LoginDialogListener()); 
    } 
} 

然後,而不是調用getID()就叫login() - 這樣你就跳過IDRequestListener,因此也就沒有空指針。或者你可以簡單地把一個try/catch周圍有問題的代碼:

try{ 
    username.setText("Welcome: " + name+"\n ID: "+id); 
    pb.setVisibility(ProgressBar.GONE); 
}catch(Exception e){ 
    e.printStackTrace(); 
} 

這將捕獲異常,並繼續進行。

編輯:通過我的回答infact看我注意到,loginDialogListener使用IDRequestListener所以你或者需要刪除調用來設置文本視圖和進度條或把try/catch!

+0

當我在第二行pd = progDialog粘貼這個;出現錯誤「不能被取消」我認爲它的suppoded是「pb」而不是「pd」,但仍然會出現錯誤。 – Peter

+0

對不起,我從一個項目複製/粘貼,我使用對話框而不是進度條,我也編輯了代碼,所以你不需要pd = progDialog;線! – Kenny

+0

它的工作,非常感謝你的幫助! – Peter