Can't get List of followers in Twitter using Fabric - android

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);
}
}

Related

Jwt token refresh?

I have an API for refreshing a token, but I am not able to use refresh token in my app, after a user login a token gets expired after 60min so now I want to refresh the user token, how can I use refresh token in my app
my interface of refresh token:
#POST("/api/token/refresh")
Call<ResponseBody> getAccessToken();
My Session:
public class Session {
Context context;
private SharedPreferences prefs;
private Session session;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
this.context = cntx;
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setJwtToken(String token) {
prefs.edit().putString("token", token).commit();
}
public String getJwtToken() {
String token = prefs.getString("token", "");
if (token == null || token.isEmpty()) {
token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";
}
return token;
}
public String getRefreshToken() {
String token = prefs.getString("RefreshToken", "");
if (token == null || token.isEmpty()) {
token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> call = apiInterface.getAccessToken();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
JSONObject resultObject = new JSONObject();
JSONObject tokenObject = null;
try {
tokenObject = resultObject.getJSONObject("token");
} catch (JSONException e) {
e.printStackTrace();
}
String newToken = null;
try {
newToken = tokenObject.getString("accessToken");
} catch (JSONException e) {
e.printStackTrace();
}
newToken = "Bearer " + newToken;
session.setJwtToken(newToken);
Log.e("Token Result Object", session.getJwtToken());
Log.e("Token Response Object", session.getRefreshToken());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
return token;
}
public void setRefreshToken(String token) {
prefs.edit().putString("RefreshToken", token).commit();
}
My login:
public class LoginActivity extends AppCompatActivity {
private Button userLogin;
ApiInterface apiInterface;
private EditText loginEmail, loginPassword;
private User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginEmail = findViewById(R.id.loginEmail);
loginPassword = findViewById(R.id.loginPassword);
userLogin = findViewById(R.id.loginButton);
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userLogin();
}
});
TextView register = (TextView) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
startActivity(intent);
}
});
ImageView back = (ImageView) findViewById(R.id.back_arrow_login);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
public void userLogin() {
final User user = new User();
final Session session = new Session(this);
user.setEmail(loginEmail.getText().toString().trim());
user.setPassword(loginPassword.getText().toString().trim());
apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> call = apiInterface.logMeIn(session.getJwtToken(),user);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.code() == 200) {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONObject dataObject = jsonObject.getJSONObject("data");
String token = dataObject.getString("access_token");
String refToken = dataObject.getString("refresh_token");
session.setJwtToken("Bearer " + token);
session.setRefreshToken("Bearer"+refToken);
String name=user.getName();
Toast.makeText(LoginActivity.this, "WELCOME", Toast.LENGTH_SHORT).show();
Log.e("USER", jsonObject.toString());
startActivity(new Intent(LoginActivity.this, MainActivity.class));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else
Log.e("TestActivity", response.raw().toString());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
}
Please help me clear out the method or process ,so that i can refresh the user token after it gets expired
public class ServiceFactory {
private static final long CONNECTION_TIMEOUT = 60 * 1000; // one minute
private Activity activity;
public ServiceFactory(Activity activity) {
this.activity = activity;
}
public static <T> T createService(final Class<T> clazz) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(clazz);
}
public <T> T createServiceWithToken(final Class<T> clazz) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(getHttpClientBuilder())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(clazz);
}
private OkHttpClient getHttpClientBuilder() {
// Setup OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.authenticator(new TokenAuthenticator());
return builder.build();
}
private void logout() {
if (activity != null) {
Intent intent = new Intent(activity, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
activity.finish();
}
}
class TokenAuthenticator implements Authenticator {
#Nullable
#Override
public Request authenticate(#NonNull Route route, #NonNull Response response) throws IOException {
TokenManager tokenManager = new TokenManager();
//called renew api call
retrofit2.Response<ResponseModel> responseModel= ServiceFactory.createService(YOUR_API.class)
.renewToken(tokenManager.getBearer())
.execute();
if (responseModel.code() == 401) {
//remove token
logout();
return null;
} else {
//saved token to local
}
//returned new reuwst with updated header
return response.request().newBuilder()
.header(APIConstants.AUTHORIZATION, tokenManager.getBearer())
.build();
}
}
}

Unable to send post request with volley android like ajax

I have a problem with volley, I googled around for samples to upload the image
with volley, however, since I'm a beginner, I have a hard time trying to make my code that works in
ajax into android (Trying to do the eact same thing with volley). The following code is what I want to do with android
volley Multipart. Some tips or examples will be great. I would love to hear from you!
$.ajax({
type: 'post',
processData: false,
contentType: false,
data: "/imagepath/sample.PNG",
url: "https://linktotheimageuploader/upload",
async: true,
success: function (res) {
if (res.status == 0) {
console.log(res);
} else {
// NOP
}
}
, error: function () {
//failed to upload
}
});
I tried to convert it to Volley android like the following but I am unable to achieve what I want to do.
public void uploadImage(String url , final File fileName) {
final File encodedString = fileName;
RequestQueue rq = Volley.newRequestQueue(this);
Log.d("URL", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.e("RESPONSE", response);
JSONObject json = new JSONObject(response);
Toast.makeText(getBaseContext(),
"The image is upload" +response, Toast.LENGTH_SHORT)
.show();
} catch (JSONException e) {
Log.d("JSON Exception", e.toString());
Toast.makeText(getBaseContext(),
"Error while loadin data!",
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error [" + error + "]");
Toast.makeText(getBaseContext(),
"Cannot connect to server", Toast.LENGTH_LONG)
.show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(encodedString); // I want to set the file not a String,
return params;
}
};
rq.add(stringRequest);
}
First, To get callBack from the server in MultipartUploadRequest, create a class by extending the UploadServiceBroadcastReceiver
public class SingleUploadBroadcastReceiver extends UploadServiceBroadcastReceiver {
public interface Delegate {
void onProgress(int progress);
void onProgress(long uploadedBytes, long totalBytes);
void onError(Exception exception);
void onCompleted(int serverResponseCode, byte[] serverResponseBody);
void onCancelled();
}
private String mUploadID;
private Delegate mDelegate;
public void setUploadID(String uploadID) {
mUploadID = uploadID;
}
public void setDelegate(Delegate delegate) {
mDelegate = delegate;
}
#Override
public void onProgress(String uploadId, int progress) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onProgress(progress);
}
}
#Override
public void onProgress(String uploadId, long uploadedBytes, long totalBytes) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onProgress(uploadedBytes, totalBytes);
}
}
#Override
public void onError(String uploadId, Exception exception) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onError(exception);
}
}
#Override
public void onCompleted(String uploadId, int serverResponseCode, byte[] serverResponseBody) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onCompleted(serverResponseCode, serverResponseBody);
}
}
#Override
public void onCancelled(String uploadId) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onCancelled();
}
}
}
Then, in your activity:
public class YourActivity extends Activity implements SingleUploadBroadcastReceiver.Delegate {
private static final String TAG = "AndroidUploadService";
private final SingleUploadBroadcastReceiver uploadReceiver =
new SingleUploadBroadcastReceiver();
#Override
protected void onResume() {
super.onResume();
uploadReceiver.register(this);
}
#Override
protected void onPause() {
super.onPause();
uploadReceiver.unregister(this);
}
public void uploadMultipart(final Context context) {
try {
String uploadId = UUID.randomUUID().toString();
uploadReceiver.setDelegate(this);
uploadReceiver.setUploadID(uploadId);
new MultipartUploadRequest(context, uploadId, "http://upload.server.com/path")
.addFileToUpload("/absolute/path/to/your/file", "your-param-name")
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload();
} catch (Exception exc) {
Log.e(TAG, exc.getMessage(), exc);
}
}
#Override
public void onProgress(int progress) {
//your implementation
}
#Override
public void onProgress(long uploadedBytes, long totalBytes) {
//your implementation
}
#Override
public void onError(Exception exception) {
//your implementation
}
#Override
public void onCompleted(int serverResponseCode, byte[] serverResponseBody) {
//your implementation
}
#Override
public void onCancelled() {
//your implementation
}
}
I have done this with Volley in two different ways:
Sending the image as a Base64 encoded string
Sending the image as multipart
Sending it as encoded String
This method will encode a bitmap into a Base64 String which you can send as a parameter in your request. Then, the server can decode the String back to an image.
public String bitmapToString(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("image", bitmapToString(BitmapFactory.decodeFile(filePath)));
return params;
}
};
Sending it as Multipart
This is a little bit more tricky since you'll need to use custom classes made by some dude named anggadarkprince, but it's way faster than the first option
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
RandomAccessFile f = null;
try {
f = new RandomAccessFile(filePath, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
byte[] b;
try {
b = new byte[(int)f.length()];
f.readFully(b);
} catch (IOException e) {
e.printStackTrace();
return null;
}
params.put("image", new DataPart("image.jpg", b, "image/jpeg"));
return params;
}
};
Here you'll find the class you need to do this.

Issue getting Facebook information

I want facebook profile information in my code. This code works Log.e("in try start", "tryyyyyyyyy"); until here but after that not even single log is executed.
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public void loginToFacebook() {
// mPrefs = getPreferences(SharedPreferences.);
// String access_token = mPrefs.getString("access_token", null);
//long expires = mPrefs.getLong("access_expires", 0);
// if (access_token != null) {
// facebook.setAccessToken(access_token);
// }
// if (expires != 0) {
// facebook.setAccessExpires(expires);
// }
if (!facebook.isSessionValid()) {
facebook.authorize(getActivity(),
new String[] { "email", "publish_actions" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
Toast.makeText(getActivity(), "hiiiiii", Toast.LENGTH_SHORT).show();
//mPrefs=getSharedPreferences("data", getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
Log.e("getProfileInformation entry", "getProfileInformation");
getProfileInformation();
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
});
}
}
public void getProfileInformation() {
Toast.makeText(getActivity(), "byeeeeeee", Toast.LENGTH_SHORT).show();
Log.e("getProfileInformation start", "getProfileInformation");
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
Log.e("in try start", "tryyyyyyyyy");
JSONObject profile = new JSONObject(json);
// getting name of the user
Log.d("profile", ""+profile);
fb_name = profile.getString("name");
// getting email of the user
fb_email = profile.getString("email");
Log.d("fb_name", "naem"+fb_name+"emial"+fb_email);
//fb_login=true;
// fb_Image = getUserPic(fb_email);
// LoginFuction();
} catch (JSONException e) {
e.printStackTrace();
Log.e("catchhhhhh", ""+e.getMessage());
}
}
public Bitmap getUserPic(String userID) {
String imageURL;
Bitmap bitmap = null;
Log.d("TAG", "Loading Picture");
imageURL = "http://graph.facebook.com/"+userID+"/picture?type=small";
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
Log.d("TAG", "Loading Picture FAILED");
e.printStackTrace();
}
return bitmap;
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
This code does not give me any name or emailId.
-Hello Abhishek !
- I have tried using Facebook sdk4.+ and i am getting profile info perfectly.
-Firs of all add below code into your oncreate method before setcontentview
FacebookSdk.sdkInitialize(getApplicationContext());
-Then Create you Callbackmanager using below code:-
callbackManager = CallbackManager.Factory.create();
-Add Permissions using below code:-
permission.add("publish_actions");
-Below code is used for Login
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
act,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
if (!TextUtils.isEmpty(object.toString())) {
try {
JSONObject jresJsonObject = new JSONObject(object.toString());
String id = "", name = "", gender = "";
if (!(jresJsonObject.isNull("id"))) {
id = jresJsonObject.getString("id");
}
if (!(jresJsonObject.isNull("gender"))) {
gender = jresJsonObject.getString("gender");
if (gender.equals("male")) {
gender = "0";
} else {
gender = "1";
}
}
if (!(jresJsonObject.isNull("name"))) {
name = jresJsonObject.getString("name");
}
} catch (Exception e) {
}
}
Log.e("graphrequest", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,gender,link");
request.setParameters(parameters);
request.executeAndWait();
}
#Override
public void onCancel() {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
#Override
public void onError(FacebookException exception) {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
});
LoginManager.getInstance().logInWithPublishPermissions(this, permission);
-Last but no least add below code in your OnActivitResult
callbackManager.onActivityResult(requestCode, resultCode, data);
NOTE:- This is using latest Facebook sdk
-Please inform me if it is not usefull or you are still getting issue in this.

Twitter How to get user profile pic using Fabric plugin in Android Studio

I am using Fabric plugin with Android studio after login I got session, username and userid. Also got email address. But can't find any option to fetch user profile pic.
/
/inti twitter client
loginButton = (TwitterLoginButton) findViewById(R.id.twitter_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
System.out.println("twitter success"+result.data.getUserId()+result.data.getUserName());
gettwitteremail();
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
}
});
private void gettwitteremail(){
TwitterSession session =
Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
TwitterAuthClient authClient = new TwitterAuthClient();
authClient.requestEmail(session, new Callback() {
#Override
public void success(Result result) {
// Do something with the result, which provides
// the email address
System.out.println("twitter sucess"+result.data);
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
System.out.println("twitter sucess"+exception.getMessage());
exception.printStackTrace();
}
});
Fixed
Fixed by using following code
TwitterSession session =
Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
TwitterApiClient twitterApiClient = Twitter.getApiClient();
StatusesService twapiclient = twitterApiClient.getStatusesService();
twapiclient.userTimeline(twitteruserid,null,null,null,null,null,null,null,null,new Callback<List<Tweet>>() {
#Override
public void success(Result<List<Tweet>> listResult) {
System.out.println("listResult"+listResult.data.size());
System.out.println("listResult"+listResult.data.get(0).user);
System.out.println("listResult"+listResult.data.get(0).user.profileImageUrl);
userInfo.imageurl = listResult.data.get(0).user.profileImageUrl;
}
#Override
public void failure(TwitterException e) {
}
});
Try this code for fetch user profile pic.
public void getTwitterData(final TwitterSession session) {
MyTwitterApiClient tapiclient = new MyTwitterApiClient(session);
tapiclient.getCustomService().show(session.getUserId(),
new Callback<User>() {
#Override
public void success(Result<User> result) {
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
name.setText(result.data.name);
location.setText(result.data.location);
new ImageDownloader(profileImageView)
.execute(result.data.profileImageUrl);
Log.d("Name", name);
Log.d("city", location);
}
public void failure(TwitterException exception) {
// Do something on failure
exception.printStackTrace();
}
});
****************
class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
interface CustomService {
#GET("/1.1/users/show.json")
void show(#Query("user_id") long id, Callback<User> cb);
}
************
class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public ImageDownloader(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

Encountering Facebook SDK Error

I'm creating app that has share button on Facebook and I'm getting an error:
This Page Contains the following errors:
error on line 2 at column 182: Entityref: expecting ';'
Below is a rendering of the page up to the first error.
I don't get this error when I run the app on the Emulator. I'm only getting this kind of error when I run the app on the device.
What is the possible cause of this error?
Your help is highly appreciated. Thanks!
Code below is sample code for Facebook SDK:
public class FacebookShare extends Activity
{
private String APP_ID, APP_SECRET, Name, Link, Description, Picture;
private int fbTYPE;
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
private Activity ctx;
private Bitmap bitmap;
SharedPreferences mPrefs;
public FacebookShare(Activity ctx)
{
APP_ID = "...obfuscated...";
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
this.ctx = ctx;
}
public void shareFB(int TypeOfSharing)
{
APP_ID = "...obfuscated...";
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
this.fbTYPE = TypeOfSharing;
loginToFacebook();
}
public void loginToFacebook()
{
Log.v("debugging", "Entered Login to facebook");
String access_token = mPrefs.getString("access_token", "");
long expires = mPrefs.getLong("access_expires", 0);
if (!access_token.equals(""))
{
facebook.setAccessToken(access_token);
Log.v("Access Token", facebook.getAccessToken());
}
if (expires != 0)
{
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid())
{
Log.v("debugging", "Session is Invalid");
facebook.authorize(ctx, new String[]{
"email","publish_stream"
}, facebook.FORCE_DIALOG_AUTH, new DialogListener()
{
public void onCancel()
{
// Function to handle cancel event
}
public void onComplete(Bundle values)
{
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
if (fbTYPE == 1)
{
postToWall();
}
else if (fbTYPE == 0)
{
postToWall(getBitmap());
}
}
public void onError(DialogError error)
{
Log.v("debugging", error.getMessage());
}
public void onFacebookError(FacebookError fberror)
{
Log.v("debugging", fberror.getMessage());
}
});
Log.v("debugging", "Passed from authorization");
}
else
{
if (fbTYPE == 1)
{
Log.v("debugging", "Entered Post to facebook");
postToWall();
}
else if (fbTYPE == 0)
{
Log.v("debugging", "Entered Post image to facebook");
postToWall(getBitmap());
}
}
}
public void clearCredentials()
{
try
{
facebook.logout(ctx);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void postToWall()
{
// post on user's wall.
Bundle params = new Bundle();
params.putString("description", getDescription());
params.putString("picture", getPicture());
params.putString("name", getName());
params.putString("link", getLink());
facebook.dialog(ctx, "feed", params, new DialogListener()
{
public void onFacebookError(FacebookError e)
{
}
public void onError(DialogError e)
{
}
public void onComplete(Bundle values)
{
Toast.makeText(ctx, "Thanks for sharing JOLENPOP", Toast.LENGTH_SHORT).show();
}
public void onCancel()
{
// Login_Activity.asyncFBLogin fblogin = null;
// fblogin.execute();
}
});
}
public void postToWall(Bitmap bmImage)
{
Log.v("debugging", "entered postToWall(bitmap)");
byte[] data = null;
Bitmap bm = Bitmap.createBitmap(bmImage);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "post");
params.putString("message", getDescription());
params.putByteArray("image", data);
try
{
String response = facebook.request("me");
response = facebook.request("me/photos", params, "POST");
if (response == null || response.equals("") || response.equals("false"))
{
Log.v("response String", response);
return;
}
else if (response.toLowerCase().contains("error"))
{
Log.v("response String", response);
return;
}
}
catch (Exception e)
{
return;
}
Toast.makeText(ctx, "Your photo has been successfuly published!", Toast.LENGTH_LONG).show();
}
public void getProfileInformation()
{
mAsyncRunner.request("me", new RequestListener()
{
public void onComplete(String response, Object state)
{
Log.d("Profile", response);
String json = response;
try
{
JSONObject profile = new JSONObject(json);
// getting name of the user
String name = profile.getString("name");
// getting email of the user
String email = profile.getString("email");
runOnUiThread(new Runnable()
{
public void run()
{
// Toast.makeText(getApplicationContext(), "Name: " + name
// + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
}
catch (JSONException e)
{
e.printStackTrace();
}
}
public void onIOException(IOException e, Object state)
{
}
public void onFileNotFoundException(FileNotFoundException e, Object state)
{
}
public void onMalformedURLException(MalformedURLException e, Object state)
{
}
public void onFacebookError(FacebookError e, Object state)
{
}
});
}
/**
* setters
* */
public void setFacebook(Facebook facebook)
{
this.facebook = facebook;
}
public void setAsyncRunner(AsyncFacebookRunner mAsyncRunner)
{
this.mAsyncRunner = mAsyncRunner;
}
public void setPrefs(SharedPreferences mPrefs)
{
this.mPrefs = mPrefs;
}
public void setName(String val)
{
this.Name = val;
}
public void setLink(String val)
{
this.Link = val;
}
public void setBitmap(Bitmap val)
{
this.bitmap = val;
}
public void setDescription(String val)
{
this.Description = val;
}
public void setPicture(String val)
{
this.Picture = val;
}
/**
* getters
* */
public String getAppID()
{
return this.APP_ID;
}
public String getName()
{
return this.Name;
}
public String getLink()
{
return this.Link;
}
public String getDescription()
{
return this.Description;
}
public String getPicture()
{
return this.Picture;
}
public Bitmap getBitmap()
{
return this.bitmap;
}
}
Here how I used it:
fbShare = new FacebookShare(this);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
then;
Bitmap screenshot = this.glSurfaceView.mRenderer.screenCapture;
fbShare.setName("JOLENPOP");
fbShare.setDescription("I got a score of " + this.glSurfaceView.mRenderer.Score + " in JOLENPOP! Try to beat me!");
fbShare.setBitmap(screenshot);
fbShare.setPrefs(mPrefs);
fbShare.shareFB(0);

Categories

Resources