I have been playing around with twitter4j and Android and so far so good. However I am having problems figuring out how to display the tweets properly on a list View. Here is my code so far, based on the code example given on the Twitter4j website:
public class MainActivity extends Activity {
//ListView with the tweets
private ListView timelineListView;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
//Adapter
ArrayAdapter<twitter4j.Status> tweetAdapter ;
//List
List<Status> rawStatuses;
//Other stuff
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
//Login methods, checking that there is an Internet connection, etc... When a button is
//pressed, an Asynctask is called and it retrieves the tweets:
class updateTimeline extends AsyncTask <Void, Void, Void>{
protected void onPreExecute(Void thing){
}
protected Void doInBackground(Void... arg0) {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
User user = twitter.verifyCredentials();
rawStatuses = twitter.getHomeTimeline();
System.out.println("Showing #" + user.getScreenName() + "'s home timeline.");
for (twitter4j.Status status : rawStatuses) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get timeline: " + te.getMessage());
//System.exit(-1);
}
return null;
}
protected void onPostExecute(Void result) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Timeline updated", Toast.LENGTH_SHORT)
.show();
tweetAdapter = new ArrayAdapter<twitter4j.Status>(MainActivity.this, android.R.layout.simple_list_item_1, rawStatuses);
timelineListView.setAdapter(tweetAdapter);
}
});
}
It retrieves the last 20 tweets or so just fine. But my problems comes fromt he final part, where I bind the list rawStatuses to the adapter and the listView, because it basically prints ALL the information on screen:
Ok, not all that information is useful or ever needed, but it is there. And I don't know how to display in the listView only the Twitter handle and the tweet, for example (i.e. extract that information from the list rawStatuses properly). I thought about having a List with the most useful information (something like:
List <User, Tweet, ID, Time> ), but it seems to me cumbersome and a very poor solution.
My question is: How can or should manage all that information that a tweet contains (an many tweets) so I can display what I want and still have the rest? The closest answer I have found is this answer, but the link given doesn't work anymore.
I hope I have explained myself. Thanks in advance.
I was running into the same problem, and you're actually on the right path here. What I did to resolve this was also create a list of Strings and storing that into an ArrayList, then putting that list into and ArrayAdapter rather that the raw statuses:
ArrayAdapter<String> stringTweetAdapter;
List<twitter4j.Status> statuses;
List<String> stringStatuses = new ArrayList<String>();
.....
User user = twitter.verifyCredentials();
statuses = twitter.getHomeTimeline();
System.out.println("Showing #" + user.getScreenName() + "'s home timeline.");
for (twitter4j.Status status : statuses) {
Log.d("Twitter","#" + status.getUser().getScreenName() + " - " + status.getText());
String myTweets = ("#" + status.getUser().getScreenName() + " - " + status.getText());
stringStatuses.add(myTweets);
}
......
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
progressDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Retrieving TimeLine Done..", Toast.LENGTH_SHORT).show();
stringTweetAdapter = new ArrayAdapter<String>(ShowTimeline.this, R.layout.timeline_list_item, R.id.textTimelineItem, stringStatuses);
twitterFeed.setAdapter(stringTweetAdapter);
}
});
}
Related
I have created an application that implements app to app calling using Sinch. It works only when the caller knows the name of the recipient.
To overcome this Sinch suggested to use PubNub to get the user state. They also have a tutorial here. The problem is that tutorial is old and PubNub has updated their API since. I tried to implement the functionality using their new API on my own using their docs, but it is not working or more accurately I don't know how to do it.
My current code is:
public class LoggedUsers extends Activity {
private PubNub pubNub;
String name;
private ArrayList users;
private JSONArray loggedUserList;
ListView UserList;
TextView allUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
allUsers = (TextView) findViewById(R.id.JSONFromPubNub);
SharedPreferences sp = getSharedPreferences("User_Details", MODE_APPEND);
try {
name = sp.getString("UserName", "");
} catch (NullPointerException e) {
}
final PNConfiguration pnc = new PNConfiguration();
pnc.setPublishKey("publish key");
pnc.setSubscribeKey("subscribe key");
pnc.setUuid(name);
pubNub = new PubNub(pnc);
users = new ArrayList<String>();
UserList = (ListView) findViewById(R.id.listView);
String user = getUserStatus();
allUsers.setText(user);
final ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), R.layout.single_item_list, users);
UserList.setAdapter(adapter);
pubNub.addListener(new SubscribeCallback() {
#Override
public void status(PubNub pubnub, PNStatus status) {
if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
// This event happens when radio / connectivity is lost
HashMap <String,String> map = new HashMap();
map.put("State","Offline");
pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());
} else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
// Connect event. You can do stuff like publish, and know you'll get it.
// Or just use the connected event to confirm you are subscribed for
// UI / internal notifications, etc
HashMap <String,String> map = new HashMap();
map.put("State","Online");
pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());
/* if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
pubnub.publish().channel("awesomeChannel").message("hello!!").async(new PNCallback<PNPublishResult>() {
#Override
public void onResponse(PNPublishResult result, PNStatus status) {
// Check whether request successfully completed or not.
if (!status.isError()) {
// Message successfully published to specified channel.
}
// Request processing failed.
else {
// Handle message publish error. Check 'category' property to find out possible issue
// because of which request did fail.
//
// Request can be resent using: [status retry];
}
}
});
}*/
} else if (status.getCategory() == PNStatusCategory.PNReconnectedCategory) {
HashMap <String,String> map = new HashMap();
map.put("State","Online");
pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());
// Happens as part of our regular operation. This event happens when
// radio / connectivity is lost, then regained.
} else if (status.getCategory() == PNStatusCategory.PNDecryptionErrorCategory) {
// Handle messsage decryption error. Probably client configured to
// encrypt messages and on live data feed it received plain text.
}
}
#Override
public void message(PubNub pubnub, PNMessageResult message) {
}
#Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
}
});
}
public String getUserStatus(){
final StringBuilder allUsers = new StringBuilder();
pubNub.subscribe().channels(Arrays.asList("CallingChannel1")).withPresence().execute();
pubNub.hereNow()
// tailor the next two lines to example
.channels(Arrays.asList("CallingChannel1"))
.includeState(true)
.includeUUIDs(true)
.async(new PNCallback<PNHereNowResult>() {
#Override
public void onResponse(PNHereNowResult result, PNStatus status) {
if (status.isError()) {
// handle error
return;
}
for (PNHereNowChannelData channelData : result.getChannels().values()) {
allUsers.append("---");
allUsers.append("channel:" + channelData.getChannelName());
allUsers.append("occoupancy: " + channelData.getOccupancy());
allUsers.append("occupants:");
for (PNHereNowOccupantData occupant : channelData.getOccupants()) {
allUsers.append("uuid: " + occupant.getUuid() + " state: " + occupant.getState());
}
}
}
});
return allUsers.toString();
}
#Override
protected void onResume() {
super.onResume();
}
}
Here are my problems:
I am trying to display all the data that I receive in a textview (later it will arranged in a listview or a recycler view) but I am getting a blank screen so I am getting null from the server.
The user status should be constantly updated to know if the user changes state (online -> offline) but there seems to be no async calls made in the code so I think it will be executed only once and then the dataset is not being changed.
How can I solve my problems?
PubNub Presence
You can monitor online and state changes using PubNub Presence. When you subscribe, subscribe with presence enabled and you will get state-change, join, leave & timeout events in the presence callback.
Callback callback = new Callback() {
#Override
public void successCallback(String channel, Object message) {
System.out.println(channel + " : "
+ message.getClass() + " : " + message.toString());
// take action on the presence events here
}
#Override
public void connectCallback(String channel, Object message) {
System.out.println("CONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void disconnectCallback(String channel, Object message) {
System.out.println("DISCONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void reconnectCallback(String channel, Object message) {
System.out.println("RECONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void errorCallback(String channel, PubnubError error) {
System.out.println("ERROR on channel " + channel
+ " : " + error.toString());
}
};
try {
pubnub.presence("my_channel", callback);
}
catch (PubnubException e) {
System.out.println(e.toString());
}
It appears Sinch is using a rather old version of the PubNub Android SDK. I would think you could still use PubNub Android SDK v4 to do what you need to do outside of Sinch SDK unless there is some explicit requirements by Sinch to use the same version of the SDK.
Hello all recently i was integrating digits by twitter in android for login users, now previously it was working fine but now i don't know what happened but after few login's it show this error
HTTP Error: 403 Forbidden, API Error: 239, User Message: Try Again
Now can someone please tell me what i am doing wrong also can someone pls tell me that in consumer key and consumer secret do i have to pass dev.twiiter my app credentials OR fabrics consumer key and secret, this thing is really very confuing because in docs they mentoned twitter keys but on some stackoverflow questions people say to use digits keys ?? Also i am not extending my activity from Application would that cause any problem or not ??
my code is give below please tell me what i am doing wrong it will be really helpful for me
public class Signup_firststageActivity extends AppCompatActivity {
private AuthCallback authCallback;
public AuthCallback getAuthCallback(){
return authCallback;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup_firststage);
TextView text = (TextView)findViewById(R.id.text);
Bundle b = getIntent().getExtras();
if (b.getString("error") == null) {
} else {
if (b.getString("error") != null && b.getString("error").equals("server_down")) {
text.setText("Error 503 Please Try Again");
} else {
}
}
//Twitter
TextView tryagain = (TextView)findViewById(R.id.tryagain);
tryagain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Digits.authenticate(new DigitsAuthConfig.Builder().withAuthCallBack(authCallback).withPhoneNumber("+918972745648").build());
}
});
final TwitterAuthConfig authConfig = new TwitterAuthConfig("agfjgD6wetDXdjfjuC4ywwoeD", "BshdjfjfwGz8WLaofkjfjsfjjsjsfhKpv60hQxni60oZwAu");
Fabric.with(getBaseContext(), new TwitterCore(authConfig), new Digits());
authCallback = new AuthCallback() {
#Override
public void success(DigitsSession session, String phoneNumber) {
Log.d("digits", "success phoneNumber: " + phoneNumber);
Log.d("digits", "session " + session.getPhoneNumber() + " " + session.toString() + " " + session.isValidUser() + " " + session.getAuthToken() + " " + session.getId());
// TwitterAuthConfig authConfig = TwitterCore.getInstance().getAuthConfig();
progressDialog = new ProgressDialog(Signup_firststageActivity.this);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please Wait... ");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.getWindow().setGravity(Gravity.CENTER);
progressDialog.show();
TwitterAuthToken authToken = (TwitterAuthToken) session.getAuthToken();
OAuthSigning oauthSigning = new OAuthSigning(authConfig, authToken);
Map<String, String> authHeaders = oauthSigning.getOAuthEchoHeadersForVerifyCredentials();
Log.d("digits", "authHeaders: 1" + authHeaders);
Signup_MobileNumber_requestData(session.getPhoneNumber());
Digits.getSessionManager().clearActiveSession(); // don't know should i write this here or not ??
}
#Override
public void failure(DigitsException exception) {
Log.d("digits", "failure");
// Do something on failure
}
};
DigitsAuthButton digitsButton = (DigitsAuthButton) findViewById(R.id.auth_button);
digitsButton.setCallback((this).getAuthCallback());
digitsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("digits", "button click");
}
});
}
Thank You in advance
This problem is occurred because of Key and Secret. I was trying to copy the values from Fabric dashboard and i got the same error.
It worked when i get the values from Fabric-Android Studio Plugin->Digits->Install->Apply
I am trying to post my message on twitter. When I click on button, it shows me message that your data has been posted on twitter,but when I check I don't get any message. Here is my code.
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
new updateTwitterStatus().execute(status);
}
});
here is update twitterstatus class
private class updateTwitterStatus extends AsyncTask<String,Void,Void>
{
#Override
protected void onPreExecute()
{
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... screen_name)
{
String status = null;
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.i(""+response, "value");
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
e.printStackTrace();
}
return null;
}
/// }
#Override
protected void onPostExecute(Void result)
{
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
please help me. I am finding for this since a couple of days, I know I have asked this but I am not getting any appropriate solution, thankyou.
For twitter there are two libraries.
Twitter4j.jar (For text wall post)
Twitpick.jar (for picture post)
Either you can go for SocialAuth library (Well managed and simple to use)
Below is my code and I integrated the facebook in my app. I am trying to make the user to be able to post an image on his wall after logging in. But I have been failing to make it for three days. Have seen few posts like this but I don't get any data(just it results in empty data data[]). I am even facing trouble with maintaining sessions too. Can some one please post working code or at least some sources where I can post image on facebook wall? Hope my below code is clear and my explanation is clear on what I have tried with the code below.
Activity's onCreate():-
public class FacebookActivity extends BaseActivity {
private static String APP_ID = "1303786178";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fb_screen);
btnFbLogin = (Button) findViewById(R.id.fbloginbtn);
btnFbLogout = (Button) findViewById(R.id.fblogoutbtn);
btnPostToWall = (Button) findViewById(R.id.fbpostbtn);
msget = (EditText)findViewById(R.id.fbmsget);
mAsyncRunner = new AsyncFacebookRunner(facebook);
mHandler = new Handler();
String passedpath = getIntent().getStringExtra("imagepath").toString();
imageuri = Uri.parse(passedpath);
/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
btnFbLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
logoutFromFacebook();
}
});
/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//postToWall(imageuri);
getAlbumId();
}
});
}
Posting on Wall includes two functions in my code one is getAlbumId() and the other is posttowall() which will be called from getAlbumId():-
public void getAlbumId()
{
dialog = ProgressDialog.show(FacebookActivity.this, "","Please Wait...", true, true);
//String wallAlbumID = null;
mAsyncRunner.request("me/albums", new BaseRequestListener(){
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
try{
Log.d("response in album"," "+response);
JSONObject json = Util.parseJson(response);
JSONArray albums = json.getJSONArray("data");
for (int i =0; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
if (album.getString("type").equalsIgnoreCase("wall")) {
final String wallAlbumID = album.getString("id");
globalalbid = wallAlbumID;
Log.d("JSON", wallAlbumID);
break;
}
}
dialog.dismiss();
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "id: " + globalalbid, Toast.LENGTH_LONG).show();
if(globalalbid != "")
postToWall(imageuri, globalalbid);
}
});
}catch (JSONException e) {
e.printStackTrace();
}
}
});
}
function to post on wall:
public void postToWall(Uri locuri, String wallid) {
if (facebook.isSessionValid()) {
Util.showAlert(this, "Warning", "You must first log in.");
} else {
dialog = ProgressDialog.show(FacebookActivity.this, "","Please Wait...", true, true);
// post on user's wall.
Uri photoUri = locuri;
if (photoUri != null) {
Bundle params = new Bundle();
try {
params.putByteArray("photo",
Utility.scaleImage(getApplicationContext(), photoUri));
} catch (IOException e) {
e.printStackTrace();
}
String imagecaption = msget.getText().toString();
if(imagecaption != "")
params.putString("caption", imagecaption);
mAsyncRunner.request(wallid+"/photos", params, "POST", new PhotoUploadListener(), null);
} else {
Toast.makeText(getApplicationContext(),
"Error from the pic", Toast.LENGTH_SHORT)
.show();
}
}
}
}
I always get album id empty. Is there anything wrong in the way that I try to get album id. Because I have seen on some posts those who try to access album id and then posting the image on album. They seem to be keeping wall as common findout in the album name. If it is so, some new ones contain timeline photos name, then how can we findout the album id. Please suggest.
Note: I want the image to be visible on to the wall not to only album.
Instead of uploading the photo to the user's album, post the image to /me/feed instead. Make sure you are asking the user for the publish_stream permission. This will upload the photo straight to the user's wall instead of going to an album.
I am using the Facebook SDK to post messages on walls.
Now I need to fetch the Facebook friends list. Can anybody help me with this?
-- Edit --
try {
Facebook mFacebook = new Facebook(Constants.FB_APP_ID);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Bundle bundle = new Bundle();
bundle.putString("fields", "birthday");
mFacebook.request("me/friends", bundle);
} catch(Exception e){
Log.e(Constants.LOGTAG, " " + CLASSTAG + " Exception = "+e.getMessage());
}
When I execute my activity, I'm not seeing anything, but in LogCat there is a debug message like:
06-04 17:43:13.863: DEBUG/Facebook-Util(409): GET URL: https://graph.facebook.com/me/friends?format=json&fields=birthday
And when I tried to access this url directly from the browser, I'm getting the following error response:
{
error: {
type: "OAuthException"
message: "An active access token must be used to query information about the current user."
}
}
You are about half way there. You've sent the request, but you haven't defined anything to receive the response with your results. You can extend BaseRequestListener class and implement its onComplete method to do that. Something like this:
public class FriendListRequestListener extends BaseRequestListener {
public void onComplete(final String response) {
_error = null;
try {
JSONObject json = Util.parseJson(response);
final JSONArray friends = json.getJSONArray("data");
FacebookActivity.this.runOnUiThread(new Runnable() {
public void run() {
// Do stuff here with your friends array,
// which is an array of JSONObjects.
}
});
} catch (JSONException e) {
_error = "JSON Error in response";
} catch (FacebookError e) {
_error = "Facebook Error: " + e.getMessage();
}
if (_error != null)
{
FacebookActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Error occurred: " +
_error, Toast.LENGTH_LONG).show();
}
});
}
}
}
Then in your request you can specify the request listener to use for receiving the response from the request, like this:
mFacebook.request("me/friends", bundle, new FriendListRequestListener());
Using FQL Query
String fqlQuery = "SELECT uid, name, pic_square FROM user WHERE uid IN " +
"(SELECT uid2 FROM friend WHERE uid1 = me() LIMIT 25)";
Bundle params = new Bundle();
params.putString("q", fqlQuery);
Session session = Session.getActiveSession();
Request request = new Request(session,"/fql", params,HttpMethod.GET, new Request.Callback(){
public void onCompleted(Response response) {
Log.i(TAG, "Result: " + response.toString());
try{
GraphObject graphObject = response.getGraphObject();
JSONObject jsonObject = graphObject.getInnerJSONObject();
Log.d("data", jsonObject.toString(0));
JSONArray array = jsonObject.getJSONArray("data");
for(int i=0;i<array.length();i++)
{
JSONObject friend = array.getJSONObject(i);
Log.d("uid",friend.getString("uid"));
Log.d("name", friend.getString("name"));
Log.d("pic_square",friend.getString("pic_square"));
}
}catch(JSONException e){
e.printStackTrace();
}
}
});
Request.executeBatchAsync(request);
I was dealing with that and I found the answer.
The problem is that you want to access to your data without previous registration with your facebook token.
First, you must to define your Facebook variable:
Facebook mFacebook = new Facebook(getString(R.string.fb_id));
Later, define your AsyncFacebookRunner:
final AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Ok, now you must to authorize your request, with autorize method. Note that you must implement callback methods on DialogListener(), put attention on onComplete() method. On that method you must to run the friend fetch request. Now your request will pass because now you are authenticated.
Now the code:
mFacebook.authorize(this, fb_perms, new DialogListener(){
/**
* Triggered on a successful Facebook registration.
*/
public void onComplete(Bundle values) {
mAsyncRunner.request("me/friends", new FriendListRequestListener());
}
/**
* Triggered on a FacebookError.
*/
public void onFacebookError(FacebookError e) {
}
/**
* Triggered on a DialogError.
*/
public void onError(DialogError e) {
}
/**
* Triggered when the User cancels the Facebook Login.
*/
public void onCancel() {
}
});
You can use the FriendListRequestListener class that was post by #Kon
I hope this helps.
Cheers!
Hi Please check below link
Facebook API for Android: how to get extended info regarding user`s friends?
Post on user's friends facebook wall through android application
I faced the same problem yesterday.
I wondering if you have overriden the onActivityResult() function?
private Facebook mFacebook=null;
...
...
...
#Override
protected void onActivityResult(int requestCode,
int resultCode,
Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
Check this answer in order to know how to get Facebook friend list and who of these friends have installed your app using new Facebook SDK 3.0 for Android.
I'm doing something like this is working good....
jsonObj = Util.parseJson(facebook.request("me/friends"));
JSONArray jArray = jsonObj.getJSONArray("data");
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.v("THIS IS DATA", i+" : "+jArray.getJSONObject(i));
}
Hope it is helpful...
If somebody is reading this in late 2015, the answer and code is quite simple. Take a look at official documentation here (in the code window click on Android SDK).
Keep in mind that you need to have user_friends permission.
Bro tip for android-rx users - get your friends synchronously, then process message and return Observable:
public Observable<List<Friend>> execute() {
return Observable.defer(new Func0<Observable<List<Friend>>>() {
#Override
public Observable<List<Friend>> call() {
AccessToken a = AccessToken.getCurrentAccessToken();
if (Utils.isValid(a)) {
try {
GraphResponse res = new GraphRequest(AccessToken.getCurrentAccessToken(), "me/friends").executeAndWait();
// process result
return Observable.just(your friend list);
} catch (Exception e) {
// notify user or load again
}
}
// invalid access token -> notify user
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}