I'm using Retrofit 2.1.0. The return in XML is quite different. The JSON was placed inside the XML. I have searching about this for several hours but still not getting any idea how to retrieve the JSON value.
XML :
<string xmlns="http://www.something.com/">
[{"ReturnOK":"OK","Fullname":"Micheal","Userid":"4","strAppID":"9A380FFEACC444E8BE1E616F72A573C0","Phoneno":"1234567890"}]
</string>
Retrofit Client:
public static Retrofit getManager() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(Constants.HTTP.BASE_URL)
.client(new OkHttpClient())
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();
}
return retrofit;
}
Login Interface:
public interface LoginService {
#GET(Constants.LOGIN.LOGIN_URL)
Call<XMLString> doLogin(#Query(Constants.LOGIN.strAppID) String strAppID,
#Query(Constants.LOGIN.uname) String uname,
#Query(Constants.LOGIN.upassword) String upassword);
}
XMLString :
#Root(name="string", strict = false)
public class XMLString {
private String reponse;
public String getReponse() {
return reponse;
}
public void setReponse(String reponse) {
this.reponse = reponse;
}
}
Method :
private void loginProcess(String username, String password){
LoginService endPoints = mManager.getManager().create(LoginService.class);
Call<XMLString> call = endPoints.doLogin("1", username, password);
call.enqueue(new Callback<XMLString>() {
#Override
public void onResponse(Call<XMLString> call, Response<XMLString> response) {
if (response.isSuccessful()) {
XMLString xmlString = null;
try {
xmlString = call.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
XMLString FromResponse = response.body();
Toast.makeText(getActivity(), FromResponse.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<XMLString> call, Throwable t) {
Utils.T(getActivity(), t.getMessage().toString());
}
});
}
Error :
FATAL EXCEPTION: main
Process: app.test.com.junn, PID: 12501
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1128)
at app.test.com.junn.controller.RestManager.getManager(RestManager.java:29)
at app.test.com.junn.ui.fragment.LoginDialogFragment.loginProcess(LoginDialogFragment.java:100)
at app.test.com.junn.ui.fragment.LoginDialogFragment.onClick(LoginDialogFragment.java:83)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Any help is really appreciated.
Related
I am new to retrofit (I was using volley before), before this I was doing fine with retrofit until this error comes :-
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected int but was Boolean at line 8 column 37 path
$.response.data.book_service_id
I tried with every solution provided in this site but could not help myself since I am new to retrofit.
I think it's because of the JSON parsing error. I don't know how to handle it.
This may be a duplicate question but please help.
Below is my code:
Request and fetching data:
private void makeBookingRequest(String position) {
final CustomProgressDialog dialog = new CustomProgressDialog();
dialog.show(getSupportFragmentManager(),"tag");
SharedPreferences preferences = getSharedPreferences("MYSharedPref",MODE_PRIVATE);
String sessionkey = preferences.getString("sessionkey",null);
System.out.println(sessionkey);
String serviceId = position;
System.out.println(position);
APIEndPoints endPoints = Url.getInstance().create(APIEndPoints.class);
Call<Book> call = endPoints.makeBookingRequest(serviceId,sessionkey);
call.enqueue(new Callback<Book>() {
#Override
public void onResponse(Call<Book> call, retrofit2.Response<Book> response) {
dialog.dismiss();
if (!response.isSuccessful()) {
Toast.makeText(HomeActivity.this, "server is not responding", Toast.LENGTH_SHORT).show();
}
else if(response.body() != null){
Book bookData = response.body();
String message = bookData.response.message;
Toast.makeText(HomeActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Book> call, Throwable t) {
dialog.dismiss();
Toast.makeText(HomeActivity.this, "Error" + t.getLocalizedMessage(),
Toast.LENGTH_SHORT).show();
System.out.println(t);
}
});
}
Model Class:
package com.medpal.medpal_client.Models;
import com.google.gson.annotations.SerializedName;
public class Book {
#SerializedName("response")
public ResponseEntity response;
public class ResponseEntity{
#SerializedName("data")
public DataEntity data;
#SerializedName("secondary_message")
public String secondary_message;
#SerializedName("message")
public String message;
#SerializedName("code")
public int code;
}
public class DataEntity {
#SerializedName("book_service_id")
public int book_service_id;
}
}
APIENDPOINTS
#FormUrlEncoded
#Headers({"apikey: testapikey", "Content-Type:application/x-www-form-urlencoded" })
#POST("service/accept?")
Call<Book> makeBookingRequest(
#Field("service_id") String ServiceId,
#Field("session_key") String sessionKey);
URL class
public class Url {
public static final String base_url = "http://www.medpal.net/api/v1/";
public static final String serviceUrl = "http://www.medpal.net/api/v1/services?";
public static Retrofit retrofit;
public static Retrofit getInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(base_url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Finallyy Response from server:
{
"response": {
"error": [],
"code": 200,
"message": "Service booked",
"secondary_message": "Service booked successfully",
"data": {
"book_service_id": 35
}
}
}
To detect the problem exactly, You need to use an interceptor to log the server response, to log the server responses you can use OkHttp3 here is an example of it.
private OkHttpClient provideOkhttpClient() {
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(15000, TimeUnit.MILLISECONDS);
client.writeTimeout(70000, TimeUnit.MILLISECONDS);
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client.addInterceptor(interceptor);
return client.build();
}
And add this to your Retrofit.Builder
.client(provideOkhttpClient())
And these are for Gradle
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.5.0'
If you do this you will see everything you sent and got from the server at your Logcat.
By This code, I am not able to get the error response as if I use same email id twice then I am getting the error response in postman but in my application, I am not getting the error response
So can you please help me to get out of this
My Interface
public interface SignupAPI {
#FormUrlEncoded
#POST("users")
Call<ResponseBody> createUser(
#Field("email") String email,
#Field("password") String password,
#Field("role") String role
);
}
My Java Code
public class SignupClient {
private static final String BASE_URL = "http://74.207.233.160/api/v1/";
private static SignupClient mInstance;
private Retrofit retrofit;
private SignupClient(){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
public static synchronized SignupClient getmInstance(){
if (mInstance == null){
mInstance = new SignupClient();
}
return mInstance;
}
public SignupAPI getApi(){
return retrofit.create(SignupAPI.class);
}
}
My Activity
Call<ResponseBody> call = SignupClient.getmInstance().getApi().createUser(email, password,role);
call.enqueue(new Callback<ResponseBody>()
{
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
{
if (response.isSuccessful()){
progressBar.setVisibility(View.GONE);
Toast.makeText(SignupActivity.this, "Account Sucessfully Created", Toast.LENGTH_SHORT).show();
}else {
try {
progressBar.setVisibility(View.GONE);
JSONObject jsonError = new
JSONObject(response.errorBody().string());
Toast.makeText(SignupActivity.this, jsonError.getString("errors"),Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
progressBar.setVisibility(View.GONE);
e.printStackTrace();
} catch (IOException e) {
progressBar.setVisibility(View.GONE);
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(SignupActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
make error pojo class..
public class Errors{
#SerializedName("email")
private List<String> email;
public void setEmail(List<String> email){
this.email = email;
}
public List<String> getEmail(){
return email;
}
}
make changes into response body class..
public class ResponseBody {
#SerializedName("errors")
private Errors errors;
public void setErrors(Errors errors){
this.errors = errors;
}
public Errors getErrors(){
return errors;
}
}
then after used into api response like
Errors errors=response.body().getErrors();
i am facing a problem regarding posting data in an array in android using retrofit 2. i have to post the data of nearly 14 fields in my profile setting activity ...
Like this ...
name="basics[first_name] , name="basics[last_name]" , name="basics[phone_number]"
i have to send data in this format. i am not understanding how to do it need help.i am not understanding how to make Call of the api in the interface because i have to put data in an array.
Currently i am doing it like this but i know its not right...
#FormUrlEncoded
#POST("profile_setting/basic_setting")
Call<ResponseBody> UpdateBasics(
#Query("user_id") int user_id ,
#Field("nickname") String nickname ,
#Field("first_name") String first_name ,
#Field("last_name") String last_name ,
#Field("phone_number") String phone_number ,
#Field("fax") String fax
);
Make a class
public class Basic {
public final int user_id;
public final String nickname;
....
public Basic(int user_id, ...) {
}
}
Then pass list of objects of this class to this interface
public interface MyService {
#POST("/basic")
Response void sendData(#Body List<Basic> basic);
}
Or you can do the same with JSONObject. Just make a list of jsonobjects
JSONObject paramObject = new JSONObject();
paramObject.put(value_one, "field_one"));
paramObject.put(value_second, "field_second"));
put the objects in a list
list.add(paramObject);
then pass to the retrofit
public interface MyService {
#POST("/basic")
Response void sendJsonObjectData(#Body List<JSONObject> basic);
}
Do this way to send Json Object as request parameters using Retrofit 2
#Headers("Content-Type: application/json")
#POST("profile_setting/basic_setting")
Call<ResponseBody> UpdateBasics(#Body String body);
This is how you would use the above method to send json object
try {
JSONObject paramObject = new JSONObject();
paramObject.put(value_one, "field_one"));
paramObject.put(value_second, "field_second"));
Call<ResponseBody> userCall = apiInterface.UpdateBasics(paramObject.toString());
userCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//handle your result here
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
//handle failure
}
});
} catch (JSONException e) {
e.printStackTrace();
}
You can follow this was. (posting how i've done that)
#POST("Users.json")
Call<UploadData> uploadToken(#Body UploadData uploadData);
UploadData.class
public class UploadData {
private String DeviceToken, DeviceIMEI;
public UploadData(String deviceToken, String deviceIMEI) {
DeviceToken = deviceToken;
DeviceIMEI = deviceIMEI;
}
public String getDeviceToken() {
return DeviceToken;
}
public String getDeviceIMEI() {
return DeviceIMEI;
}
}
Then in your Activity
private void uploadToken() {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
UploadData uploadToken = new UploadData(deviceToken, imei);
final Call<UploadData> callUpload = apiInterface.uploadToken(uploadToken);
callUpload.enqueue(new Callback<UploadData>() {
#Override
public void onResponse(Call<UploadData> call, Response<UploadData> response) {
if (response.isSuccessful()) {
Toasty.success(Main.this, "Token Uploaded !! ", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure (Call < UploadData > call, Throwable t){
call.cancel();
Toasty.error(Main.this, "Error: " + t.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}
});
}
This question already has an answer here:
How to fix Expected BEGIN_OBJECT in Retrofit?
(1 answer)
Closed 4 years ago.
In my application i want use Retrofit for get some data from server.
I write below codes but when run application and call api show me below error :
E/socketLogResponse: Err : com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
Please see my above codes and help me
API response from server :
{
"status": "ok",
"time": 0.014972925186157227
}
ApiService interface :
#POST("api/log")
Call<SocketPingResponse> getSocketPingLog(#Header("jwt") String jwt, #Body SocketPingBodySendData socketPingBodySendData);
SocketPingResponse class :
public class SocketPingResponse {
#SerializedName("status")
#Expose
private String status;
#SerializedName("time")
#Expose
private Double time;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Double getTime() {
return time;
}
public void setTime(Double time) {
this.time = time;
}
}
SocketPingBodySendData class :
public class SocketPingBodySendData {
#SerializedName("auction_id")
#Expose
int auction_id;
#SerializedName("data")
#Expose
List<SocketPingEntity> data;
public int getAuction_id() {
return auction_id;
}
public void setAuction_id(int auction_id) {
this.auction_id = auction_id;
}
public List<SocketPingEntity> getData() {
return data;
}
public void setData(List<SocketPingEntity> data) {
this.data = data;
}
}
Api call codes in activity :
pingEntityList.addAll(socketPingDatabase.socketPingDao().getSocketPingEntityList());
SocketPingBodySendData pingBodySendData = new SocketPingBodySendData();
pingBodySendData.setAuction_id(auctionID);
pingBodySendData.setData(pingEntityList);
Toast.makeText(context, ""+pingEntityList.size(), Toast.LENGTH_SHORT).show();
Call<SocketPingResponse> pingResponseCall = apis.getSocketPingLog(jwtToken, pingBodySendData);
pingResponseCall.enqueue(new Callback<SocketPingResponse>() {
#Override
public void onResponse(Call<SocketPingResponse> call, Response<SocketPingResponse> response) {
if (response.body() != null) {
Toast.makeText(context, response.body().getStatus(), Toast.LENGTH_SHORT).show();
if (response.body().getStatus().equals("ok")) {
pingEntityList.clear();
socketPingDatabase.socketPingDao().deleteAll();
}
}
}
#Override
public void onFailure(Call<SocketPingResponse> call, Throwable t) {
Log.e("socketLogResponse", "Err : " + t.toString());
}
});
ApiClient class :
public class ApiClient {
private static final String BASE_URL = Constants.SERVER;
private static Retrofit retrofit = null;
private static Context context;
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.interceptors().add(interceptor);
client.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("X-Client-Version", Constants.getAppVersionName()).build();
return chain.proceed(request);
}
});
client.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("uuid", Constants.getUUID(Constants.currentActivity)).build();
return chain.proceed(request);
}
});
client.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("agent", Constants.getAgent()).build();
return chain.proceed(request);
}
});
OkHttpClient client2 = client
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client2)
.build();
}
return retrofit;
}
}
How can i fix this issue?
I think the problem returns string when no data is returned. Backend can usually do such errors. this error had happened to me before. you should check the response json when no data is available
Retrofit is typesafe library. It means that it waits only particular (predefined) types of objects. If server sends something else - it crashes with error. This is your case. Just check raw server response and you'll see what's wrong.
Try changing your API call
from
#POST("api/log")
Call<SocketPingResponse> getSocketPingLog(#Header("jwt") String jwt, #Body SocketPingBodySendData socketPingBodySendData);
to
#POST("api/log")
Call<String> getSocketPingLog(#Header("jwt") String jwt, #Body SocketPingBodySendData socketPingBodySendData);
pingEntityList.addAll(socketPingDatabase.socketPingDao().getSocketPingEntityList());
SocketPingBodySendData pingBodySendData = new SocketPingBodySendData();
pingBodySendData.setAuction_id(auctionID);
pingBodySendData.setData(pingEntityList);
Toast.makeText(context, ""+pingEntityList.size(), Toast.LENGTH_SHORT).show();
Call<String> pingResponseCall = apis.getSocketPingLog(jwtToken, pingBodySendData);
pingResponseCall.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.body() != null) {
//Convert here your string response to Other POJO format
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("socketLogResponse", "Err : " + t.toString());
}
});
I want to use Twitter Rest Api without using twitter4j. Fabric is fine but i couldn't find a method like gettingUserFollowers(). I don't know why it has. Anyway I want to call my user followers ids using this service. https://dev.twitter.com/rest/reference/get/followers/ids
I have looked a tutorial from fabric website(http://docs.fabric.io/android/twitter/access-rest-api.html#tweets). There is a class for getting a custom service. But i couldn't understan how i can call it sending parameter.I changed it as following
import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterSession;
import retrofit.http.GET;
import retrofit.http.Query;
public class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
interface CustomService {
#GET("/1.1/followers/ids.json")
void show(#Query("user_id") long id);
}
}
I think when i send an id ,service brings followers ids.
MyTwitterApiClient aa = new MyTwitterApiClient(session);
aa.getCustomService().show(userId);
But app is stopped.What is my wrong ?
LogCat is
5897-15897/com.tumymedia.tumer.lylafortwitter E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tumymedia.tumer.lylafortwitter, PID: 15897
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=140, result=-1, data=Intent { (has extras) }} to activity {com.tumymedia.tumer.lylafortwitter/com.tumymedia.tumer.lylafortwitter.MainActivity}: java.lang.IllegalArgumentException: CustomService.show: Must have either a return type or Callback as last argument.
at android.app.ActivityThread.deliverResults(ActivityThread.java:4058)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4101)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1497)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: java.lang.IllegalArgumentException: CustomService.show: Must have either a return type or Callback as last argument.
at retrofit.RestMethodInfo.methodError(RestMethodInfo.java:123)
at retrofit.RestMethodInfo.parseResponseType(RestMethodInfo.java:285)
at retrofit.RestMethodInfo.<init>(RestMethodInfo.java:113)
at retrofit.RestAdapter.getMethodInfo(RestAdapter.java:213)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:236)
at java.lang.reflect.Proxy.invoke(Proxy.java:397)
at com.tumymedia.tumer.lylafortwitter.$Proxy16.show(Unknown Source)
at com.tumymedia.tumer.lylafortwitter.MainActivity$1.success(MainActivity.java:55)
at com.twitter.sdk.android.core.identity.TwitterAuthClient$CallbackWrapper.success(TwitterAuthClient.java:230)
at com.twitter.sdk.android.core.Callback.success(Callback.java:40)
at com.twitter.sdk.android.core.identity.AuthHandler.handleOnActivityResult(AuthHandler.java:91)
at com.twitter.sdk.android.core.identity.TwitterAuthClient.onActivityResult(TwitterAuthClient.java:161)
at com.twitter.sdk.android.core.identity.TwitterLoginButton.onActivityResult(TwitterLoginButton.java:131)
at com.tumymedia.tumer.lylafortwitter.MainActivity.onActivityResult(MainActivity.java:96)
at android.app.Activity.dispatchActivityResult(Activity.java:6543)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4054)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4101)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1497)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Actually Fabric uses retrofit to make REST Api calls and as mentioned
in Fabric documentation, for getting ids of followers we need to pass
user_id as parameter and retrieve list in response.
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);
}
Now in MainActivity we will authenticate the user and then by getting
the session we will retrieve the list of all followers corresponding
to a userid.
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);
}
}
In Retrofit 2.0,
Interface ->
public interface FollowersService {
#GET("/1.1/followers/list.json")
Call<ResponseBody> list(#Query("screen_name") String userId);
}
Call to method ->
FollowersService followersService = followersTwitterApiClient.getFollowersService();
Call<ResponseBody> call = followersService.list(userId);
call.enqueue(followerCallback);
Custom Api client ->
public class FollowersTwitterApiClient extends TwitterApiClient {
public FollowersTwitterApiClient(TwitterSession twitterSession){
super(twitterSession);
}
public FollowersService getFollowersService(){
return getService(FollowersService.class);
}
}
You need to authenticate to Twitter in order to be able to call the API and get results. I don't see that happening in this code. (Maybe you are doing it outside this code?)
Details on Twitter authentication at https://dev.twitter.com/oauth