Nidhi Bhatt
Nidhi Bhatt

Reputation: 71

Not able to access getPreferences method

I am not able to access getPreferences method of sharedPreferences interface in my method.I used getpreferences method in my method logintofacebook but it gives me error for PRIVATE_MODE how can I solve this problem.

this is the my edited code.

    public class FacebookUtils {

private static final DialogListener DEFAULT_AUTH_ACTIVITY_CODE = null;

private static String APP_ID = "783826255024540"; 
public Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
Button btnFbLogin;
Button btnFbGetProfile;
Context mcontext;

public FacebookUtils() {
    // TODO Auto-generated constructor stub

}
public void authorize(Activity activity, String[] permissions,
        final DialogListener listener) {
    authorize(activity, permissions, DEFAULT_AUTH_ACTIVITY_CODE);
}
public FacebookUtils(Context context) {

}


@SuppressWarnings("unused")
public void loginToFacebook() {

    SharedPreferences sharedPreferences=mcontext.getSharedPreferences("", Context.MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);

    if (access_token != null) {
        facebook.setAccessToken(access_token);
        btnFbLogin.setVisibility(View.INVISIBLE);
        btnFbGetProfile.setVisibility(View.VISIBLE);
        Log.d("FB Sessions", "" + facebook.isSessionValid());
    }
    if (expires != 0) {
        facebook.setAccessExpires(expires);
    }
    if (!facebook.isSessionValid()) {
        facebook.authorize((Activity) mcontext,
                new String[] { "email", "publish_stream" },
                new DialogListener() {
                    @Override
                    public void onCancel() {
                    }
                    @Override
                    public void onComplete(Bundle values) {

                        SharedPreferences sharedPreferences=mcontext.getSharedPreferences("", Context.MODE_PRIVATE);
                        Editor editor=sharedPreferences.edit();
                        editor.putString("access_token",facebook.getAccessToken());
                        editor.putLong("access_expires",facebook.getAccessExpires());
                        editor.commit();
                        btnFbLogin.setVisibility(View.INVISIBLE);
                        btnFbGetProfile.setVisibility(View.VISIBLE);
                    }
                    @Override
                    public void onError(DialogError error) {
                        // Function to handle error
                    }
                    @Override
                    public void onFacebookError(FacebookError fberror) {
                    }

                });
        }


}



public void getprofileinformation()
{

    mAsyncRunner.request("me", new RequestListener() {

        @Override
        public void onMalformedURLException(MalformedURLException e, Object state) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onIOException(IOException e, Object state) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFileNotFoundException(FileNotFoundException e, Object state) {
            // TODO Auto-generated method stub

        }

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

        }

        @Override
        public void onComplete(String response, Object state) {
            // TODO Auto-generated method stub
            Log.d("Profile", response);
            String json = response;
            try {
                JSONObject profile = new JSONObject(json);
                final String name = profile.getString("name");
                final String email = profile.getString("email");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mcontext, "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }); 

}
protected void runOnUiThread(Runnable runnable) {
    // TODO Auto-generated method stub
}
}

and this is logcat error.

12-02 13:31:36.648: E/AndroidRuntime(2524): FATAL EXCEPTION: main
12-02 13:31:36.648: E/AndroidRuntime(2524): Process: com.facebook.androidhive, PID: 2524
12-02 13:31:36.648: E/AndroidRuntime(2524): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
12-02 13:31:36.648: E/AndroidRuntime(2524):     at com.facebook.demo.FacebookUtils.loginToFacebook(FacebookUtils.java:56)
12-02 13:31:36.648: E/AndroidRuntime(2524):     at com.facebook.demo.AndroidFacebookConnectActivity$1.onClick(AndroidFacebookConnectActivity.java:51)
12-02 13:31:36.648: E/AndroidRuntime(2524):     at android.view.View.performClick(View.java:4756)
12-02 13:31:36.648: E/AndroidRuntime(2524):     at android.view.View$PerformClick.run(View.java:19749)
12-02 13:31:36.648: E/AndroidRuntime(2524):     at android.os.Handler.handleCallback(Handler.java:739)
12-02 13:31:36.648: E/AndroidRuntime(2524):     at android.os.Handler.dispatchMessage(Handler.java:95)
12-02 13:31:36.648: E/AndroidRuntime(2524):     at android.os.Looper.loop(Looper.java:135)
12-02 13:31:36.648: E/AndroidRuntime(2524):     at android.app.ActivityThread.main(ActivityThread.java:5221)
12-02 13:31:36.648: E/AndroidRuntime(2524):     at java.lang.reflect.Method.invoke(Native Method)
12-02 13:31:36.648: E/AndroidRuntime(2524):     at java.lang.reflect.Method.invoke(Method.java:372)
12-02 13:31:36.648: E/AndroidRuntime(2524):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
12-02 13:31:36.648: E/AndroidRuntime(2524):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)`

this is my second activity in which i called this class.

public class AndroidFacebookConnectActivity extends Activity {
    private static String APP_ID = "783826255024540"; 
    private Facebook facebook = new Facebook(APP_ID);
    private AsyncFacebookRunner mAsyncRunner;
    String FILENAME = "AndroidSSO_data";
    private SharedPreferences mPrefs;
    Button btnFbLogin;
    Button btnFbGetProfile;
    @SuppressWarnings("unused")
    private FacebookUtils utils;
    Context mContext;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
        btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
        mAsyncRunner = new AsyncFacebookRunner(facebook);
        utils = new FacebookUtils();
        btnFbLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Image Button", "button Clicked");
                utils.loginToFacebook(mContext);
            }
        });
        btnFbGetProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                utils.getprofileinformation();
            }
        });
    }

error is related to this activity? I am getting null exception in this line. String access_token = mPrefs.getString("access_token", null);

Upvotes: 1

Views: 11357

Answers (3)

TechArcSri
TechArcSri

Reputation: 2002

This would be easy for you:-

Putting the values

SharedPreferences sharedPreferences=mContext.getSharedPreferences("", Context.MODE_PRIVATE);
Editor editor=sharedPreferences.edit();
editor.putString("access_token",facebook.getAccessToken());
editor.putLong("access_expires",facebook.getAccessExpires());
editor.commit();

Getting the values

SharedPreferences sharedPreferences=mContext.getSharedPreferences("", Context.MODE_PRIVATE);
String access_token = sharedPreferences.getString("access_token", null);
long expires = sharedPreferences.getLong("access_expires", 0);

Check the constructor once. May be mContext is null. Try this:-

public FacebookUtils(Context context) {
  mContext=context;
}

Try to pass context to loginToFacebook():-

public void loginToFacebook(Context mContext) {
}

Upvotes: 2

karan vs
karan vs

Reputation: 3364

just in case anybody faces this issue:

  public class listops {
  Context mcontext;
   SharedPreferences prefs;


  public listops(Context context)
   {
    mcontext=context;
    prefs= mcontext.getSharedPreferences("prefs", Context.MODE_PRIVATE);

  }
 ...
 }

this would resolve the issue.

Upvotes: 0

Atul O Holic
Atul O Holic

Reputation: 6792

You have not initialized variable mPrefs. Hence the error since when you try to do mPrefs.getString("access_token", null); its null;

As of now you have only declared it with statement,

private SharedPreferences mPrefs;

but in-order to access it you will also have to initialize it as,

 mPrefs = getPreferences(MODE_PRIVATE);

before you try to use it.

Upvotes: 4

Related Questions