getting email address from facebook SDK For Android - java

I have integrated Facebook login in my application .i get other profile information but can't get the email from the sdk.is it possible?
public void getProfileInformation_fb() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
final String id = profile.getString("id");
Log.i("ID , Name", ""+id+ ""+name);
Log.i("Email", ""+email);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("Face Book", "" + email);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#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 id working for me.
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
String name = object.getString("name");
String birthday = object.getString("birthday");
String gender = object.getString("gender");
String email = object.getString("email");
String picture = object.getString("picture");
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,birthday,first_name,gender,last_name,location,email,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.e("fb", "cancel ");
LoginManager.getInstance().logOut();
}
#Override
public void onError(FacebookException exception) {
// App code
Log.e("fb", "error " + exception);
LoginManager.getInstance().logOut();
}
});

public class FbLogin extends Activity{
CallbackManager callbackManager;
private static final String NAME = "name";
private static final String ID = "id";
private static final String PICTURE = "picture.type(large)";
private static final String EMAIL = "email";
private static final String FIELDS = "fields";
private static final String REQUEST_FIELDS =
TextUtils.join(",", new String[]{ID, NAME, EMAIL, PICTURE});
Bitmap mIcon1 = null;
String imgUrl = "";
String id = "";
String name = "";
String email = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_type);
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
fetchUserInfo();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
btnFb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LoginManager.getInstance().logInWithReadPermissions(Activity_LoginType.this, Arrays.asList("public_profile", "user_friends","email"));
}
});
}
private void fetchUserInfo() {
final String PERMISSION = "publish_actions";
final AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null) {
GraphRequest request = GraphRequest.newMeRequest(
accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
// TODO Auto-generated method stub
parseUserInfo(object);
}
});
Bundle parameters = new Bundle();
parameters.putString(FIELDS, REQUEST_FIELDS);
request.setParameters(parameters);
GraphRequest.executeBatchAsync(request);
LoginManager.getInstance().logInWithPublishPermissions(
this,
Arrays.asList(PERMISSION));
} else {
}
}
private void parseUserInfo(JSONObject me) {
try {
id = me.getString("id");
name = me.getString("name");
email = me.getString("email");
imgUrl = me.getJSONObject("picture").getJSONObject("data").getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
callbackManager.onActivityResult(requestCode, resultCode, data);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and add
FacebookSdk.sdkInitialize(getApplicationContext());
in application class.
and add below code in manifest file
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/fb_id" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />

Related

volley- How do I return the ArrayList from OnResponse Method In Volley

I am using volley to parse the Movie Details from a REST api and I am saving the parsed Data in an Arraylist of objects called detailsMovies. But I can't access the ArrayList outside the onResponse Method. I am new to Android So I dont know what to do exactly.
Any Help is appreciated!
Here's the code:`
public class MovieDetailsActivity extends AppCompatActivity {
TextView movieIdText;
private VolleySingleton volleySingleton;
private RequestQueue mRequestQueue;
private ArrayList<MovieDetails> detailsMovies = new ArrayList<>();
// private String movieTitle ;
// private String movieSummary ;
// private int movieYear;
// private long movieRating;
// private String movieYoutubeId;
// private String movieUrlThumbnail;
// private String movieDownloadLink720p;
// private String movieQuality720p;
// private String moviefileSize720p;
// private String movieDownloadLink1080p;
// private String movieQuality1080p;
// private String moviefileSize1080p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
Intent i = getIntent();
String movieId = i.getExtras().getString("movieId");
volleySingleton = VolleySingleton.getsInstance();
mRequestQueue = VolleySingleton.getmRequestQueue();
parseMovieDetails();
}
public void parseMovieDetails(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getUrl(100), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
MovieDetails movieDetails = new MovieDetails();
if (response == null || response.length() == 0) {
Toast.makeText(getApplicationContext(), "Null Object", Toast.LENGTH_LONG).show();
}
try {
JSONObject movieData = response.getJSONObject("data");
JSONObject movieDetailsObject = movieData.getJSONObject(Keys.EndPointMovieDetails.KEYS_MOVIE);
String movieTitle = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_TITLE_LONG);
long movieRating = movieDetailsObject.getInt(Keys.EndPointMovieDetails.KEYS_RATING);
String movieSynopsis = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_DESCRIPTION);
String moviePosterUrl = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_COVER);
String movieYoutubeId = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEY_YOUTUBE_ID);
movieDetails.setTitle(movieTitle);
movieDetails.setRating(movieRating);
movieDetails.setSummary(movieSynopsis);
movieDetails.setUrlThumbnail(moviePosterUrl);
movieDetails.setYoutube_id(movieYoutubeId);
detailsMovies.add(movieDetails);
JSONArray torrentDownloadLinks = movieDetailsObject.getJSONArray(Keys.EndPointMovieDetails.KEYS_TORRENTS);
for(int i=0;i<torrentDownloadLinks.length();i++) {
JSONObject urlInfo = torrentDownloadLinks.getJSONObject(i);
String urlTorrent = urlInfo.getString("url");
String quality = urlInfo.getString("quality");
String fileSize = urlInfo.getString("size");
movieDetails.setDownloadLink(urlTorrent);
movieDetails.setQuality(quality);
movieDetails.setFileSize(fileSize);
detailsMovies.add(movieDetails);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public String getUrl(int movieId){
return UrlEndPoints.URL_MOVIE_DETAILS+
UrlEndPoints.URl_CHAR_QUESTION+
UrlEndPoints.URL_PARAM_ID+movieId;
}
Define an Interface in your class and implement that.
So Simple trick here is interface with callback.
public class MovieDetailsActivity extends AppCompatActivity {
TextView movieIdText;
private VolleySingleton volleySingleton;
private RequestQueue mRequestQueue;
private ArrayList<MovieDetails> detailsMovies = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
Intent i = getIntent();
String movieId = i.getExtras().getString("movieId");
volleySingleton = VolleySingleton.getsInstance();
mRequestQueue = VolleySingleton.getmRequestQueue();
parseMovieDetails(new CallBack() {
#Override
public void onSuccess(ArrayList<MovieDetails> detailsMovies) {
// Do Stuff
}
#Override
public void onFail(String msg) {
// Do Stuff
}
});
}
public void parseMovieDetails(final CallBack onCallBack){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getUrl(100), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
MovieDetails movieDetails = new MovieDetails();
if (response == null || response.length() == 0) {
Toast.makeText(getApplicationContext(), "Null Object", Toast.LENGTH_LONG).show();
}
try {
JSONObject movieData = response.getJSONObject("data");
JSONObject movieDetailsObject = movieData.getJSONObject(Keys.EndPointMovieDetails.KEYS_MOVIE);
String movieTitle = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_TITLE_LONG);
long movieRating = movieDetailsObject.getInt(Keys.EndPointMovieDetails.KEYS_RATING);
String movieSynopsis = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_DESCRIPTION);
String moviePosterUrl = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_COVER);
String movieYoutubeId = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEY_YOUTUBE_ID);
movieDetails.setTitle(movieTitle);
movieDetails.setRating(movieRating);
movieDetails.setSummary(movieSynopsis);
movieDetails.setUrlThumbnail(moviePosterUrl);
movieDetails.setYoutube_id(movieYoutubeId);
detailsMovies.add(movieDetails);
JSONArray torrentDownloadLinks = movieDetailsObject.getJSONArray(Keys.EndPointMovieDetails.KEYS_TORRENTS);
for(int i=0;i<torrentDownloadLinks.length();i++) {
JSONObject urlInfo = torrentDownloadLinks.getJSONObject(i);
String urlTorrent = urlInfo.getString("url");
String quality = urlInfo.getString("quality");
String fileSize = urlInfo.getString("size");
movieDetails.setDownloadLink(urlTorrent);
movieDetails.setQuality(quality);
movieDetails.setFileSize(fileSize);
detailsMovies.add(movieDetails);
}
onCallBack.success(detailsMovies);
} catch (JSONException e) {
e.printStackTrace();
onCallBack.onFail(e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public String getUrl(int movieId){
return UrlEndPoints.URL_MOVIE_DETAILS+
UrlEndPoints.URl_CHAR_QUESTION+
UrlEndPoints.URL_PARAM_ID+movieId;
}
public interface CallBack {
void onSuccess(ArrayList<MovieDetails> detailsMovies);
void onFail(String msg);
}

Android AsyncTask Error with Facebook SDK

I used Facebook SDK in Android App for Login. I can login with Facebook. I want to insert AccessToken and Email to my database. I solved get Email but I can get email from user with Async. Then I use AsyncTask For Insert data to database. When I used AsyncTask with Facebook SDK, I got exception.
AsyncTask #5 java.lang.RuntimeException: An error occured while executing doInBackground()
And My Code
private JSONParser jParser = new JSONParser();
private String AccessToken;
public String Email;
private LoginAPI api = new LoginAPI();
#Override
protected void onCreate(Bundle savedInstanceState) {
FacebookSdk.sdkInitialize(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (LoginButton)findViewById(R.id.login_button);
if(Profile.getCurrentProfile()!=null){
user = Profile.getCurrentProfile();
new LoginAPI().execute();
}
loginButton.setReadPermissions("public_profile");
loginButton.setReadPermissions("email");
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
user = Profile.getCurrentProfile();
AccessToken = loginResult.getAccessToken().getToken();
GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
Email = user.optString("email");
api.execute();
}
}).executeAsync();
}
#Override
public void onCancel() {
AlertDialog alertMessage = new AlertDialog.Builder(Login.this).create();
alertMessage.setMessage("Iptal");
alertMessage.show();
}
#Override
public void onError(FacebookException exception) {
AlertDialog alertMessage = new AlertDialog.Builder(Login.this).create();
alertMessage.setMessage(exception.toString());
alertMessage.show();
}
});
}
class LoginAPI extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(final String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair() {
#Override
public String getName() {
return "Email";
}
#Override
public String getValue() {
return Email;
}
});
params.add(new NameValuePair() {
#Override
public String getName() {
return "AccessToken";
}
#Override
public String getValue() {
return AccessToken;
}
});
JSONObject json = jParser.makeHttpRequest("WebServiceURL", "POST", params); //Exception Line
try {
if (json != null) {
Sonuc = json.getBoolean("Result");
Mesaj = json.getString("Message");
JSONObject _uye = json.getJSONObject("Data");
if(_uye!=null){
localUser = new User(_uye.getInt("UserID"),
_uye.getString("FacebookID"),
_uye.getString("NameSurname"),
_uye.getString("Email"),
_uye.getString("ProfileImage"));
}
else{
localUser = new User(1,"","","","");
}
}
} catch (JSONException e) {
return e.getMessage().toString();
}
return null;
}
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
if(Sonuc){
Intent welcomeAct = new Intent(getBaseContext(), Welcome.class);
welcomeAct.putExtra("User",localUser);
Login.this.startActivity(welcomeAct);
}
else{
AlertDialog alertMessage = new AlertDialog.Builder(Login.this).create();
alertMessage.setMessage(Mesaj);
alertMessage.show();
}
}
});
}
}
I solved this problem. I wrote AsyncTask code in OnActivityResult event. When Authenticate process finished, I call AsyncTask.

Android Tumblr login issue "JumblrException: Not Authorized"

Why following code giving me such type of exception com.tumblr.jumblr.exceptions.JumblrException: Not Authorized
I saw this question , but i am not able to resolved this issue...plz help me
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "TumblrDemo";
private static final String PREFERENCE_NAME = "tumblr";
public static final String REQUEST_TOKEN_URL = "https://www.tumblr.com/oauth/request_token";
public static final String ACCESS_TOKEN_URL = "https://www.tumblr.com/oauth/access_token";
public static final String AUTH_URL = "https://www.tumblr.com/oauth/authorize";
// public static final String CALLBACK_URL =
// "tumblrdemo://tumblrdemo.com/ok";
public static final String OAUTH_CALLBACK_SCHEME = "oauthflow-tumblr";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://"
+ OAUTH_CALLBACK_HOST;
private TransparentProgressDialog progressDialog;
private Button loginTumblrBtn;
private SharedPreferences preferences;
private CommonsHttpOAuthConsumer consumer;
private CommonsHttpOAuthProvider provider;
private String token, token_secret, oauth_verifier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
consumer = new CommonsHttpOAuthConsumer(Constant.CONSUMER_KEY,
Constant.CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL,
ACCESS_TOKEN_URL, AUTH_URL);
preferences = getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
loginTumblrBtn = (Button) findViewById(R.id.login_tumblr);
Uri uri = this.getIntent().getData();
if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
try {
oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Log.d(TAG, uri.toString());
// provider.retrieveAccessToken(consumer, oauth_verifier);
// token = consumer.getToken();
// token_secret = consumer.getTokenSecret();
token = uri.getQueryParameter("oauth_token");
token_secret = uri.getQueryParameter("oauth_verifier");
consumer.setTokenWithSecret(token, token_secret);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Constant.TOKEN, token);
editor.putString(Constant.TOKEN_SECRET, token_secret);
editor.commit();
getUserDetails();
} catch (Exception e) {
e.printStackTrace();
}
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
loginTumblrBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.login_tumblr) {
if (isTumblrConnected()) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Constant.TOKEN, null);
editor.putString(Constant.TOKEN_SECRET, null);
editor.commit();
loginTumblrBtn.setText(getString(R.string.login_tumblr));
} else {
new AsyncTaskClass().execute();
}
}
}
private boolean isTumblrConnected() {
return preferences.getString(Constant.TOKEN, null) != null;
}
private class AsyncTaskClass extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
String authUrl = provider.retrieveRequestToken(consumer,
CALLBACK_URL);
startActivity(new Intent("android.intent.action.VIEW",
Uri.parse(authUrl)));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new TransparentProgressDialog(MainActivity.this,
R.drawable.loading);
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (isTumblrConnected()) {
token = preferences.getString(Constant.TOKEN, null);
token_secret = preferences.getString(Constant.TOKEN_SECRET, null);
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
getUserDetails();
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
}
private void getUserDetails() {
new Thread(new Runnable() {
#Override
public void run() {
try {
JumblrClient client = new JumblrClient(
Constant.CONSUMER_KEY, Constant.CONSUMER_SECRET);
client.setToken(token, token_secret);
// Write the user's name
User user = client.user();
System.out.println(user.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
Ya finally got solution after too much work, i misunderstood between access token and request token.
Here it is working solution for above issue.Hope it works for you.
public class MainActivity extends Activity implements OnClickListener {
private Button loginTumblrBtn;
private CommonsHttpOAuthConsumer consumer;
private CommonsHttpOAuthProvider provider;
private SharedPreferences preferences;
private Uri uri;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = getSharedPreferences("tumblr", Context.MODE_PRIVATE);
loginTumblrBtn = (Button) findViewById(R.id.login_tumblr);
loginTumblrBtn.setOnClickListener(this);
consumer = new CommonsHttpOAuthConsumer(Constant.CONSUMER_KEY,
Constant.CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider(Constant.REQUEST_TOKEN_URL,
Constant.ACCESS_TOKEN_URL, Constant.AUTH_URL);
uri = this.getIntent().getData();
if (uri != null
&& uri.getScheme().equals(Constant.OAUTH_CALLBACK_SCHEME)) {
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
consumer.setTokenWithSecret(
preferences.getString("requestToken", ""),
preferences.getString("requestSecret", ""));
provider.setOAuth10a(true);
provider.retrieveAccessToken(consumer,
uri.getQueryParameter(OAuth.OAUTH_VERIFIER));
consumer.setTokenWithSecret(consumer.getToken(),
consumer.getTokenSecret());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("token", consumer.getToken());
editor.putString("token_secret",
consumer.getTokenSecret());
editor.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_tumblr:
if (preferences.getString("token", null) != null) {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
SharedPreferences.Editor editor = preferences.edit();
editor.putString("token", null);
editor.putString("token_secret", null);
editor.commit();
} else {
progressDialog = ProgressDialog.show(this, "Loading",
"Please Wait...");
new Thread(new Runnable() {
#Override
public void run() {
try {
String authUrl = provider.retrieveRequestToken(
consumer, Constant.CALLBACK_URL);
SharedPreferences.Editor editor = preferences
.edit();
editor.putString("requestToken",
consumer.getToken());
editor.putString("requestSecret",
consumer.getTokenSecret());
editor.commit();
startActivity(new Intent(
"android.intent.action.VIEW", Uri
.parse(authUrl)));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
break;
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (preferences.getString("token", null) != null) {
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
and put this intent-filter code inside manifest>application>activity (where callback is done)
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="callback"
android:scheme="oauthflow-tumblr" />
</intent-filter>
Image sharing on TUMBLR
public void shareImageOnTumblr(final File imgFile, final String caption,
final Handler handler) {
new Thread(new Runnable() {
#Override
public void run() {
try {
PhotoPost photoPost = client.newPost(client.user()
.getBlogs().get(0).getName(), PhotoPost.class);
if (!caption.isEmpty())
photoPost.setCaption(caption);
photoPost.setPhoto(new Photo(imgFile));
photoPost.save();
Bundle bundle = new Bundle();
Message message = new Message();
bundle.putInt("method",
UploadActivity.SHARED_PHOTO_SUCCESSFULLY);
message.setData(bundle);
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
Video sharing on TUMBLR
public void shareVideoOnTumblr(final File videoFile, final String caption,
final Handler handler) {
new Thread(new Runnable() {
#Override
public void run() {
try {
VideoPost videoPost = client.newPost(client.user()
.getBlogs().get(0).getName(), VideoPost.class);
if (!caption.toString().isEmpty())
videoPost.setCaption(caption.toString());
videoPost.setData(videoFile);
videoPost.save();
Bundle bundle = new Bundle();
Message message = new Message();
bundle.putInt("method",
UploadActivity.SHARED_VIDEO_SUCCESSFULLY);
message.setData(bundle);
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}

Android : getParams() called two times dont know why?

Here getParams() method called two times and added two times data at my server. I have also noticed that my logs print twice in logcat. It occurs when I check two checkbox of from contact picker list view to send data to server.
Here is my json data :
{
"send_data":[{
"gcm_reg_id":
"APA91bFPfAvEL_UJRHiOSohkekTh7M9qj1Kj307kFqmWh4VS8Re1aeejWSKXQnJb7q3OIjykCccbbI-0pn14DwvyjjL4ynQTHNR-m1p3vxLKy7ujGXv2MpIe0fhT2vcTJE0SW0uTjkD9iPJz0pw3sMuGojA4yxw0zg", "receiver_id":
"170"
},{
"gcm_reg_id":
"APA91bFheDJdBe3LwBk7MNchLitnKkECgVARxopr0HnFemo1vfW3Q0Mt1m6GXxccoq-wjUwoV-yXOVvcw9JwXcOZwAPyal9ZqMoA-U3fLNdaMa7pu8f-GYSyMsv16XKkgzPpzOPPKs8pc9C-7K1MhZXKgRf67DiXTSRY67swIOGP1XmJyoa3l1s", "receiver_id":
"166"
}]
}
Here is my code :
public class ContacsPicker extends ListActivity implements OnClickListener{
ProgressDialog dialog;
ConnectionDetector cd;
String phoneNumber ;
String conatct_num;
ArrayList<integer> status;
ImageView iv;
ArrayList<PhoneContactInfo> list;
JSONArray contact_noArray;
ArrayList<String> contact_database;
ArrayList<String> contact_userid;
ArrayList<String> image;
ListView list_view;
CustomListViewAdapter adpter;
String user_id,message,level,time,image_name,receiver_id,regId,mail;
Bitmap send_image;
Store_pref obj_Store_pref;
RegisterUser obj_RegisterUser;
ProgressDialog Dialog;
EditText edt_search;
ImageView iv_search;
RelativeLayout relative_search;
Boolean is_serch=false;
Matrix matrix = new Matrix();
send_data obj_Send_data;
String sender_regid,ba1, data;
Context mContext;
public Uri targetUri;
JSONObject obj;
Button button1_send;
ArrayList<String> checkedValue;
ArrayList<send_data> id_arrArrayList;
List<com.waycreon.picture_puzzle.model.RegisterUser.Registure_user> Registure_user;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_picker);
mContext=this;
edt_search =(EditText) findViewById(R.id.edt_search);
iv_search=(ImageView)findViewById(R.id.iv_search);
button1_send=(Button) findViewById(R.id.button1_send);
button1_send.setOnClickListener(this);
relative_search=(RelativeLayout)findViewById(R.id.relative_search);
set_invisible_relative_search();
obj_Store_pref=new Store_pref(ContacsPicker.this);
regId=obj_Store_pref.get_GCMreg_id();
mail=obj_Store_pref.get_mail_id();
Log.i("GCM reg id in contact picker class", "++++"+regId);
Log.i("mail id in contact picker class", "++++"+mail);
iv_search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(!is_serch)
{
is_serch=true;
search_click();
}
else
{
is_serch=false;
close_click();
}
}
});
list_view=getListView();
message = getIntent().getStringExtra("message");
level = getIntent().getStringExtra("level");
time = getIntent().getStringExtra("time");
targetUri= (Uri) getIntent().getParcelableExtra("targetUri");
Log.i("get message", message);
Log.i("get level", level);
Log.i("get time", time);
Log.i("get send_image", send_image+"=");
Log.i("target uri", ""+targetUri);
try {
int orientation = getOrientation(this, targetUri);
Log.i("orientation on create", "++"+orientation);
matrix.postRotate(orientation);
send_image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), targetUri);
send_image= get_Resized_Bitmap(send_image,600,800);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
send_image.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
ba1=Base64.encodeToString(ba,1);
Log.i("base 64", ba1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
status=new ArrayList<integer>();
contact_database=new ArrayList<String>();
contact_userid=new ArrayList<String>();
image=new ArrayList<String>();
cd=new ConnectionDetector(this);
obj_Store_pref= new Store_pref(this);
dialog = new ProgressDialog(ContacsPicker.this);
dialog.setCancelable(false);
dialog.setMessage("Please Wait...");
dialog.setCancelable(false);
list = getAllPhoneContacts();
get_registered_no();
edt_search = (EditText) findViewById(R.id.edt_search);
edt_search .addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = edt_search .getText().toString()
.toLowerCase(Locale.getDefault());
adpter.filter(text);
list_view.setAdapter(adpter);
adpter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
});
id_arrArrayList=new ArrayList<send_data>();
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
CheckBox cb = (CheckBox) arg1.findViewById(R.id.checkBox1_check);
cb.performClick();
receiver_id =arg1.getTag().toString();
// String gcm_reg_id=Registure_user.get(arg2).gcm_regid;
// Log.i("gcm_reg id on list click", gcm_reg_id);
Log.i("in if", receiver_id+"++++");
if(!arg1.getTag().equals("0"))
{
String[] separated = arg1.getTag().toString().split(" ");
String receiver_id =separated[0];
String gcm_reg_id=separated[1];
if (cb.isChecked()) {
Log.i("in if check box", receiver_id+"++++");
obj_Send_data = new send_data();
obj_Send_data.setReceiver_id(receiver_id);
obj_Send_data.setGcm_reg_id(gcm_reg_id);
id_arrArrayList.add(obj_Send_data);
Log.i("arraylist in if lisze", "++"+ id_arrArrayList.size());
} else if (!cb.isChecked()) {
id_arrArrayList.remove(obj_Send_data);
Log.i("arraylist in else lisze", "++"+ id_arrArrayList.size());
}
}
// if(!arg1.getTag().equals("0"))
// {
// receiver_id =arg1.getTag().toString();
// show_alert_invitation("Invitation","Are you sure you want to send puzzle to your friend ?");
//
// Log.i("in if ", receiver_id+"++++");
//
// Get_receiver_reg_id();
//
//
// }
// else
// {
// show_alert_unregister_user("Notification",getString(R.string.unregister_user_message));
// }
}
});![enter image description here][1]
}
public void onClick(View v) {
if(v==button1_send)
{
// Log.i("array list", receiver_id);
// Send_data();
show_alert_invitation("Invitation","Are you sure you want to send task to your friend ?");
}
}
private void get_registered_no() {
// TODO Auto-generated method stub
if (cd.isConnectingToInternet())
{
dialog.show();
RequestQueue queue = Volley.newRequestQueue(ContacsPicker.this);
String url="http://karmamobichamps.com/Restaurant_app/puzzle/puzzle_app_services.php?do=get_registered_no";
Log.i("url", url+"+++++++++++");
StringRequest myReq = new StringRequest(Method.GET,url,
Get_Event_list_ReqSuccessListener(),
Get_Event_list_ReqErrorListener());
queue.add(myReq);
}
else
{
cd.show_alert("no connection", "Please check with your internet Connection");
}
}
private ErrorListener Get_Event_list_ReqErrorListener() {
return new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Log.i("Volly err", error.getLocalizedMessage()+"++++");
error.printStackTrace();
}
};
}
private Listener<String> Get_Event_list_ReqSuccessListener() {
return new Response.Listener<String>() {
public void onResponse(String response) {
dialog.dismiss();
Log.i("registration data", response+"");
try {
JSONObject jo=new JSONObject(response);
if(jo.getString("ResponseCode").equals("1"))
{
try
{
Gson gson = new GsonBuilder().create();
obj_RegisterUser= gson.fromJson(response, RegisterUser.class);
Registure_user=obj_RegisterUser.Registure_user;
Log.i("user size", Registure_user.size()+"--");
}
catch (Exception e) {
e.printStackTrace();
}
}
} catch (JSONException e1) {
e1.printStackTrace();
}
for(int i=0;i<list.size();i++)
{
image.add("0");
}
for(int i=0;i<list.size();i++)
{
for(int j=0;j<Registure_user.size();j++)
{
String[] separated = Registure_user.get(j).mobile_no.split(" ");
String mobilenono = separated[separated.length-1];
String country_code = separated[0];
// String mobilenono=separated[1];
String mobile_no=country_code+mobilenono;
if(list.get(i).getcontactNumber().equals(mobilenono) || list.get(i).getcontactNumber().equals(mobile_no) ||(list.get(i).getcontactNumber().equals(Registure_user.get(j).mobile_no)) ||list.get(i).getcontactNumber().equals("0"+mobilenono)) {
image.set(i,Registure_user.get(j).id.toString()+" "+Registure_user.get(j).gcm_regid.toString());
Log.i("match", list.get(i).getcontactNumber()+"==");
}
}
}
adpter=new CustomListViewAdapter(ContacsPicker.this, list,Registure_user,image);
list_view.setAdapter(adpter);
}
};
}
private void Send_data() {
data=Write_json();
Log.i("in send data method", data);
Dialog=new ProgressDialog(this);
Dialog.setTitle("sending..");
Dialog.setCancelable(false);
Dialog.show();
RequestQueue queue = Volley.newRequestQueue(ContacsPicker.this);
String url = null;
url = "http://karmamobichamps.com/Restaurant_app/puzzle/send_multi_data.php" ;
StringRequest myReq = new StringRequest(Method.POST,url,
send_data_ReqSuccessListener(),
send_data_ReqErrorListener())
{
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
// HashMap<String, String> params = new HashMap<String, String>();
// {
**params.put("data", data);
params.put("image", ba1);
params.put("sender_id", obj_Store_pref.get_user_id());
params.put("message", message);
params.put("level",level);
params.put("time", time);
params.put("status", "1");
Log.i("data in params", data);
Log.i("sender_id in params", obj_Store_pref.get_user_id());
Log.i("level",level);
Log.i("message in params", message);
Log.i("time in params", time);
Log.i("status in params", "1");**
return params;
};
};
queue.add(myReq);
}
private ErrorListener send_data_ReqErrorListener() {
return new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Dialog.dismiss();
Log.i("Volly err", error.getLocalizedMessage()+"++++");
error.printStackTrace();
}
};
}
private Listener<String> send_data_ReqSuccessListener() {
return new Response.Listener<String>() {
public void onResponse(String response) {
Dialog.dismiss();
Log.i("registration data", response+"");
try {
JSONObject jo=new JSONObject(response);
if (jo.getString("ResponseCode").equals("1")) {
finish();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
}
private void send_to_web() {
// TODO Auto-generated method stub
final String URL = "http://karmamobichamps.com/Restaurant_app/puzzle/send_multi_data.php";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("data", data);
// params.put("image", ba1);
// params.put("sender_id", obj_Store_pref.get_user_id());
// params.put("message", message);
// params.put("level",level);
// params.put("time", time);
// params.put("status", "1");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
ApplicationController.getInstance().addToRequestQueue(req);
}
private void show_alert_invitation(String title,String msg) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(title)
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// new ImageUpload().execute();
Send_data();
// send_to_web();
Log.i("bitmap width in contact picker", ""+send_image.getWidth());
Log.i("bitmap height in contact picker", ""+send_image.getHeight());
dialog.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void show_alert_unregister_user(String title,String msg) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(title)
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Swapatask");
String sAux = "\nHeyy use this amazing application i m using too...\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.waycreon.picture_puzzle \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
private void set_visible_relative_search() {
relative_search.setVisibility(RelativeLayout.VISIBLE);
}
private void set_invisible_relative_search() {
relative_search.setVisibility(RelativeLayout.GONE);
}
private void search_click() {
iv_search.setImageResource(R.drawable.close);
set_visible_relative_search();
edt_search.setFocusable(true);
}
private void close_click() {
iv_search.setImageResource(R.drawable.search_button);
set_invisible_relative_search();
edt_search.setText("");
}
/*============================get local to phone all contect===================================*/
public ArrayList<PhoneContactInfo> getAllPhoneContacts() {
Log.d("START","Getting all Contacts");
ArrayList<PhoneContactInfo> arrContacts = new ArrayList<PhoneContactInfo>();
PhoneContactInfo phoneContactInfo=null;
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone._ID}, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
String contactNumber= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
if (contactNumber.length()>0)
{
phoneContactInfo = new PhoneContactInfo();
phoneContactInfo.setphoneContactID(phoneContactID);
phoneContactInfo.setcontactName(contactName);
phoneContactInfo.setcontactNumber(contactNumber.replaceAll("\\s+",""));
arrContacts.add(phoneContactInfo);
}
phoneContactInfo = null;
cursor.moveToNext();
}
cursor.close();
cursor = null;
Log.d("END","Got all Contacts");
return arrContacts;
}
private void Send_push() {
// Dialog.show();
RequestQueue queue = Volley.newRequestQueue(ContacsPicker.this);
String url = null;
try {
url = "http://karmamobichamps.com/Restaurant_app/puzzle/puzzle_app_services.php?do=Receive_Push_notification&gcm_regid="
+sender_regid+"&message="+URLEncoder.encode("You Have Received Swapatask Request", "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("rgister url", url);
StringRequest myReq = new StringRequest(Method.GET,url,
Registration_ReqSuccessListener(),
Registration_ReqErrorListener());
queue.add(myReq);
}
private ErrorListener Registration_ReqErrorListener() {
return new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
// Dialog.dismiss();
Log.i("Volly err", error.getLocalizedMessage()+"++++");
error.printStackTrace();
}
};
}
private Listener<String> Registration_ReqSuccessListener() {
return new Response.Listener<String>() {
public void onResponse(String response) {
// Dialog.dismiss();
Log.i("registration data", response+"");
//
}
};
}
public Bitmap get_Resized_Bitmap(Bitmap bmp, int newHeight, int newWidth) {
int width = bmp.getWidth();
int height = bmp.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
// Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// matrix.postRotate(90);
// "RECREATE" THE NEW BITMAP
Bitmap newBitmap = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
return newBitmap ;
}
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
private String Write_json() {
// TODO Auto-generated method stub
Log.i("arraylist lisze in next button", "++"+ id_arrArrayList.size());
obj = new JSONObject();
JSONArray list1 = new JSONArray();
try {
for (int i = 0; i < id_arrArrayList.size(); i++) {
String gcm_reg_id=Registure_user.get(i).gcm_regid;
JSONObject jsonObject=new JSONObject();
jsonObject.put("receiver_id", id_arrArrayList.get(i).getReceiver_id());
jsonObject.put("gcm_reg_id", id_arrArrayList.get(i).getGcm_reg_id());
Log.i("gcm_reg_id", gcm_reg_id);
list1.put(jsonObject);
}
obj.put("send_data", list1);
}catch (Exception e) {
e.printStackTrace();
}
return obj.toString();
}
// public class ImageUpload extends AsyncTask<String, String,String>
// {
// Bitmap bitmap;
// public ImageUpload()
// {
// // TODO Auto-generated constructor stub
//// this.bitmap=bitmap;
// }
// #Override
// protected void onPreExecute()
// {
// dialog.show();
// super.onPreExecute();
//
// }
// #Override
// protected String doInBackground(String... params)
// {
// // TODO Auto-generated method stub
// try
// {
//// ByteArrayOutputStream bao = new ByteArrayOutputStream();
//// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao);
//// byte [] ba = bao.toByteArray();
//// String ba1=Base64.encodeToString(ba,1);
// Log.i("base 64", ba1);
// ArrayList<NameValuePair> nameValuePairs = new enter code hereArrayList<NameValuePair>();
// HttpClient httpclient = new DefaultHttpClient();
// HttpPost httppost = new HttpPost("http://karmamobichamps.com/Restaurant_app/puzzle/send_multi_data.php");
// Log.i("url", ""+httppost);
// nameValuePairs.add(new BasicNameValuePair("data", data));
// nameValuePairs.add(new BasicNameValuePair("image", ba1));
// nameValuePairs.add(new BasicNameValuePair("sende
To identify the root of this issue you'll need to debug and see what's the path in which getParams is called.
You could either breakpoint within getParams block or print the stack trace to log like so:
Throwable throwable = new IllegalArgumentException("Something");
throwable.printStackTrace();
Add this before adding request to request queue
request.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

How to get user details after successful Login through Facebook

I tried this: when isSessionValid getDetails directly else facebook.authorize and then getDetails in onActivityResult
public class MainActivity extends Activity {
Facebook facebook = new Facebook("xxxxxxxxxxxxxxxx");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = getPreferences(MODE_PRIVATE);
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(this, new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}else{
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
}
This works fine when I have facebook app installed on my system. But If not installed i get a Web View to enter facebook credentials and in logcat shows login-success, but none of the getDetails block is called.
Here in initFacebook() function through you can login and perform you functionality, here i am fetching user's friends information.
private void initFacebook()
{
try
{
if (APP_ID == null)
{
Util.showAlert(this,"Warning","Facebook Applicaton ID must be "+ "specified before running this example: see Example.java");
}
mFacebook = new Facebook();
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mFacebook.authorize(FacebookList.this, APP_ID, new String[] {"email", "read_stream", "user_hometown", "user_location","friends_about_me", "friends_hometown", "friends_location","user_relationships", "friends_relationship_details","friends_birthday", "friends_education_history","friends_website" }, new DialogListener()
{
public void onComplete(Bundle values)
{
getHTTPConnection();
}
public void onFacebookError(FacebookError error)
{
Log.i("public void onFacebookError(FacebookError error)....","....");
}
public void onError(DialogError e)
{
Log.i("public void onError(DialogError e)....", "....");
CustomConfirmOkDialog dialog = new CustomConfirmOkDialog(FacebookList.this, R.style.CustomDialogTheme, Utils.FACEBOOK_CONNECTION_ERROR);
dialog.show();
}
public void onCancel()
{
Log.i("public void onCancel()....", "....");
}
});
SessionStore.restore(mFacebook, this);
SessionEvents.addAuthListener(new SampleAuthListener());
SessionEvents.addLogoutListener(new SampleLogoutListener());
}
catch (Exception e)
{
e.printStackTrace();
}
}
Here in getHTTPConnection(), proceeding for connection and sending fields, that we require about user's friends as here we can see that passing fields are fields=id,first_name,last_name,location,picture of friends. here you can change this fields according to application's requirements.
private void getHTTPConnection()
{
try
{
mAccessToken = mFacebook.getAccessToken();
HttpClient httpclient = new DefaultHttpClient();
String result = null;
HttpGet httpget = new HttpGet("https://graph.facebook.com/me/friends?access_token="+ mAccessToken + "&fields=id,first_name,last_name,location,picture");
HttpResponse response;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
{
result = EntityUtils.toString(entity);
parseJSON(result);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Now after successfully connecting with facebook , we are getting JSON data and further to parse it .
private void parseJSON(String data1) throws Exception,NullPointerException, JSONException
{
try
{
JSONObject jObj = new JSONObject(data1);
JSONArray jObjArr = jObj.optJSONArray("data");
int lon = jObjArr.length();
for (int i = 0; i < lon; i++)
{
JSONObject tmp = jObjArr.optJSONObject(i);
String temp_image = tmp.getString("picture"); String temp_fname = tmp.getString("first_name");
String temp_lname = tmp.getString("last_name");
String temp_loc = null;
JSONObject loc = tmp.getJSONObject("location");
temp_loc = loc.getString("name");
}
}
catch (Exception e)
{
Log.i("Exception1 is Here>> ", e.toString());
e.printStackTrace();
}
}
It is assumed that you have already added a facebook jar in to your application and for proceeding this code you can call initFacebook() in to onCreate() of your activity

Categories