I faced with the following problem: I need to get FB id and email after authorization. Here's my code:
#Override
public void onSuccess(LoginResult loginResult) {
final String[] email = new String[1];
final String[] id = new String[1];
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
email[0] = object.getString(FB_EMAIL_PERMISSION);
id[0] = object.getString(FB_ID_PERMISSION);
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email");
request.setParameters(parameters);
request.executeAsync();
Bundle bundle = new Bundle();
bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
bundle.putString(EXTRA_EMAIL, email[0]);
bundle.putString(EXTRA_ID, id[0]);
mPresenter.saveUserData(bundle);
}
But when I run my app, I don't get this fields. I checked in debugger and part
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
email[0] = object.getString(FB_EMAIL_PERMISSION);
id[0] = object.getString(FB_ID_PERMISSION);
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
isn't called at all. I don't understand why it happens. So, what's the matter and how can I solve it?
UPD
Probably, maybe it would help, here's whole fb logic:
mCallbackManager = CallbackManager.Factory.create();
mFacebookButton.setReadPermissions(Collections.singletonList(FB_EMAIL_PERMISSION));
mFacebookButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
final String[] email = new String[1];
final String[] id = new String[1];
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
email[0] = object.getString(FB_EMAIL_PERMISSION);
id[0] = object.getString(FB_ID_PERMISSION);
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email");
request.setParameters(parameters);
request.executeAsync();
Bundle bundle = new Bundle();
bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
bundle.putString(EXTRA_EMAIL, email[0]);
bundle.putString(EXTRA_ID, id[0]);
mPresenter.saveUserData(bundle);
}
UPD 2
I have one think about this problem, that request is asynchronous and when I put a breakpoint on line mPresenter.saveUserData(bundle); information isn't loaded yet, but how can I make it synchronous? Or maybe I am wrong?
UPD 3
I changed my request in the following way, but it still doesn't work and breakpoints are skipped in this part.
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
if (response.getJSONObject() != null) {
JSONObject data = response.getJSONObject();
if (data.has(FB_EMAIL_PERMISSION)) {
email[0] = response.getJSONObject().getString(FB_EMAIL_PERMISSION);
}
if (data.has(FB_ID_PERMISSION)) {
id[0] = response.getJSONObject().getString(FB_ID_PERMISSION);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
And here's the values of permissions:
private static final String FB_EMAIL_PERMISSION = "email";
private static final String FB_ID_PERMISSION = "id";
did you add permission to your facebook login button
fbLoginButton.setPermissions(Arrays.asList("public_profile,email,user_birthday"));
this is how i am using it
i am not sure of the value of FB_EMAIL_PERMISSION FB_ID_PERMISSION
final GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
String id = "", user_email = "", name = "";
Log.d("EHREIUIU", String.valueOf(object));
if (response.getJSONObject() != null) {
JSONObject data = response.getJSONObject();
if (data.has("id"))
id = data.getString("id");
if (data.has("email"))
user_email = data.getString("email");
}
getOneSignalToken();
socialLogin(user_email, name, null, id, "facebook");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Related
I am trying to get a string response from post request. Here, I am sending a post request. where I am sending this data. I have a Model of BillReceipt. Which I pass on the request body.
public void UserTransactionReceiptReport(TransactionTypeListener<String> listener, BillReceipt billReceiptReport){
final UserSettings userSettings = getMUserSettings();
final StringBuilder url = new StringBuilder(AppConfigsManager.getTouchServerUrl());
url.append("/api/User/UserData");
JSONObject params = new JSONObject();
try{
params.put("iB_CUST_ID",billReceiptReport.getiB_CUST_ID());
params.put("transactioN_DATE",billReceiptReport.getTransactioN_DATE());
params.put("transactioN_DATE_NM",billReceiptReport.getTransactioN_DATE_NM());
}catch (Exception e){
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url.toString(), params
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Gson mapper = new GsonBuilder().create();
try{
Type type = new TypeToken<APIResponse<String>>() {
}.getType();
APIResponse<String> responseObject = mapper.fromJson(response.toString(), type);
if(responseObject.Status == APIStatus.OK){
listener.didFetch(responseObject.Result, responseObject.Message);
}else {
listener.didError(responseObject.Message);
}
}catch (Exception e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.didError(error.getMessage());
}
})
{
#Override
public Map<String, String> getHeaders() {
return getAuthorizationTokenHashMap(getMUserSettings());
}
};
addVolleyRequest(request);
}
and I call this api from recycler download button.Here , I globally declared the manager where i write the api code. and also declare a the model name.
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manager.UserTransactionReceiptReport(listener,billReceiptReport);
}
});
}
private final TransactionTypeListener<String> listener = new TransactionTypeListener<String>() {
#Override
public void didFetch(String response, String message) {
str = response;
}
#Override
public void didError(String message) {
}
};
any one help me to solve the problem i am facing.
Try this code
<code>
JSONObject jsonObject = new JSONObject(response);
System.out.println("jsonWallet----" + jsonObject);
int status_ = jsonObject.getInt("status");
if(status_ == 1){
String incomeWalletBal = jsonObject.getString("income_wallet");
String refundWalletBal = jsonObject.getString("refund_wallet");
}else {
}
</code>
I am trying to trigger a piece of code on button click using View.setOnClickListener.
My code includes two OkHttp requests going to Google Places API which returns JSON files. I parse them and then place a call on a phone number extracted using the APIs.
Now, when I click on the button, the code is executed only partially. It executes the first request and returns the Place ID of the place I need. But, the phone call is not placed.
On using Logcat, we can see that the place ID is extracted, but only when I click the button once again, the complete code is executed and I see double output, i.e. the phone number extracted is logged twice.
Please help me in clearing this execution flow problem and making sure that the single click is enough to request the 2 APIs and then place the call also.
Below is the code for the onCreate method of my Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPerms(this);
simpleLocation = new SimpleLocation(this, true);
tv1 = findViewById(R.id.tv1);
tv2 = findViewById(R.id.tv2);
bt = findViewById(R.id.bt);
String apikey = getString(R.string.apikey);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
simpleLocation.beginUpdates();
final double latitude = simpleLocation.getLatitude();
final double longitude = simpleLocation.getLongitude();
tv1.setText(String.valueOf(latitude));
tv2.setText(String.valueOf(longitude));
ExecutorService ex = Executors.newFixedThreadPool(1);
final FutureTask<String> result1 = (FutureTask<String>) ex.submit(new Callable<String>() {
public String call(){
OkHttpClient client = new OkHttpClient();
Request request1 =new Request.Builder()
.url(URLBuilder1(latitude, longitude, apikey))
.get()
.build();
try{
Response response = client.newCall(request1).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
pid = jsonObject.getJSONArray("results").getJSONObject(0).getString("place_id");
} catch (IOException | JSONException e) {
e.printStackTrace();
Log.d("JSON 1", e.getLocalizedMessage());
}
return pid;
}
});
try {
PID = result1.get();
Log.d("TAG", PID);
}
catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
final FutureTask<String> result2 = (FutureTask<String>) ex.submit(new Callable<String>() {
#Override
public String call() {
try {
OkHttpClient client = new OkHttpClient();
Request request2 = new Request.Builder()
.url(URLBuilder2(apikey, pid))
.get()
.build();
Response response = client.newCall(request2).execute();
JSONObject jsonObject = new JSONObject(Objects.requireNonNull(response.body()).string());
phone = jsonObject.getJSONObject("result").getString("international_phone_number");
phone = phone.replace(" ", "");
Log.d("TAG", phone);
}
catch (IOException | JSONException e){
e.printStackTrace();
}
return phone;
}
});
try {
phone = result2.get();
Log.d("TAG", phone);
}
catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
Log.d("TAG", phone);
Intent i = new Intent(Intent.ACTION_CALL);
i.setData(Uri.parse("tel:" + phone));
}
});
}
p.s. I am a student developer who began Java for Android only 2 months ago, so any tips on code optimization or any other tips regarding bettering the code will be highly appreciated.
You should nest the two requests.
So first you should run the first request. then right after you assign the pid variable you should start the second request. Then right after you assign the phone variable you should start the phone call intent. Its simple as that. Second request should be inside the first request. Phone Call Intent should be inside the second request. I hope you'd understand.
In your code what happens is, before you receive the pid the second request is also executed. Its better if you could use Volley Library by Google
Example Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
context = this;
checkPerms(this);
simpleLocation = new SimpleLocation(this, true);
tv1 = findViewById(R.id.tv1);
tv2 = findViewById(R.id.tv2);
bt = findViewById(R.id.bt);
String apikey = getString(R.string.apikey);
bt.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
simpleLocation.beginUpdates();
final double latitude = simpleLocation.getLatitude();
final double longitude = simpleLocation.getLongitude();
tv1.setText(String.valueOf(latitude));
tv2.setText(String.valueOf(longitude));
ExecutorService ex = Executors.newFixedThreadPool(1);
final FutureTask < String > result1 = (FutureTask < String > ) ex.submit(new Callable < String > () {
public String call() {
OkHttpClient client = new OkHttpClient();
Request request1 = new Request.Builder().url(URLBuilder1(latitude, longitude, apikey)).get().build();
try {
Response response = client.newCall(request1).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
pid = jsonObject.getJSONArray("results").getJSONObject(0).getString("place_id");
final FutureTask < String > result2 = (FutureTask < String > ) ex.submit(new Callable < String > () {#Override
public String call() {
try {
OkHttpClient client = new OkHttpClient();
Request request2 = new Request.Builder().url(URLBuilder2(apikey, pid)).get().build();
Response response = client.newCall(request2).execute();
JSONObject jsonObject = new JSONObject(Objects.requireNonNull(response.body()).string());
phone = jsonObject.getJSONObject("result").getString("international_phone_number");
phone = phone.replace(" ", "");
Log.d("TAG", phone);
Intent i = new Intent(Intent.ACTION_CALL);
i.setData(Uri.parse("tel:" + phone));
}
catch(IOException | JSONException e) {
e.printStackTrace();
}
return phone;
}
});
} catch(IOException | JSONException e) {
e.printStackTrace();
Log.d("JSON 1", e.getLocalizedMessage());
}
return pid;
}
});
}
});
}
Alternatevely you can use OkHttp in async manner. For example:
ExecutorService ex = Executors.newFixedThreadPool(1);
ex.submit(new Runnable() {
public void run() {
OkHttpClient client = new OkHttpClient();
Request request1 = new Request.Builder()
.url(URLBuilder1(latitude, longitude, apikey))
.get()
.build();
client.newCall(request1).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
//logging
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
pid = jsonObject.getJSONArray("results").getJSONObject(0).getString("place_id");
Log.d("TAG", pid);
} catch (IOException | JSONException e) {
e.printStackTrace();
Log.d("JSON 1", e.getLocalizedMessage());
}
Request request2 = new Request.Builder()
.url(URLBuilder2(apikey, pid))
.get()
.build();
OkHttpClient client = new OkHttpClient();
client.newCall(request2).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
try {
JSONObject jsonObject = new JSONObject(Objects.requireNonNull(response.body()).string());
phone = jsonObject.getJSONObject("result").getString("international_phone_number");
phone = phone.replace(" ", "");
Log.d("TAG", phone);
Intent i = new Intent(Intent.ACTION_CALL);
i.setData(Uri.parse("tel:" + phone));
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
});
Note: I did not run the code above, just giving an example.
Instead of client.newCall(request1).execute(); which runs synchronically, you can use:
client.newCall(request1).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
//if request fails then this method gets executed
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
//response is coming as method parameter "response"
}
});
which is completely async.
I am trying to set text in TextView userEmail, after calling FaceBook request for getting Email.
public TextView userEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
//user_profile_name
userName = (TextView)findViewById(R.id.user_profile_name);
userEmail = (TextView)findViewById(R.id.user_profile_short_bio);
userbday = (TextView) findViewById(R.id.user_bday);
getMyFBProfileRequest();
}
public void getMyFBProfileRequest() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
Log.i("Response",response.toString());
Toast.makeText(MyProfileActivity.this,object.getString("email") ,
Toast.LENGTH_SHORT).show();
// Application code
String email = object.getString("email");
String birthday = object.getString("birthday");
userEmail.setText(email);
} catch (JSONException e) {
e.printStackTrace();
Log.i("Error","");
//profileView.showToast("Error");
}
}
});
// GraphRequest.GraphJSONObjectCallback objectCallback = new JSONObjectCallback();
// GraphRequest request = GraphRequest.newMeRequest(accessToken, objectCallback);
Bundle parameters = new Bundle();
parameters.putString("fields", "email,name,first_name,last_name,gender");
request.setParameters(parameters);
request.executeAsync();
}
And I get a fine response, which I see in toast.
But nothing change in textView. UI does not update… why? I do not know what to do. I used Broadcast Receiver. lost a lot of time. It does not work… Help me, please, anybody.
FB answer has field "birthday"! But my request did't get birthday. It is correct for get it: params.putString("fields", "birthday")
params.putString("fields","email,birthday,picture.type(large)");
2) To surround with try catch all operation with JSONObject:
try {
userModel.setEmail( data.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setEmail("");
}
try {
userModel.setBday(data.getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setBday("");
}
and set "" in cath if result null;
So, now my request looks like:
Bundle params = new Bundle();
params.putString("fields", "email,birthday,picture.type(large)");
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/", params, HttpMethod.GET,
new GraphRequest.Callback() {
public ImageLoader imageLoader;
public ImageView mImageView;
public UserInfo userModel;
#Override
public void onCompleted( GraphResponse response) {
saveDataInSingletone(response);
profileView.setInfoToView();
}
private void saveDataInSingletone(GraphResponse response) {
JSONObject data = response.getJSONObject();
userModel = UserInfo.getInstance();
String lastName, firstName;
String profilePicUrl;
if (data.has("picture")) {
try {
profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
// getFacebookProfilePicture(profilePicUrl);
// imageView = (ImageView) findViewById(R.id.pic);
// imageView.setScaleType(ImageView.ScaleType.FIT_XY);
userModel.setAvatar(profilePicUrl);
//mImageView.setImageBitmap(profilePic);
// userModel.setAvatar(profilePic);
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
userModel.setEmail( data.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setEmail("");
}
try {
userModel.setBday(data.getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setBday("");
}}).executeAsync();
My graphrequest seems to work fine, I have no issue retrieving the User who logs ins Name nor do I have any problem getting their ID. I am trying to store their profile picture for use within my app (By downloading it as a bitmap) but cant seem to succesfully download it. Could someone tell me what I am doing wrong?
//Run the first time we log into Facebook
//connects everything here
private void firstTimeFBlogin() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.i("joe", "Heyyyyo");
try {
String userName = response.getJSONObject().getString("name");
String userID = response.getJSONObject().getString("id");
//String hi2 = response.getJSONObject().getString("first_name");
//String hi3 = response.getJSONObject().getString("gender");
final JSONObject mPicture = object.getJSONObject("picture");
final JSONObject mPictureData = mPicture.getJSONObject("data");
final String mImageUrl = mPictureData.getString("url");
Log.i("joe", "User's Facebook Name: " + userName);
Log.i("joe", ParseUser.getCurrentUser().getUsername());
Log.i("joe", mImageUrl);
Log.i("joe", userID);
ParseUser.getCurrentUser().put("name", userName);
ParseUser.getCurrentUser().put("iUrl", mImageUrl);
ParseUser.getCurrentUser().put("fbID", userID);
ParseUser.getCurrentUser().saveInBackground();
profilePictureRetriever(userID);
} catch (JSONException e) {
Log.i("joe", "Couldn't Succesfully retrieve the stuff...");
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,picture");
request.setParameters(parameters);
request.executeAsync();
}
public void profilePictureRetriever(String id) {
Log.i("joe", "Profile Picture Checker");
//Bitmap bitmap = getFacebookProfilePicture(id);
//this is here for test purposes
//tried just maually putting the url in..
Bitmap bm = DownloadImageBitmap("https://graph.facebook.com/849993771766163/picture?type=square");
}
public static Bitmap DownloadImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("IMAGE", "Error getting bitmap", e);
}
return bm;
}
}
Is there another/better way to be doing this?
Thanks so much!
I have done something like this:
First you need to call GraphRequest API for getting all the details of user in which API also gives URL of current Profile Picture.
Bundle params = new Bundle();
params.putString("fields", "id,email,gender,cover,picture.type(large)");
new GraphRequest(token, "me", params, HttpMethod.GET,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
if (response != null) {
try {
JSONObject data = response.getJSONObject();
if (data.has("picture")) {
String profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
Bitmap profilePic = getFacebookProfilePicture(profilePicUrl);
// set profilePic bitmap to imageview
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
You can use this method which returns current Profile picture of User from URL which we get from above GraphRequest API.
public static Bitmap getFacebookProfilePicture(String url){
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bitmap;
}
I hope it helps!
Update
Pass required parameter in bundle, as id,name,email,gender, birthday,picture is passed in below code.
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday,picture");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.e(TAG, "Cancel");
}
#Override
public void onError(FacebookException exception) {
Log.e(TAG, "Error");
Log.e(TAG, exception.toString());
}
});
Old Answer
get it by calling
graph.facebook.com/<FB UserId>/picture?type=large
following code is put after login success.
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
Log.d("info",object.toString()+"");
String id = object.getString("id");
String profilePic ="http://graph.facebook.com/"+id+"/picture";
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,age_range,gender,locale,timezone,updated_time,verified,email");
request.setParameters(parameters);
request.executeAsync();
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