How to get Facebook information in android - java

I am trying to get information from my facebook in android ,
my code :
loginButton.setReadPermissions(Arrays.asList("email", "user_photos", "public_profile"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Toast.makeText(getApplicationContext(),""+loginResult.getAccessToken(),Toast.LENGTH_SHORT).show();
String accessToken = loginResult.getAccessToken().getToken();
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.i("LoginActivity", response.toString());
// Get facebook data from login
try {
object.get("gender");
object.get("email");
} catch (JSONException e) {
e.printStackTrace();
}
// Bundle bFacebookData = getFacebookData(object);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location"); // ParĂ¡metros que pedimos a facebook
request.setParameters(parameters);
request.executeAsync();
}
But the program does not get into `public void onCompleted(JSONObject object, GraphResponse response) {
the result of this function is :
{Request: accessToken: {AccessToken token:ACCESS_TOKEN_REMOVED permissions:[email, user_photos, public_profile]}, graphPath: me, graphObject: null, httpMethod: GET, parameters: Bundle[{}]}
Is there any solution? or this case related to facebook privacy settings ?

Try the building your login flow manually. This way you don't get stuck on the sdk.
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow

Try replacing
loginResult.getAccessToken()
with
loginResult.getAccessToken().getToken() .
Facebook doesn't allow devs to Log "session.getAccessToken" directly, because it may cause leaks.Can also check this for more information: http://stackoverflow.com/a/29544390/2754871

Related

Can I get Contact Number while login in app using Facebook along with other fields like fbUserName, fbEmail,fbPicture etc.?

I want to fetch the Contact Number using facebook login in my app, is there any way to fetch the contact number ??
I have to show the facebook user details in my app and if the user hasn't added his contact Number then I simply set the ContactNo column as empty where I want to show the basic user details.
I have fetched the user details like this:
//useLoginInformation() method is called from the CallbackManager listener to display details once the user has successfully logged in
private void useLoginInformation(AccessToken accessToken) {
/**
Creating the GraphRequest to fetch user details
1st Param - AccessToken
2nd Param - Callback (which will be invoked once the request is successful)
**/
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
//OnCompleted is invoked once the GraphRequest is successful
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String name = object.getString("name");
String email = object.getString("email");
String id=object.getString("id");
String image_url="https://graph.facebook.com/" + id + "/picture?type=normal";
//Send facebook user details from login activity to FacebookUserDetails activity
Intent intent=new Intent(LoginActivity.this,FacebookUserDetails.class);
intent.putExtra("facebookUsername",name);
intent.putExtra("facebookUserEmail",email);
intent.putExtra("facebookPic",image_url);
startActivity(intent);
progressBar.setVisibility(View.VISIBLE);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// We set parameters to the GraphRequest using a Bundle.
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email,id,picture");
request.setParameters(parameters);
// Initiate the GraphRequest
request.executeAsync();
}

How to send and retrieve data to and from a website?

Ok, guys, so I'm recently developing android app that takes user's ID to login to website and fetch the data to my phone.
Now, there is login page: http://14.140.201.189:8280/opac/myaccount/myAccount.html
I want to send get and post request and retrieve data corresponding to a username and display it in my style in my android app.I don't want to use WebView for loading the whole web page, as the webpage is not reactive so all components are not at place.
Have you got any thoughts or tips/methods/guides/anything how to do that?
You can't use html page as API.
You need an API(php etc.) which will return data in JSON/XML form not in HTML or any other code like JS.
Parse it in your app and do what you want.
You can use simple volley API to make request and gather information from database. Get username and password from edittext. Pass to the function give below. Declare necessary all types of variables. Write simple php script for login. This is very simple and basic code.
/*************** PASS YOUR USERNAME AND PASSWORD TO FUNCTION *******************/
public void userValidationInfo(String username, String password){
String url = "url goes here"; // example.com/login.php
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray dataArray;
JSONObject jsonObject;
String user_id,user_type,
try {
jsonObject = new JSONObject(response);
dataArray = jsonObject.getJSONArray(JSON_ARRAY);
JSONObject obj;
try {
/***************** GET INFORMATION FROM REQUEST HERE ************************/
obj = dataArray.getJSONObject(0);
user_id = obj.getString(TAG_USER_ID);
user_type = obj.getString(TAG_USER_TYPE);
//Toast.makeText(getActivity(), brand_names, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
/***************** SET YOUR USER INFO HERE ****************/
Log.e(TAG, "onResponse: "+response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/****************** SHOW WAITING MESSAGE / ERROR MESSAGE HERE *****************/
Toast.makeText(getContext(), "Taking bit longer ...", Toast.LENGTH_LONG).show();
}
}){
/******************** POST YOUR PARAMETERS HERE *************************/
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
};
queue1.add(stringRequest);
}
For more information check this gist.

Android: Error connecting Android app with Database using php and json

My android app needs to send a string, and based on that, needs to get a response from the database.
I have a php that receives the string from the app, queries the database, and returns the response using echo json_encode($response_array); which works fine on the browser and echoes in a json object format.
However, In the app, I am using Volley. The php array $response_array above sends multiple strings which i need to display in the app textview.
I have set up volley in the gradle dependencies.
However, on running the app from my phone (which is connected on my laptop hotspot), the error i get is "null". This is the sample code from the app.
TextView o,t;
private RequestQueue requestQueue;
private static final String URL = "http://172.25.33.189/fadapp/mirror.php";
private StringRequest request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
o=(TextView)findViewById(R.id.tryOne);
t=(TextView)findViewById(R.id.tryTwo);
requestQueue = Volley.newRequestQueue(this);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonobject = new JSONObject(response);
if (jsonobject.names().get(0).equals("name")) {
o.setText(jsonobject.getString("name"));
if(jsonobject.getString("stat").equals("1")) {
t.setText(R.string.inText);
t.setTextColor(Color.parseColor("#00FF00"));
} else {
t.setText(R.string.outText);
t.setTextColor(Color.parseColor("#FF0000"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, ""+error.getMessage(), Toast.LENGTH_SHORT).show();;
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("speid", "database query string here");
return hashMap;
}
};
requestQueue.add(request);
Have you grant the intenet access to the app with ?
If you are hosting from your laptop you may need to open the port 80, to be sure that the problem isn't yor Volley set-up try to query for example google and print the response that should be a 200 http code

Facebook graph api not sending all data in android

I'm trying to get user_id, name & email from facebook via graph API. but its not sending me the email. I'm using a function like this:
void callGraphApi() {
accessToken = AccessToken.getCurrentAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
tv_response.setText(response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();
}
I'm only getting a response like this:
{"id":"1480750682018443","name":"Ogwemuvwem Ossas","gender":"male"}, error: null}
Any solution??
In your facebook developer dashboard Go to App review in There you can see your data request permission.
If email permission not listed there you have to add it by click start a submission button on the same page.
From facebook Docs:
Note, even if you request the email permission it is not guaranteed
you will get an email address. For example, if someone signed up for
Facebook with a phone number instead of an email address, the email
field may be empty.
You can try this new api. You can pass permissions in ArrayList like this.
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
getUserDetails(loginResult);
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
You can handle LoginResult like this.
// Get Facebook login results
protected void getUserDetails(LoginResult loginResult) {
GraphRequest data_request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json_object, GraphResponse response) {
Log.i("onfbCompleted: ", json_object.toString());
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
data_request.setParameters(permission_param);
data_request.executeAsync();
}
I Hope it's help for you. :)

Android - Parse.com NullPointerException when saving object

In my app I am using Parse.com and Facebook login, and the Facebook login is working and I am now trying to save the email of the user who signed. I am doing this like this:
Request.newMeRequest(ParseFacebookUtils.getSession(), new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
String email = user.getProperty("email").toString();
Log.i(TAG, email);
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.put("email", email);
currentUser.saveInBackground();
}
}
}).executeAsync()
But then when I run I get java.lang.NullPointerException at this line currentUser.put("email", email); But I log email before this and it is not null and I have a email attribute in my User class on parse, so Im not sure why this?
Here the code that comes before to set up the FB Login you should need it and it is working but just in case.
public void onLoginClick(View v) {
progressDialog = ProgressDialog.show(LoginActivity.this, "", "Logging in...", true);
final List<String> permissions = Arrays.asList("public_profile", "email");
// NOTE: for extended permissions, like "user_about_me", your app must be reviewed by the Facebook team
// (https://developers.facebook.com/docs/facebook-login/permissions/)
ParseFacebookUtils.logIn(permissions, this, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
progressDialog.dismiss();
if (user == null) {
Log.d(TAG, "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d(TAG, "User signed up and logged in through Facebook!");
showSelectSchoolActivity();
} else {
Log.d(TAG, "User logged in through Facebook!");
showMainActivity();
}
}
});
Thanks for the help :)
for checking the response you should always use (err==null) as the condition for success. Only after you have recieved the response from the server and err==null then you can check for current user. You should also have a check for when err!=null. Then get the error message from the err.getCode() and check what the error code is.

Categories

Resources