Android Facebook Graph API - java

Has anyone got an example of how to use the Android Graph API?
I am stuck with the basics, like posting text to the wall on Facebook.
I'm using the Facebook SDK for Android. Here is what I have so far:
Bundle params = new Bundle();
params.putString("message", "picture caption");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me/feed", params, "POST", 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
}
}, "foo");
Nothing happens, and my Logcat says:
03-02 22:10:02.973: WARN/Bundle(1930): Key message expected byte[] but value was a java.lang.String. The default value <null> was returned.
03-02 22:10:02.983: WARN/Bundle(1930): Attempt to cast generated internal exception:
03-02 22:10:02.983: WARN/Bundle(1930): java.lang.ClassCastException: java.lang.String
03-02 22:10:02.983: WARN/Bundle(1930): at android.os.Bundle.getByteArray(Bundle.java:1305)
03-02 22:10:02.983: WARN/Bundle(1930): at com.facebook.android.Util.encodePostBody(Util.java:63)
03-02 22:10:02.983: WARN/Bundle(1930): at com.facebook.android.Util.openUrl(Util.java:182)
03-02 22:10:02.983: WARN/Bundle(1930): at com.facebook.android.Facebook.request(Facebook.java:559)
03-02 22:10:02.983: WARN/Bundle(1930): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:253)

try this
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, token);
params.putString("message", "graph api");
mAsyncRunner.request("/me/feed", params,"POST", new SampleUploadListener(),null);
you can get access token by using
token = mFacebook.getAccessToken();

You can do this like :--
give description in bundle message and if u want to share some image from server u can provide link as i given below
Bundle params = new Bundle();
params.putString("message", "description");
params.putString("link","your image url" );
new GraphRequest( AccessToken.getCurrentAccessToken(),
"me/feed",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
Log.d(TAG, "" + response.toString());
try {
JSONObject jsonObject = new JSONObject(response.getRawResponse());
if (jsonObject != null) {
String postId = jsonObject.getString("id");
if (postId != null && !postId.equalsIgnoreCase("")) {
hideProgressDialog();
Log.d("postId", "" + postId);
} else {
hideProgressDialog();
Utils.showToast(getActivity(), getResources().getString(R.string.txt_try_again));
}
} else {
hideProgressDialog();
Utils.showToast(getActivity(), getResources().getString(R.string.txt_try_again));
}
} catch (JSONException e) {
hideProgressDialog();
e.printStackTrace();
} catch (Throwable e) {
hideProgressDialog();
e.printStackTrace();
}
}
}).executeAsync();

Related

Android java parsing Json from url to object list

I would like to connect to a Api url, retrieve the json and store everything in a object list. Here is an example of what the url can return as Json.
The following code was given to me but it returns a error Cannot resolve method setOnResponse in my activity line 31
This is my activity.java
public class resultOverview_activity extends Activity implements onResponse{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_overview);
Bundle search_activity_data = getIntent().getExtras();
if(search_activity_data == null){
return;
}
String URL = "http://www.gw2spidy.com/api/v0.9/json/item-search/Sunrise";
AsyncTask parkingInfoFetch = new AsyncFetch(this);
parkingInfoFetch.setOnResponse(this);
parkingInfoFetch.execute(URL);
//Log.i("gw2Log", parkingInfoFetch.);
}
#Override
public void onResponse(JSONObject object) {
Log.d("Json Response", "Json Response" + object);
ResultClass resultClass = new ResultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray array = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = array.getJSONObject(i);
resultClass.setData_id(resultsObject.getInt("data_id"));
resultClass.setName(resultsObject.getString("name"));
resultClass.setRarity(resultsObject.getInt("rarity"));
resultClass.setRestriction_level(resultsObject
.getInt("restriction_level"));
resultClass.setImg(resultsObject.getString("img"));
resultClass.setType_id(resultsObject.getInt("type_id"));
resultClass.setSub_type_id(resultsObject.getInt("sub_type_id"));
resultClass.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
resultClass.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
resultClass.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
resultClass.setOffer_availability(resultsObject
.getInt("offer_availability"));
resultClass.setSale_availability(resultsObject
.getInt("sale_availability"));
resultClass.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
resultClass.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
AsyncFetch.java class
public class AsyncFetch extends AsyncTask<String, Void, JSONObject> {
public AsyncFetch(Context context) {
this.context = context;
}
private Context context;
private JSONObject jsonObject;
private onResponse onResponse;
public onResponse getOnResponse() {
return onResponse;
}
public void setOnResponse(onResponse onResponse) {
this.onResponse = onResponse;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
try {
HttpGet get = new HttpGet(params[0]);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
jsonObject = new JSONObject(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
this.onResponse.onResponse(result);
}
public interface onResponse {
public void onResponse(JSONObject object);
}
}
And ofcourse the constructur ResultClass which i assume is not necessary to include here as code.
What does this error Cannot resolve method setOnResponse mean and how do i fix this?
Change this line:
AsyncTask parkingInfoFetch = new AsyncFetch(this);
To this:
AsyncFetch parkingInfoFetch = new AsyncFetch(this);
The error means that the line:
parkingInfoFetch.setOnResponse(this);
Is trying to call a method defined in the subclass AsyncFetch, but you have the variable defined as the parent class AsyncTask which has no method setOnResponse.

In App Null Pointer Exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
i'm tring to implement In App Billing into my application. I wrote this code.
public class Settings extends PreferenceFragment {
ServiceConnection mServiceConn;
IInAppBillingService mService;
PendingIntent pending;
Intent intent;
Bundle bundle;
#Override
public void onDestroy() {
super.onDestroy();
if (mService != null) {
getActivity().unbindService(mServiceConn);
}
}
#Override
public void onCreate(Bundle savedIstanceState) {
super.onCreate(savedIstanceState);
addPreferencesFromResource(R.xml.settings);
getActivity().getActionBar().setTitle(getString(R.string.settings));
mServiceConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
mService = IInAppBillingService.Stub.asInterface(arg1);
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
mService = null;
}
};
intent = new Intent("com.android.vending.billing.InAppBillingService.BIND").setPackage("com.android.vending");
getActivity().bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE);
try {
bundle = mService.getBuyIntent(3, getActivity().getPackageName(), "pro_version", "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
pending = bundle.getParcelable("BUY_INTENT");
getActivity().startIntentSenderForResult(pending.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SendIntentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When i launch the application and open this Fragment the app crash with this error:
01-31 19:59:30.969: E/AndroidRuntime(11546): java.lang.NullPointerException: Attempt to invoke interface method 'android.os.Bundle com.android.vending.billing.IInAppBillingService.getBuyIntent(int, java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
In the AndroidManifest obviously i've these permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.android.vending.BILLING"/>
Your try block is called before onServiceConnected is, that's why mService is null. Move the try block inside the onServiceConnected and after the assignment like so:
mServiceConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
mService = IInAppBillingService.Stub.asInterface(arg1);
try {
bundle = mService.getBuyIntent(3, getActivity().getPackageName(), "pro_version", "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
pending = bundle.getParcelable("BUY_INTENT");
getActivity().startIntentSenderForResult(pending.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SendIntentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
mService = null;
}
};

Extract the values from the json object to the purpose of intent

According to the code sample I have shown, responseJson returns the value of FirstName. I want to get that value out of responseJson because i want to pass it to next activity. Any help will be highly appreciated.
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("Status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
intent.putExtra("FirstName", firstname);
contxt.startActivity(intent);
} else {
Toast.makeText(contxt,
"Login Error, invalid Email or Password", Toast.LENGTH_SHORT)
.show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this is the my responseJson value {"LastName":"A","UserID":"1","Status":"200","FirstName":"P"}
Change
intent.putExtra("FirstName", firstname);
to
intent.putExtra("FirstName", responseJson.getString("FirstName"));
OR
firstname=responseJson.getString("FirstName");
if(firstname!=null)
intent.putExtra("FirstName", firstname);

twitter4j no authentication challenges found

Been trying to use twitter4j to post a tweet for couple days now without luck, what i want to do is for a person to post their new top score on their timeline from the app at the end of a round. Here is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweetr);
Button tweetr = (Button)findViewById(R.id.tweetr);
//create a new twitter configuration using user details
tweetTwitter = new TwitterFactory().getInstance();
tweetTwitter.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
//create a twitter instance
// tweetTwitter = new TwitterFactory(twitConf).getInstance();
tweetr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dt.execute();
}
});
}
public class TweetTask extends AsyncTask<Object, Void, String> {
#Override
protected String doInBackground(Object... values) {
/* try {
//requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
*/
try {
requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
String authUrl = requestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("URI", "DONE");
super.onPostExecute(result);
}
}
#Override
protected void onResume() {
super.onResume();
final Uri uri = getIntent().getData();
if(uri != null ){
Log.d("URI", uri.toString());
Thread th = new Thread(){
public void run(){
try {
String verifier = uri.getQueryParameter("oauth_verifier");
String oauthToken = uri.getQueryParameter("oauth_token");
RequestToken reqToken = tweetTwitter.getOAuthRequestToken(oauthToken,verifier);
AccessToken accessToken = tweetTwitter.getOAuthAccessToken(reqToken);
String token = accessToken.getToken(), secret = accessToken.getTokenSecret();
} catch (TwitterException ex) {
Log.e("Main.onNewIntent", "" + ex.getMessage());
}
}};
th.start();
}else
Log.d("URI", "FAILED");
}
}
This is my error print out
10-23 15:35:18.661: D/TWIT ER(2392): No authentication challenges foundRelevant discussions can be found on the Internet at:
refer to the javadoc of Twitter4J
In order to get access acquire AccessToken using xAuth, you must apply by sending an email to api#twitter.com — all other applications will receive an HTTP 401 error.

Android post picture to Facebook wall

I am trying to post a picture to my wall on Facebook. I have managed logging in and posting text to the wall. However, when I try posting the picture, nothing happens.
I am using the Android Facebook SDK.
Here is what I have so far:
Bundle params = new Bundle();
params.putString("method", "photos.upload");
Toast.makeText(FacebookPoster.this, "" + getIntent().getExtras().getByteArray("data").length, Toast.LENGTH_SHORT).show();
params.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
The Toast shows 8733, which means the byte array isn't empty
NB. Logcat output some warnings (not errors):
03-02 14:19:29.554: WARN/Bundle(1891): Attempt to cast generated internal exception:
03-02 14:19:29.554: WARN/Bundle(1891): java.lang.ClassCastException: java.lang.String
03-02 14:19:29.554: WARN/Bundle(1891): at android.os.Bundle.getByteArray(Bundle.java:1305)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.Util.openUrl(Util.java:155)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.Facebook.request(Facebook.java:559)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:253)
03-02 14:19:29.584: WARN/Bundle(1891): Key method expected byte[] but value was a java.lang.String. The default value <null> was returned.
(Shows several times underneath each other.)
What am I doing wrong?
SOLVED.
This is what I did to make it work:
facebook.authorize(this, new String[] { "publish_stream" },
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError dialogError) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
postToWall(values.getString(Facebook.TOKEN));
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
And the helper method:
private void postToWall(String accessToken) {
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, accessToken);
// The byte array is the data of a picture.
params.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
try {
facebook.request("me/photos", params, "POST");
} catch (FileNotFoundException fileNotFoundException) {
makeToast(fileNotFoundException.getMessage());
} catch (MalformedURLException malformedURLException) {
makeToast(malformedURLException.getMessage());
} catch (IOException ioException) {
makeToast(ioException.getMessage());
}
}
first thing is that you are not using graph api to upload the pictures... u r using the old rest api... try to use graph api, its simple...
Use following code:
Bundle param = new Bundle();
param.putString("message", "picture caption");
param.putByteArray("picture", ImageBytes);
mAsyncRunner.request("me/photos", param, "POST", new SampleUploadListener());
According to error message, it looks like its giving errors in getting bytes from intent's bundle...
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
facebook.authorize(FbdemoActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
#Override
public void onComplete(Bundle values) {
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
});
public void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile("/sdcard/viewitems.png");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, facebook.getAccessToken());
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
// process the response here: (executed in background thread)
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String src = json.getString("src");
// 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."
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
}
try this code it will work i had used the same code and uploads the image on Facebook.
Here is the working code sample. Pass image path and message.
public static void postImageonWall(String FilePath,String msg ) {
try {
Bitmap bi = BitmapFactory.decodeFile(FilePath);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.PNG, 100, stream); // where bm is bitmap from Sdcard
byte[] byteArray = stream.toByteArray();
Bundle param = new Bundle();
param = new Bundle();
param.putString("message", msg);
param.putString("filename", "Dessert Dash");
param.putByteArray("image", byteArray);
param.putString("caption", "Dessert Dash in Android Market Now");
mAsyncRunner.request("me/photos", param, "POST", fbrq, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String postwall(String uid)
{
String response = "";
try
{
String DIRECTORY_PATH = "/sdcard/159.jpg";
Bundle params = new Bundle();
Bitmap bitmap = BitmapFactory.decodeFile(DIRECTORY_PATH);
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
params.putString("app_id", uid);
params.putString("message", "picture caption");
params.putByteArray("picture", data);
mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
mAsyncRunner.request("me/photos", params, "POST", new WallPostRequestListener());
mAsyncRunner.request(response, new WallPostRequestListener());
Log.e("post result", response);
}
catch (Exception e)
{
e.printStackTrace();
}
return response;
}
public 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;
}
}
I'm sure Facebook will fix this eventually, but for the time being these examples (posted by other users) are very misleading because they do NOT in fact post to the user's wall (in the regular sense). Instead they are added to the user's photo gallery, and then happen to end up on the wall, but not in the same way in which normal posts work... there is no title and no caption and if you add another photo it ends up side by side with the first (rather than as a separate entry). So, when you use the api command me/feed it just fails in a spectacular way where it actually adds a post to the wall but it's an empty post from the application (it even disregards the title and caption).
Hopefully Facebook will fix this sometime in the near term.
Posting the image and Text to Facebook wall from code, Once you logged in using facebook credentials.
note : This is applicable only after logging in to your app using facebook credentials
sharePhotoToFacebook(); //function called from any UI event
private void sharePhotoToFacebook(){
Bitmap bitmap=null;
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/";
try {
File file = new File(path, "image9.jpg");
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
catch (Exception e){
Log.e("Error" , " Error in loading file");
}
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("A post from Android code")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
Toast.makeText(LoginSuccessActivity.this, "Image posted successfully", Toast.LENGTH_LONG).show();
}

Categories