I am trying to retrieve the text from every tweet of a user.
I don't send a get request.
I successfully connect with a tweeter account to my app with :
activity.client.authorize(activity, new Callback<TwitterSession>()
{
#Override
public void success(Result<TwitterSession> result)
{
Toast.makeText(getApplicationContext(), "Login worked", Toast.LENGTH_LONG).show();
writeInfile(result);
}
#Override
public void failure(TwitterException e)
{
Toast.makeText(getApplicationContext(), "Login failed", Toast.LENGTH_LONG).show();
}
});
With the result I can access informations from my user such as his id or his name.
I also have the UserTimeLine
final UserTimeline userTimeline = new UserTimeline.Builder()
.userId(result.data.getUserId())
.build();
How can I get his tweets or the id of his tweets from there ?
Thank you
I managed to do it by looking at every methods given by auto completion so if it can help anyone, here is how I did it :
void writeData(ContentResolver contentResolver)
{
activity.client.authorize(activity, new Callback<TwitterSession>()
{
#Override
public void success(Result<TwitterSession> result)
{
writeInfile(result);
}
#Override
public void failure(TwitterException e)
{
Log.e("Twitter Log in", e.toString());
}
});
}
void writeInFile(Result<TwitterSession> result)
{
userTimeline = new UserTimeline.Builder()
.userId(result.data.getUserId())
.includeRetweets(false)
.maxItemsPerRequest(200)
.build();
userTimeline.next(null, callback);
}
Callback<TimelineResult<Tweet>> callback = new Callback<TimelineResult<Tweet>>()
{
#Override
public void success(Result<TimelineResult<Tweet>> searchResult)
{
List<Tweet> tweets = searchResult.data.items;
for (Tweet tweet : tweets)
{
String str = tweet.text; //Here is the body
maxId = tweet.id;
}
if (searchResult.data.items.size() == 200)
userTimeline.previous(maxId, callback);
else
closeOutputFile();
}
#Override
public void failure(TwitterException error)
{
//Do something
}
};
Related
First Button has the following perms , and after I'm writting the code as is described in the try catch to make the call to facebook and retrieving data, when click button is pressed. Here there no need to set parameters like another api call.
In the folowing link shows the implementation too, https://developers.facebook.com/docs/android/graph
loginButtonFacebooK.setReadPermissions(Arrays
.asList("public_profile"," email", "user_friends"));
try {
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
if( accessToken != null ){
GraphRequestBatch batch = new GraphRequestBatch(GraphRequest.newMeRequest(accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String versionApp = GeneralLogic.getVersionName( SplashActivity.this );
Usuario usuarioNexusDomun = new Usuario(
object.getString("id"),
object.getString("first_name"),
object.getString("last_name"),
object.getString("name"),
object.getString("link"),
object.getString("gender"),
object.getString("updated_time"),
token.getToken(),
versionApp);
// here is saving data and just is showing id and name,
// other data is coming null
loginFacebookOk = true;
} catch (JSONException e) {
e.getMessage();
}
}
})
);
batch.addCallback(new GraphRequestBatch.Callback() {
#Override
public void onBatchCompleted(GraphRequestBatch batch) {
if( loginFacebookOk ) {
gotoMain();
} else {
errorMsg(1);
}
}
});
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}catch (Exception e){
e.getMessage();
}
I am using Fabric sdk for Twitter. In this I am able to make login request as it's described in its document. Now I wan't to get list of follower of logged in user and show in RecycleView with follower name and profile image. I have tried various solutions like:
private void getFollowersdReq(long userID) {
showProgressDialog();
JsonObjectRequest getRegisterReq = new JsonObjectRequest(Request.Method.GET,
"https://api.twitter.com/1.1/followers/list.json?cursor=-1&&skip_status=true&include_user_entities=false&user_id=" + userID, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
LogUtils.LOGD("Server Response", response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("server Error",
"Error: " + error.getMessage());
Toast.makeText(getActivity(),
"Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(getRegisterReq, new SignpostUrlStack(twitterToken, secret));
// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}
In above code I am calling Twitter API to get list of followers but in this I am getting error message
{
"errors": [
{
"code": 215,
"message": "Bad Authentication data."
}
]
}
Also I have tried
class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
public UsersService getUsersService() {
return getService(UsersService.class);
}
}
interface CustomService {
#GET("/1.1/followers/list.json")
void show(#Query("user_id") Long userId,
#Query("screen_name") String var,
#Query("skip_status") Boolean var1,
#Query("include_user_entities") Boolean var2,
#Query("count") Integer var3, Callback<User> cb);
}
interface UsersService {
#GET("/1.1/users/show.json")
void show(#Query("user_id") Long userId,
#Query("screen_name") String screenName,
#Query("include_entities") Boolean includeEntities,
Callback<User> cb);
}
Called this class like:
new MyTwitterApiClient(session).getCustomService().show(userID, null, true, true, 100, new Callback<User>() {
#Override
public void success(Result<User> result) {
LogUtils.LOGI("Get success",result.toString());
}
#Override
public void failure(TwitterException e) {
hideProgressDialog();
}
});
By this method also I am not able to get desired output.
The second method (using TwitterApiClient) is almost correct except for the response data model. Refere https://dev.twitter.com/rest/reference/get/followers/list for the structure of the response. You need to build a data model according to this structure.
Here is the fix :
//data model
public class Followers {
#SerializedName("users")
public final List<User> users;
public Followers(List<User> users) {
this.users = users;
}
}
class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
interface CustomService {#GET("/1.1/followers/list.json")
void show(#Query("user_id") Long userId, #Query("screen_name") String
var, #Query("skip_status") Boolean var1, #Query("include_user_entities") Boolean var2, #Query("count") Integer var3, Callback < Followers > cb);
}
new MyTwitterApiClient(session).getCustomService().show(userID, null, true, true, 100, new Callback < Followers > () {#Override
public void success(Result < Followers > result) {
Log.i("Get success", "" + result.data.users.size());
}
#Override
public void failure(TwitterException e) {
}
});
The above code is working for me. Hope it helps!
MyTwitterApiClient.java
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterSession;
import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.Query;
public class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
/**
* Provide CustomService with defined endpoints
*/
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
// example users/show service endpoint
interface CustomService {
#GET("/1.1/followers/ids.json")
void list(#Query("user_id") long id, Callback<Response> cb);
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = "YOUR_TWITTER_KEY";
private static final String TWITTER_SECRET = "YOUR_TWITTER_SECRET";
TwitterLoginButton loginButton;
SharedPreferences shared;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig), new Crashlytics());
setContentView(R.layout.activity_main);
shared = getSharedPreferences("demotwitter", Context.MODE_PRIVATE);
loginButton = (TwitterLoginButton) findViewById(R.id.login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = Twitter.getSessionManager()
.getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
//Here we get all the details of user's twitter account
System.out.println(result.data.getUserName()
+ result.data.getUserId());
Twitter.getApiClient(session).getAccountService()
.verifyCredentials(true, false, new Callback<User>() {
#Override
public void success(Result<User> userResult) {
User user = userResult.data;
//Here we get image url which can be used to set as image wherever required.
System.out.println(user.profileImageUrl+" "+user.email+""+user.followersCount);
}
#Override
public void failure(TwitterException e) {
}
});
shared.edit().putString("tweetToken", token).commit();
shared.edit().putString("tweetSecret", secret).commit();
TwitterAuthClient authClient = new TwitterAuthClient();
authClient.requestEmail(session, new Callback<String>() {
#Override
public void success(Result<String> result) {
// Do something with the result, which provides the
// email address
System.out.println(result.toString());
Log.d("Result", result.toString());
Toast.makeText(getApplicationContext(), result.data,
Toast.LENGTH_LONG).show();
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
System.out.println(exception.getMessage());
}
});
MyTwitterApiClient apiclients=new MyTwitterApiClient(session);
apiclients.getCustomService().list(result.data.getUserId(), new Callback<Response>() {
#Override
public void failure(TwitterException arg0) {
// TODO Auto-generated method stub
}
#Override
public void success(Result<Response> arg0) {
// TODO Auto-generated method stub
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(arg0.response.getBody().in()));
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
System.out.println("Response is>>>>>>>>>"+result);
try {
JSONObject obj=new JSONObject(result);
JSONArray ids=obj.getJSONArray("ids");
//This is where we get ids of followers
for(int i=0;i<ids.length();i++){
System.out.println("Id of user "+(i+1)+" is "+ids.get(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result to the login button.
loginButton.onActivityResult(requestCode, resultCode, data);
}
}
I am implementing a Facebook login with the SDK 4 but it only works once.
When I install the app I can login with Facebook perfectly. However, when I logout and try to login again, I get the Sorry, something went wrong message:
How I init SDK:
// Called in onCreate()
private void initFacebook() {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "On success");
getUserData(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "On cancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, error.toString());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (callbackManager != null) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
private void getUserData(AccessToken accessToken) {
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject json,
GraphResponse response) {
Log.v(TAG, response.toString());
if (response.getError() != null) {
// handle error
Log.d(TAG, "GraphRequest error");
} else {
Log.d(TAG, "GraphRequest success");
try {
String jsonresult = String.valueOf(json);
Log.d(TAG, "JSON Result" + jsonresult);
String str_email = json.getString("email");
String str_id = json.getString("id");
String str_name = json.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
onLoginSuccess();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email");
request.setParameters(parameters);
request.executeAsync();
}
And here the login and logout:
#Override
public void onLoginClicked() {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email"));
}
#Override
public void onLogoutClicked() {
LoginManager.getInstance().logOut();
}
What is going wrong?
Thanks!
first of all initialize facebook sdk , just before setContentview();
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.main);
then in onResume() you should call
#Override
protected void onResume() {
super.onResume();
AppEventsLogger.activateApp(this);
}
in onPause() call following:
#Override
public void onPause() {
super.onPause();
//for facebook
AppEventsLogger.deactivateApp(this);
}
except this your code is looking fine, yesterday i also got some problem like this, i guess it is problem from Facebook, because today my app work fine automatically.
I'm logging in with twitter using Fabric.
This is how I fetch the user data:
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
AccountService ac = Twitter.getApiClient(result.data).getAccountService();
ac.verifyCredentials(true, true, new Callback<com.twitter.sdk.android.core.models.User>() {
#Override
public void success(Result<com.twitter.sdk.android.core.models.User> result) {
String imageUrl = result.data.profileImageUrl;
String email = result.data.email;
String userName = result.data.name;
System.out.println(imageUrl);
System.out.println(email);
System.out.println(userName);
}
#Override
public void failure(TwitterException e) {
}
});
}
This is working fine, except that the email variable is null when I print to log. Is there an other way of fetching the user email?
-Here is the Solution!
twitauthobj.requestEmail(twitsessionobj,new Callback<String>() {
#Override
public void success(Result<String> stringResult) {
'You code here'
}
#Override
public void failure(TwitterException e) {
}
});
-Thanks let me inform if t doesnt work!
To bypass Twitter's useless request email activity and to fix a leak, I dug through the source code and pulled this out:
new Retrofit.Builder()
.client(getClient(sessionResult))
.baseUrl(new TwitterApi().getBaseHostUrl())
.addConverterFactory(getFactory())
.build()
.create(EmailService.class)
.getEmail()
.enqueue(new Callback<User>() {
#Override
public void success(Result<User> result) {
String email = result.data.email;
// Handle the result
if (email == null) {
TwitterProvider.this.failure(
new TwitterException("Your application may not have access to"
+ " email addresses or the user may not have an email address. To request"
+ " access, please visit https://support.twitter.com/forms/platform."));
} else if (email.equals("")) {
TwitterProvider.this.failure(
new TwitterException("This user does not have an email address."));
} else {
mCallbackObject.onSuccess(createIdpResponse(sessionResult.data, email));
}
}
#Override
public void failure(TwitterException exception) {
TwitterProvider.this.failure(exception);
}
});
private OkHttpClient getClient(Result<TwitterSession> sessionResult) {
return OkHttpClientHelper.getOkHttpClient(
sessionResult.data,
TwitterCore.getInstance().getAuthConfig(),
TwitterCore.getInstance().getSSLSocketFactory());
}
private GsonConverterFactory getFactory() {
return GsonConverterFactory.create(
new GsonBuilder()
.registerTypeAdapterFactory(new SafeListAdapter())
.registerTypeAdapterFactory(new SafeMapAdapter())
.registerTypeAdapter(BindingValues.class, new BindingValuesAdapter())
.create());
}
EmailService:
interface EmailService {
#GET("/1.1/account/verify_credentials.json?include_email=true?include_entities=true?skip_status=true")
Call<User> getEmail();
}
Does anyone know if there is a way to pull a signed in users profile picture to be placed through the app, to maybe place it on the ActionBar as they navigate around?
hints, tips, examples, downloads all welcome :)
If you can help me, please assume I very little knowledge regarding anything outside basic Java!
Again, thanks people x
You can get a user's profile image by using /1.1/users/show.json. You can refer to REST API URLs for Twitter data.
By extending TwitterApiClient we can retrieve Twitter data from the URL.
class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public UsersService getUsersService() {
return getService(UsersService.class);
}
}
interface UsersService {
#GET("/1.1/users/show.json")
void show(#Query("user_id") Long userId,
#Query("screen_name") String screenName,
#Query("include_entities") Boolean includeEntities,
Callback<User> cb);
}
Next, get the UsersService and call its show method, passing in the defined query parameters. I defined the query parameters based on the ones that are documented.
new MyTwitterApiClient(session).getUsersService().show(12L, null, true,
new Callback<User>() {
#Override
public void success(Result<User> result) {
Log.d("twittercommunity", "user's profile url is "
+ result.data.profileImageUrlHttps);
}
#Override
public void failure(TwitterException exception) {
Log.d("twittercommunity", "exception is " + exception);
}
});
Courtesy: https://twittercommunity.com/t/android-get-user-profile-image/30579/2
This is how I got mine to work:
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
twitterApiClient.getAccountService().verifyCredentials(false,false, new Callback<User>() {
#Override
public void success(Result<User> userResult) {
String name = userResult.data.name;
String profilebannerurl = userResult.data.profileBannerUrl;
String profileurl = userResult.data.profileImageUrl;
}
#Override
public void failure(TwitterException e) {
}
});
I have place this piece of code within my LoginButton callback method:
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) { <insert here> }
I did it with a custom button and this is the code that is executed by it's onClick listener :
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_API_KEY, TWITTER_API_SECRET);
Fabric.with(activity, new Twitter(authConfig));
TwitterCore.getInstance().getApiClient().getAccountService().verifyCredentials(false, false, new com.twitter.sdk.android.core.Callback<User>() {
#Override
public void success(Result<User> result) {
Log.d(TAG, "Twitter log in success");
String userName = result.data.screenName;
int userId = result.data.id;
String pictureUrl = result.data.profileImageUrl;
String coverUrl = result.data.profileBannerUrl;
}
#Override
public void failure(TwitterException e) {
Log.d(TAG, "Twitter log in error : " + e.getMessage());
}
});
I should ask the user to authorize access to your app and log him in if he accepts.