I have been trying to make wall post from multiple pages but when i try to make post from other pages except original facebook page, it is giving me an exception of java.lang.NullPointerException
The method i am calling and created in a Facebook page.
public void setConnection() {
mContext = this;
mFacebook = new Facebook(getResources().getString(R.string.FACEBOOK_ID_TEST));
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
}
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();
}
public void getID()
{
Bundle bundle = new Bundle();
bundle.putString("fields", "birthday");
try {
mFacebook.request("me/friends", bundle);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Error in FaceBook Friends List","Exception = "+e.getMessage());
e.printStackTrace();
}
if (isSession()) {
Log.d(TAG, "sessionValid");
try {
mFacebook.request("me/friends", bundle);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Error in FaceBook Friends List","Exception = "+e.getMessage());
e.printStackTrace();
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
}
}
I am able to get the wall post dialog box but its showing "An error occurred. Please try again later".
Please help me out.
Thanks in advance.
I think the best way for you to achieve this would be to make an abstract class which extends the super class Activity, use this to hold all your facebook functions.
Then when you want to have an activity which has the facebook functionality then you would just extend this abstract class. If your not sure what I mean then take a look at the tutorial here, it goes through how to setup a basic Facebook Activity class. Hope this helps.
Related
Hi i am using facebook to login to my app. I am unable to get user
birthday and user location from facebook. Below is the method used to get the details from user. I am using activity class for login.
private void loginFacebook() {
// TODO Auto-generated method stub
if (!facebook.isSessionValid()) {
final Session.OpenRequest request = new
Session.OpenRequest(LoginActivity.this);
facebook.authorize(this, new String[] {
"email","user_birthday","user_about_me","user_location"
}, new LoginDialogListener());
} else {
getProfileInformation();
}
}
public void getProfileInformation() {
// TODO Auto-generated method stub
try {
profile = Util.parseJson(facebook.request("me"));
mUserId = profile.getString("id");
Gloabalvariables.setUserID(mUserId);
mUserToken = facebook.getAccessToken();
mUserName = profile.getString("name");
mUserEmail = profile.getString("email");
JSONObject c=new JSONObject(profile.getString("location"));
mUserhomeTown=c.getString("name");
new insertintoServer().execute();
//getOnlineFreindList();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + mUserName "\nEmail+"+ mUserEmail, Toast.LENGTH_LONG).show();
}
});
} catch (FacebookError e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here the problem is i can able to get user_birthday and user_location from the user only for the account which i created app id. For other account i am unable to get those details. i am struggle for two days. But i dint find what i did wrong in the code.
Go to Facebook Developer Console set permissions:
Facebook Graph API Explorer
There:
Application
Get Access Token: Here select your fieds which you want.
Search For Field
Submit
Save Session
EDIT:
I wrote a function passing the Authenticated Box Client and Bitmap Bytestream. Was also informated the root directory on Box has an ID of 0. But I'm still unable to upload.
What I need to do is create a directory, if present don't and upload the file in that directory.
private void doUpload(final BoxAndroidClient client, final ByteArrayInputStream bs) {
if(client.isAuthenticated())
{
System.out.println("Trying to upload: In upload function");
AsyncTask<Null, Integer, Null> task = new AsyncTask<Null, Integer, Null>() {
#Override
protected void onPostExecute(Null result) {
Toast.makeText(PagerActivity.this, "done uploading", Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
Toast.makeText(PagerActivity.this, "start uploading", Toast.LENGTH_LONG).show();
super.onPreExecute();
}
#Override
protected Null doInBackground(Null... params) {
try {
BoxDefaultRequestObject folreqObj = new BoxDefaultRequestObject();
BoxFolder newFol = new BoxFolder();
String parentId = newFol.getId();
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject("0", "bestphotonow.png", bs);
client.getFilesManager().uploadFile(requestObj);
/*
if(client.getFoldersManager().getFolder(parentId, folreqObj).getName()!=null)
{
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject(parentId, "bestphotonow.png", bs);
client.getFilesManager().uploadFile(requestObj);
}
else
{
BoxFolderRequestObject upreqObj = BoxFolderRequestObject.createFolderRequestObject("BestPhotoNow", parentId);
client.getFoldersManager().createFolder(upreqObj);
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject(parentId, "bestphotonow.png", bs);
client.getFilesManager().uploadFile(requestObj);
}*/
} catch (BoxRestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BoxJSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BoxServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthFatalFailureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
};
task.execute();
}
}
So, I have a wallpaper app that fetches some images from a server. I'm trying to integrate box to be able to upload the picture in the current view (viewpager) to Box via Box Android API v2.
https://github.com/box/box-android-sdk-v2
I have been successful to authenticate the user via oauth. But, I'm really stuck at trying to upload the bitmap or uri direct to their upload call without having to launch a folder picker activity. This is what I have.
On click of a button for upload:
case R.id.boxcloudbutton:
imageLoader.loadImage(url, new SimpleImageLoadingListener(){
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
Intent intent = OAuthActivity.createOAuthActivityIntent(getApplicationContext(), "vfoj4o6nxqblahh454wem", "J9TQWyFSblahV2C", false, "http://localhost");
intent.putExtra("boximageUri", imageUri);
System.out.println("BoxUri: "+imageUri);
startActivityForResult(intent, BOX_RESULT);
super.onLoadingComplete(imageUri, view, loadedImage);
}
});
break;
I'm trying to pass either the bitmap or uri
and in the OnActivityResult
case BOX_RESULT:
if (resultCode == Activity.RESULT_CANCELED) {
// Get the error message for why authentication failed.
String failMessage = data.getStringExtra(OAuthActivity.ERROR_MESSAGE);
// Implement your own logic to handle the error.
// handleFail(failMessage);
} else {
// You will get an authenticated oath token object back upon success.
BoxAndroidOAuthData oauth = data.getParcelableExtra(OAuthActivity.BOX_CLIENT_OAUTH);
// If you don't want to supply a customized hub or parser, use null to fall back to defaults.
BoxAndroidClient client = new BoxAndroidClient( "vfoj4oxxxxxxxxxxtordlh454wem",
"J9TjxxxxxxxmRwux2V2C", null, null, null);
client.authenticate(oauth);
System.out.println("Data for Box: "+data.getExtras().getString("boximageUri"));
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject(0, "name", file);
BoxFile bFile = client.getFilesManager().uploadFile(requestObj);
}
break;
Here, I successfully get authenticated, but I do not recieve the uri or the bitmap in the Intent data that I passed.
More, if anyone has any idea of how I can pass bitmap to a file for a file upload for Box api v2, I would really appreciate some assistance!
Thanks,
Arnab
Try shifting around the responsibility....
When you go to the Oauth activity , do just the authentication and return the credentials or Token from that which grants permission for subsequent actions on Box api.
Choose correct api to POST a bitmap... Here you want an api call that allows the ByteArray corresponding to the bitMap to be loaded as a ByteArrayEntity in the body of a http POST action.
This answer sample of how to prepare a local bitmap instance for being wrapped in body of Post as byteArray.
I am trying to pass Facebook data from one activity to another.
The logs in activity 1 show that all the data was received (name, age etc.).
However, when I try to work with this data in activity 2, nothing happens. None of the logs at the bottom show up. Any idea what I'm doing wrong?
protected void handleFacebookData()
{
Intent intent = getIntent();
name = (String) intent.getSerializableExtra(Const.NAME);
Log.d(Profile.class.getSimpleName(), "Got FB name");
age = (String) intent.getSerializableExtra(Const.AGE);
Log.d(Profile.class.getSimpleName(), "Got FB age");
imgUrl = (String) intent.getSerializableExtra(Const.PIC);
x = BitmapFactory.decodeFile(imgUrl);
Log.d(Profile.class.getSimpleName(), "Got FB picture");
facebookData = true;
}
final Intent intent = new Intent(
MainActivity.this,
Profile.class);
intent.putExtra(Const.NAME,
getFacebookAccountName(userString));
intent.putExtra(Const.AGE,
getFacebookAge(userString));
intent.putExtra(Const.PIC,
getFacebookImage(userString));
startActivityForResult(intent,
REQUEST_FOR_RESULT_CREATE);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onError(DialogError de) {
Log.v(TAG, "********************** fb: onError()");
}
#Override
public void onFacebookError(FacebookError error) {
Log.v(TAG,
"********************** fb: onFacebookError()");
}
});
}
I am new to android and I am building an app that I want to authenticate using the local users google account. Unfortunately I have gotten myself in a bit of a bind looking at Auth 2.0 and logging in via the google services.
What is the recommended route to authenticate (and hopefully not require typing a login name)? I tried many of the samples that I saw but much of it seems deprecated.
Any example code would be very helpful as well.
I was using this tutorial but it is a bit outdated and I believe that it is much simplier now.
http://blog.notdot.net/2010/05/Authenticating-against-App-Engine-from-an-Android-app
Thanks,
Craig
Here is how I solved it. Don't know if it is the recommended approach but it works...
in OnCreate of my entry activity (main) I put...
AccountManager accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");
AccountManagerFuture<Bundle> futur;
futur = accountManager.getAuthToken(accounts[0],AUTH_TOKEN_TYPE_USERINFO_PROFILE, null, null,
new OnTokenAcquired(), new Handler(new OnError()));
In that same activity I created...
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
// Get the result of the operation from the AccountManagerFuture.
Bundle bundle;
try {
bundle = result.getResult();
// The token is a named value in the bundle. The name of the
// value
// is stored in the constant AccountManager.KEY_AUTHTOKEN.
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
//If token isn't null then let them in and also make sure Crunchy accounts are created
if(token!=null){
ProcessToken pt = new ProcessToken(token);
pt.execute("");
}
Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 0);
return;
}
}catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I also created an asyncTask to process the token (because I do a bit more logic to setup account and set a cookie). It looks like this (much of my processing/cookie logic is not completed yet)
package com.craig.activities.login;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
import android.util.Log;
public class ProcessToken extends AsyncTask<String,Integer,Long>{
private static final String AUTH_ACCESS_TOKEN_URL = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=";
private static final String DEBUG_TAG = "OnTokenAcquired.class";
private static String token="";
public ProcessToken(String tokenValue){
token=tokenValue;
}
#Override
protected Long doInBackground(String... params) {
try {
URL url = new URL(AUTH_ACCESS_TOKEN_URL+token);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int serverCode= con.getResponseCode();
if(serverCode==200){
Log.i(DEBUG_TAG, "code 200!!!");
//PUT MY LOGIC IN HERE....
}
else{
Log.i(DEBUG_TAG, "Oops, We had an error on authentication");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Not sure if this is the best but it seems to be working for me....
I want to post image along with text caption via facebook SDK.
I am referring to the solution posted here.
Android post picture to Facebook wall
However, I am getting the following error.
FATAL EXCEPTION: main
java.lang.NullPointerException
at java.net.URLDecoder.decode(URLDecoder.java:104)
at java.net.URLDecoder.decode(URLDecoder.java:48)
at com.facebook.android.Util.openUrl(Util.java:173)
at com.facebook.android.Facebook.request(Facebook.java:751)
at com.xxx.yyy.gui.share.ShareDialogFactory.shareThroughFacebook(ShareDialogFactory.java:170)
I had verified my code against the previous posted solution.
private static void shareThroughFacebook(final Context context, final File file, final int heartbeatForShare) {
final Facebook facebook = new Facebook("285243934881501");
// Login.
facebook.authorize((Activity)context, new String[] { "publish_stream" }, new DialogListener() {
#Override
public void onComplete(Bundle values) {
android.util.Log.i("CHEOK", "onComplete");
}
#Override
public void onFacebookError(FacebookError error) {
android.util.Log.i("CHEOK", "onFacebookError");
}
#Override
public void onError(DialogError e) {
android.util.Log.i("CHEOK", "onError");
}
#Override
public void onCancel() {
android.util.Log.i("CHEOK", "onCancel");
}
});
android.util.Log.i("CHEOK", "STEP 1");
final byte[] data = JPEG2ByteArray(file);
final Bundle bundle = new Bundle();
bundle.putString(Facebook.TOKEN, facebook.getAccessToken());
android.util.Log.i("CHEOK", "data length is " + data.length);
bundle.putByteArray("picture", data);
bundle.putString("message", "this-is-message");
bundle.putString("caption", "this-is-caption");
// I can reach till here!
android.util.Log.i("CHEOK", "STEP 2");
try {
// NPE happens right here!!!
facebook.request("me/photos", bundle, "POST");
} catch (FileNotFoundException e1) {
android.util.Log.i("CHEOK", "FileNotFoundException");
e1.printStackTrace();
} catch (MalformedURLException e1) {
android.util.Log.i("CHEOK", "MalformedURLException");
e1.printStackTrace();
} catch (IOException e1) {
android.util.Log.i("CHEOK", "IOException");
e1.printStackTrace();
}
android.util.Log.i("CHEOK", "STEP 3");
}
I can confirm my byte array is non-zero length. I do not receive any callback during authorize, not sure whether this is correct behaviour. Note, the code shareThroughFacebook is invoked from a Dialog.
Is there any other steps I had missed out?