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.
Related
I'm entangled in a query in which I need to send an image array to server.
I googled it but I couldn't find any relevant data, so can any one tell me how can I achieve it?
Early reply is appreciable .
My code is
private void imageUpload(final ArrayList imagePath) {
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(
Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d( "Response", response );
try {
JSONObject jObj = new JSONObject( response );
String message = jObj.getString( "message" );
System.out.println( "Done" );
Toast.makeText( getApplicationContext(), message, Toast.LENGTH_LONG ).show();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText( getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG ).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
for (int i = 0; i<imagePath.size();i++){
String ab = imagePath.get( i ).toString();
System.out.println("Images is find path "+ab);
smr.addFile(""+i,imagePath.get(i).toString());
}
MyApplication.getInstance().addToRequestQueue(smr);
}
Thanks
I am using https://github.com/esafirm/android-image-picker this library to get images list
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.upload_btn:
openImagesList();
break;
}
}
public void openImagesList() {
ImagePicker.create(this) // Activity or Fragment
.start();
}
#Override
public void onActivityResult(int requestCode, final int resultCode, Intent data) {
if (ImagePicker.shouldHandle(requestCode, resultCode, data)) {
// Get a list of picked images
List<Image> images = ImagePicker.getImages(data);
List<File> imgFile = new ArrayList<>();
for (Image imge : images) {
imgFile.add(new File(imge.getPath()));
}
for (File f : imgFile) {
if (f.exists()) {
Log.i(TAG, "exist");
}
}
uploadToSever(imgFile);
}
super.onActivityResult(requestCode, resultCode, data);
}
Use https://github.com/amitshekhariitbhu/Fast-Android-Networking to POST request
public void uploadToSever(List<File> imgList) {
AndroidNetworking.upload("your sever url")
.addMultipartFileList("image[]", imgList)
.addMultipartParameter("key", "value")
.setPriority(Priority.HIGH)
.build()
.setUploadProgressListener(new UploadProgressListener() {
#Override
public void onProgress(long bytesUploaded, long totalBytes) {
// do anything with progress
}
})
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
// do anything with response
}
#Override
public void onError(ANError error) {
// handle error
}
});
}
I am sending a request to a server using Volley in a JobService. My question is, since the service runs on the main thread, should I create a seperate thread inside the service and call my Volley request there, or simple call the volley request? Here is some of my code.
public class JobService extends android.app.job.JobService {
static int count = 0;
#Override
public boolean onStartJob(final JobParameters jobParameters) {
Log.d("Job Service", "onStartJob " + count);
final SharedPreferences prefs = getSharedPreferences(LOGIN_PREFS, MODE_PRIVATE);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Job Service", "onResponse");
try {
writeFileToCache(response);
jobFinished(jobParameters, true);
} catch (Exception e) {
e.printStackTrace();
jobFinished(jobParameters, true);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley error job", error.toString());
jobFinished(jobParameters, true);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("regno", prefs.getString(REG_NO, ""));
params.put("bdate", prefs.getString(DATE_OF_BIRTH, ""));
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(12000, 0, 0f));
queue.add(request);
return true;
}
private void writeFileToCache(String response) throws IOException {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
return;
}
File file = new File(getExternalCacheDir() + CACHE_FILE);
FileOutputStream fout = new FileOutputStream(file);
Log.d("Writing to cache job", response);
fout.write(response.getBytes());
fout.close();
}
#Override
public boolean onStopJob(JobParameters jobParameters) {
Log.d("Job Service", "onStopJob");
return false;
}
I've this code:
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(GithubService.SERVICE_ENDPOINT).build();
GithubService service = retrofit.create(GithubService.class);
service.getAirport()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<Airport>>() {
List<Airport> airps = new ArrayList<Airport>();
#Override
public void onCompleted() {
for(final Airport air : airps) {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm mRealm) {
AirportR airport = mRealm.createObject(AirportR.class);
airport.setId(air.getId());
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Log.wtf("ok", "ok");
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.e("ok", "non vaaa");
}
});
}
}
#Override
public void onError(Throwable e) {
e.printStackTrace();
}
#Override
public void onNext(List<Airport> airports) {
airps = airports;
}
});
}
});
and I need to put a download percentage because airports are so much..and so I want to put in a textview the percentage of the download (and I don't know how to do it in onNext() method) and the percentage of the realm adding in the airport...
It's possible to do?
Thanks
I used this function to show download progress, combine by rxjava and okhttp, hope it helps.
private void initOkHttpClient() {
mOkHttpClient = new OkHttpClient();
mRequest = new Request.Builder().url(URL_JSON).build();
}
private void rxPublishProgress() {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
mRequest = new Request.Builder().url(URL_IMAGE).build();
Observable.create(new Observable.OnSubscribe<String>() {
#Override
public void call(Subscriber<? super String> subscriber) {
try {
InputStream inputStream;
Response response = mOkHttpClient.newCall(mRequest).execute();
if (response.isSuccessful()) {
inputStream = response.body().byteStream();
long len = response.body().contentLength();
String progress = "0";
subscriber.onNext(progress);
byte[] data = new byte[1024];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1) {
total += count;
progress = String.valueOf(total * 100 / len);
subscriber.onNext(progress);
}
inputStream.close();
subscriber.onCompleted();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).subscribeOn(Schedulers.newThread()).subscribe(new Subscriber<String>() {
#Override
public void onCompleted() {
LogUtils.d("onCompleted");
mProgressDialog.dismiss();
}
#Override
public void onError(Throwable e) {
LogUtils.d(e.toString());
mProgressDialog.dismiss();
}
#Override
public void onNext(final String progress) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.setProgress(Integer.parseInt(progress));
}
});
}
});
}
I have written a Class to perform network operation using Volley and have callback passed in the method.
Code is as below
public class MyNetUtil {
public interface MyNetCallbacks {
public void onResponse(String response);
public void onErrorResponse(VolleyError error);
public void onErrorResponseData(ErrorResponseData error);
public void onResponseCode(int code);
}
private void request(int method, String url, final Map<String, String> headMap, final byte[] bodyContent, final MyNetCallbacks myNetCallbacks) {
Log.d(TAG, " Getting url : " + url);
final StringRequest strReq = new StringRequest(method, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
if (myNetCallbacks != null) {
myNetCallbacks.onResponse(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
int statusCode = -1;
if (error != null && error.networkResponse != null) {
statusCode = error.networkResponse.statusCode;
}
VolleyLog.d(TAG, "Error: " + error.getMessage());
ErrorResponseData errorResponseData = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
String errorResponse = new String(response.data);
if (statusCode == -1) {
statusCode = response.statusCode;
}
errorResponseData = ErrorResponseData.getResponseData(errorResponse);
}
if (myNetCallbacks != null) {
myNetCallbacks.onErrorResponse(error);
if (statusCode != -1) {
myNetCallbacks.onResponseCode(statusCode);
}
myNetCallbacks.onErrorResponseData(errorResponseData);
}
Log.d(TAG, " inside onErrorResponse " + statusCode);
}
}) {
// protected Map<String, String> getParams() {
// return stringMap;
// }
#Override
public byte[] getBody() throws AuthFailureError {
Log.d(TAG, "Body : " + new String(bodyContent));
return bodyContent;
}
#Override
public String getBodyContentType() {
return CONTENT_TYPE_APPLICATION_JSON;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
Log.d(TAG, " inside parseNetworkResponse, responseCode : " + response.statusCode);
if (myNetCallbacks != null) {
myNetCallbacks.onResponseCode(response.statusCode);
}
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", CONTENT_TYPE_APPLICATION_JSON);
headers.put("Accept", "application/api.ryder.v2");
headers.put("Authentication-Token", getAuthToken());
if (headMap != null) {
for (Map.Entry<String, String> entry : headMap.entrySet()) {
headers.put(entry.getKey() + "", entry.getValue() + "");
}
}
Log.d(TAG, " Header ");
Util.displayMap(TAG, headers);
return headers;
}
};
BaseApplication.getInstance().addToRequestQueue(strReq, "");
}
}
In my Activity I use it as
private MyNetUtil mMyNetUtil = new MyNetUtil();
mMyNetUtil.request(Request.Method.DELETE, url, headMap, bodyContent, new MyNetUtil.MyNetCallbacks() {
#Override
public void onResponse(String response) {
showProgress(false);
}
#Override
public void onErrorResponse(VolleyError error) {
showProgress(false);
}
#Override
public void onErrorResponseData(ErrorResponseData error) {
showProgress(false);
}
#Override
public void onResponseCode(int code) {
showProgress(false);
setInfoMessage(R.string.alert__lbl__your_account_was_deleted_successfully);
Log.d(TAG, "onResponseCode " + code);
if (code == MyNetUtil.CODE_204) {
Log.d(TAG, "FINISH --------- " + code);
DataUser.deleteUserFromPref();
Toast.makeText(mContext, R.string.alert__lbl__your_account_was_deleted_successfully, Toast.LENGTH_SHORT).show();
ActivityProfile.this.finish();
return;
} else {
setErrorMessage(R.string.server_error);
}
}
});
Control is going till ActivityProfile.this.finish();
but the activity is not getting finished
I tried onBackPressed also that also not working.
But when I call ActivityProfile.this.finish() out side callback it getting finished
what could be the issue, please help me
You should only call finish from the UI thread.
parseNetworkResponse runs on non UI thread.
That was the issue.
Use this:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
MainActivity.this.finish();
}
});
See also this post.
Or check this.
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);
}
}