I am new to Android and Java Development and I am trying to figure out a way to retrieve the current users Profile posts and save it in a Text File on my smart phone for further processes.
I am able to retrieve User Name, Email, Gender, Age Range and Birthday. so far everything works fine and the text file is being written when Facebook is connected with my Application.
Below class is how its coded in order to retrieve the mentioned Data, If anyone does know of how to retrieve posts as well via this method, please suggest?
Thanks!
package com.example.daunte_pc.anique;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
public class SocialActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "SocialActivity";
LoginButton loginButton;
CallbackManager callbackManager;
ProgressDialog progressDialog;
URL profile_pic;
String id;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_social);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open,R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setNavigationItemSelectedListener(this);
FacebookSdk.sdkInitialize(getApplicationContext());
loginButton = (LoginButton)findViewById(R.id.login_button);
callbackManager = CallbackManager.Factory.create();
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_status","user_posts"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
progressDialog = new ProgressDialog(SocialActivity.this);
progressDialog.setMessage("Please Wait! Anique_Profile's being processed!");
progressDialog.show();
String accessToken = loginResult.getAccessToken().getToken();
Log.i("accessToken",accessToken);
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.i("Test",response.toString());
Bundle bFacebookData = getFacebookData(object);
String name = bFacebookData.getString( "name");
String email = bFacebookData.getString( "email");
String gender = bFacebookData.getString( "gender");
String profilepic = bFacebookData.getString( "profile_pic");
String age_range = bFacebookData.getString( "age_range");
String birthday = bFacebookData.getString( "birthday");
String posts = bFacebookData.getString( "posts{message}");
Intent in = new Intent(SocialActivity.this, Facebook_Profile.class);
in.putExtra("name", name);
in.putExtra("email", email);
in.putExtra("gender", gender);
in.putExtra("Image", profilepic);
in.putExtra("posts", posts);
startActivity(in);
try{
File root = new File(Environment.getExternalStorageDirectory(),"Anique Text Files");
if (! root.exists()){
root.mkdir();
}
File filePath = new File(root, "myFile.txt");
FileWriter writer = new FileWriter(filePath);
writer.append("Name : "+ name+"\n");
writer.append("\n");
writer.append("Email : "+ email+"\n");
writer.append("\n");
writer.append("Gender : "+ gender+"\n");
writer.append("\n");
writer.append("Age : "+ age_range+"\n");
writer.append("\n");
writer.append("Birthday : "+ birthday+"\n");
writer.append("\n");
writer.append("Posts : "+ posts+"\n");
writer.append("\n");
writer.flush();
writer.close();
Toast.makeText(SocialActivity.this,"Success!! Logged into Anique_Profile as per given user information. ",Toast.LENGTH_LONG).show();
Toast.makeText(SocialActivity.this, "Data is Written!", Toast.LENGTH_LONG).show();
}catch (Exception ex){
ex.printStackTrace();
}
progressDialog.hide();
finish();
}
});
Bundle params = new Bundle();
params.putString("fields", "id, name, email, gender, age_range, birthday, posts, feed");
request.setParameters(params);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
private Bundle getFacebookData(JSONObject object) {
Bundle bundle = new Bundle();
try{
id = object.getString("id");
profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?width=200&height=200");
Log.i("profile_pic", profile_pic +"");
bundle.putString("profile_pic",profile_pic.toString());
}catch (JSONException ex){
ex.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
bundle.putString("idFacebook",id);
if(object.has("name")){
try{
bundle.putString("name", object.getString("name"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
if(object.has("email")){
try{
bundle.putString("email", object.getString("email"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
if(object.has("gender")){
try{
bundle.putString("gender", object.getString("gender"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
if(object.has("age_range")){
try{
bundle.putString("age_range", object.getString("age_range"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
if(object.has("birthday")){
try{
bundle.putString("birthday", object.getString("birthday"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
if(object.has("posts")){
try{
bundle.putString("posts", object.getString("posts"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
return bundle;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
I want to get current users profile statuses for catching particular key words to predict something. There is no objection in showing the posts to user on my App. But that doesn't seem inappropriate since prediction is involved here.
You need to do something with the data that more or less directly benefits the user’s “in-app experience” to begin with ... Facebook will not approve this in review, if the sole purpose is background analysis of the data that has no direct connection to the user experience.
The permission necessary to read a user’s posts would be user_posts, but documentation lists this as one of the non-applicable use cases:
Non-visible use of this data such as sentiment analysis or guarding against spam bots.
https://developers.facebook.com/docs/facebook-login/permissions/v3.0#reference-user_posts
Related
i'm very beginner in this problem.
i following the tutorials from youtube make a database for user register, i use localhost and put the php file into htdocs and it's succes but when i tried to put the php file into 000webhost file manager. the result is 'something went wrong' it should be 'Succesfully Registered'. i dont know what should i do because there's no error in logcat. i'm sure there's no error in php file because i've matched it with the real source code.
Example Error Image
Thank you in advance.
here is my code
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class Register extends AppCompatActivity {
private EditText etName, etEmail, etPassword, etReenterPassword;
private TextView tvStatus;
private String URL = "https://db4image.000webhostapp.com/login/register.php";
private String name, email, password, reenterPassword;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = findViewById(R.id.name);
etEmail = findViewById(R.id.email);
etPassword = findViewById(R.id.password);
etReenterPassword = findViewById(R.id.repass);
tvStatus = findViewById(R.id.tvStatus);
name = email = password = reenterPassword = "";
}
public void daftarCok (View view) {
name = etName.getText().toString().trim();
email = etEmail.getText().toString().trim();
password = etPassword.getText().toString().trim();
reenterPassword = etReenterPassword.getText().toString().trim();
if(!password.equals(reenterPassword)){
Toast.makeText(this, "Password Mismatch", Toast.LENGTH_SHORT).show();
}
else if(!name.equals("") && !email.equals("") && !password.equals("")){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
tvStatus.setText("Successfully registered.");
Intent inten = new Intent(Register.this, MainActivity.class);
startActivity(inten);
}
else if (response.equals("failure")) {
tvStatus.setText("Something went wrong!");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("name", name);
data.put("email", email);
data.put("password", password);
return data;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
public void login(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
This is my register.php
<?php
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])){
require_once "conn.php";
require_once "validate.php";
$name = validate($_POST['name']);
$email = validate($_POST['email']);
$password = validate($_POST['password']);
$sql = "INSERT INTO users VALUES ('', '$name', '$email', '" . md5($password) . "')";
if(!$conn->query($sql)){
echo "failure";
}else{
echo "success";
}
}
?>
There are libraries available for login with outlook using a browser (especially chrome browser i.e. MSAL android library ) OR ADAL, but I don't want to log-in with chrome because in my device chrome is not available (Its custom OS flashed in an android device).
I have tried on my end also but its not working as this code is giving access token but not useful to call graph API
here is my code
package learn2crack.weboauth2;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity implements View.OnClickListener {
private static final String TAG = "MainActivity";
//Change the Scope as you need
WebView web;
Button auth;
SharedPreferences pref;
TextView Access;
String authCode = "";
private Dialog auth_dialog;
private Button authEbay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("AppPref", MODE_PRIVATE);
Access =(TextView)findViewById(R.id.Access);
auth = (Button)findViewById(R.id.auth);
auth.setOnClickListener(this);
authEbay = (Button)findViewById(R.id.auth_ebay);
auth.setOnClickListener(this);
authEbay.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.auth:
auth(Constants.OUTLOOK.USER_AGENT,
Constants.OUTLOOK.OAUTH_URL,
Constants.OUTLOOK.REDIRECT_URI,
Constants.OUTLOOK.CLIENT_ID,
Constants.OUTLOOK.OAUTH_SCOPE);
break;
case R.id.auth_ebay:
auth(Constants.EBAY.USER_AGENT,
Constants.EBAY.OAUTH_URL,
Constants.EBAY.REDIRECT_URI,
Constants.EBAY.CLIENT_ID,
Constants.EBAY.OAUTH_SCOPE);
break;
}
}
private void auth(String userAgent, String oauthUrl, String redirectUri, String clientId,
String oauthScope) {
final Dialog auth_dialog;
// TODO Auto-generated method stub
auth_dialog = new Dialog(MainActivity.this);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView)auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
WebSettings webSettings = web.getSettings();
web.getSettings().setUserAgentString(userAgent);
webSettings.setSupportMultipleWindows(true);
web.loadUrl(oauthUrl+"?redirect_uri="+
redirectUri+"&response_type=code&client_id="+
clientId+"&scope="+ oauthScope);
web.setWebViewClient(new WebViewClient() {
boolean authComplete = false;
Intent resultIntent = new Intent();
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains("?code=") && authComplete != true) {
Uri uri = Uri.parse(url);
authCode = uri.getQueryParameter("code");
callGraphAPI(authCode);
Log.i("", "CODE : " + authCode);
authComplete = true;
resultIntent.putExtra("code", authCode);
auth_dialog.dismiss();
Toast.makeText(getApplicationContext(),"Authorization Code is: "
+authCode, Toast.LENGTH_SHORT).show();
}else if(url.contains("error=access_denied")){
Log.i("", "ACCESS_DENIED_HERE");
Toast.makeText(getApplicationContext(), "Error Occured",
Toast.LENGTH_SHORT).show();
auth_dialog.dismiss();
}
}
});
auth_dialog.show();
auth_dialog.setTitle("Authorize Learn2Crack");
auth_dialog.setCancelable(true);
}
private void callGraphAPI(final String code)
{
Log.d(TAG, "Starting volley request to graph");
/* Make sure we have a token to send to graph */
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject parameters = new JSONObject();
try {
parameters.put("key", "value");
} catch (Exception e) {
Log.d(TAG, "Failed to put parameters: " + e.toString());
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Constants.OUTLOOK.MSGRAPH_URL,
parameters,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
/* Successfully called graph, process data and send to UI */
Log.d(TAG, "Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap();
headers.put("Authorization", "Bearer " + authCode);
return headers;
}
};
Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());
request.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
}
anybody please suggeest how to get proper access token after login with microsoft/outlook using webview.
Thanks in advance.
I was able to implement a Facebook login for a social networking app i am developing for android. I used Facebook's android sdk to do so, as well as getting first/last name, gender and age and displaying it on a profile page. Now i want to know how i can store this information on a database in order to display it to other users who visit the profile. Thanks in advance! Here is the code i am using for the profile page.
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
public class ProfileActivity extends AppCompatActivity {
private Profile profile = Profile.getCurrentProfile();
public ImageView profileActivityPicture;
public TextView nameFirst, nameLast, age, gend, user_location;
private String userID, email, gender, picture, birthday, name, city;
private String profilePicUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("My Profile");
}
nameFirst = (TextView) findViewById(R.id.profileActivityFirstName);
nameLast = (TextView) findViewById(R.id.profileActivityLastName);
age = (TextView) findViewById(R.id.profileActivityAge);
gend = (TextView) findViewById(R.id.profileActivityGender);
profileActivityPicture = (ImageView) findViewById(R.id.profileActivityPic);
user_location = (TextView) findViewById(R.id.profileActivityCity);
if(profile != null) {
nameFirst.setText(getString(R.string.hello_user, profile.getFirstName()));
nameLast.setText(getString(R.string.hello_user, profile.getLastName()));
}
nameFirst.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
nameFirst.setTypeface(null, Typeface.BOLD);
nameLast.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
nameLast.setTypeface(null, Typeface.BOLD);
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject data,
GraphResponse response) {
try {
data = response.getJSONObject();
if (data.has("id"))
userID = data.getString("id");
if (data.has("name"))
name = data.getString("name");
if (data.has("location"))
city = data.getJSONObject("location").getString("name");
user_location.setText(city);
user_location.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
if (data.has("picture"))
Picasso.with(ProfileActivity.this).load("https://graph.facebook.com/" + userID+ "/picture?width=3000&height=4000").into(profileActivityPicture);
if (data.has("birthday"))
birthday = data.getString("birthday");
age.setText(birthday);
age.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
age.setTypeface(null, Typeface.BOLD);
if (data.has("gender"))
gender = data.getString("gender");
gend.setText(gender);
gend.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
} catch(Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,cover,picture.type(large),location");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
#Override
public void onDestroy(){
super.onDestroy();
}
}
When you get response in completed callback simply Parse like this
JSONObject jobj = response.getJSONObject();
if (jobj != null) {
try {
ProfileBean profileBean = new ProfileBean();
profileBean.id = jobj.getString("id");
profileBean.name = jobj.getString("name");
profileBean.email = jobj.getString("email");
profileBean.link = jobj.getString("link");
profileBean.last_name = jobj.getString("last_name");
profileBean.first_name = jobj.getString("first_name");
profileBean.gender = jobj.getString("gender");
JSONObject pic = jobj.getJSONObject("picture");
JSONObject data = pic.getJSONObject("data");
profileBean.profile_pic = data.getString("url");
} catch (Exception e) {
// print exception
}
}
here you FB data are stored in a profileBean so like this you can get your data..
Actually i want to post on my page as a page not as a user using facebook sdk in android app but the problem is page "AccessToken" which i retrieve from graph request is in String and now i cannot use it in an other graph request. it says String cannot converted to AccessToken.
Here is my code.
package com.mak.masimmak.pageshare;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import org.json.JSONException;
import org.json.JSONObject;
public class sharePage extends AppCompatActivity {
Button shareButton;
public String PageId;
String PageAccessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_page);
shareButton = (Button) findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(getIntent().getExtras() != null) {
Bundle extras = getIntent().getExtras();
PageId = extras.getString("PageId");
/* make the API call */
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/"+PageId+"?fields=access_token",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
try {
JSONObject data = response.getJSONObject();
PageAccessToken = data.getString("access_token");
PostOnPage();
} catch (JSONException e) {
Toast.makeText(sharePage.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
).executeAsync();
}
}
});
}
public void PostOnPage(){
Bundle params = new Bundle();
params.putString("message", "This is a test message");
/* make the API call */
new GraphRequest(
/* Problem is here the PageAccessToken is in String How to use this string token here? */
(AccessToken) PageAccessToken,
"/"+PageId+"/feed",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
}
}
).executeAsync();
}
}
I search the problem in google and i found something..
public AccessToken(String accessToken, String applicationId, String userId, Collection permissions, Collection declinedPermissions, AccessTokenSource accessTokenSource, Date expirationTime, Date lastRefreshTime)
But i don't know how use this or implement this in my code.
I found the solution of my own question.
You can convert AccessToken from String format to Facebook AccessToken format using this line of code.
AccessToken PageAT = new AccessToken(PageAccessToken, AccessToken.getCurrentAccessToken().getApplicationId(), AccessToken.getCurrentAccessToken().getUserId(), AccessToken.getCurrentAccessToken().getPermissions(), null, AccessTokenSource.FACEBOOK_APPLICATION_NATIVE, AccessToken.getCurrentAccessToken().getExpires(), null);
Then this PageAT will work fine in your new Graph Request..
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Is there any api for facebook to integration in android?
I got a requirement to publish images to facebook through android application.
Please give links or suggestions regarding this..
If you had taken the time to Google "Android Facebook SDK" you'd have immediately found the official Android Facebook SDK: http://github.com/facebook/facebook-android-sdk
Having used it in a project I can say it's a little rough around the edges as the new oAuth / Graph API based stuff is quite young, but it works well with a little tweaking.
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import com.sun.medialib.mlib.Image;
import net.xeomax.FBRocket.FBRocket;
import net.xeomax.FBRocket.Facebook;
import net.xeomax.FBRocket.LoginListener;
import net.xeomax.FBRocket.ServerErrorException;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
public class TestRocket extends Activity implements LoginListener {
public FBRocket fbRocket;
public static String currentFileName ;
public final String images[] = {"http://safesport.site40.net/tv.jpg"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shareFacebook();
}
public void shareFacebook() {
fbRocket = new FBRocket(this, "test",
"ommited");
if (fbRocket.existsSavedFacebook()) {
fbRocket.loadFacebook();
return;
} else {
//fbRocket.login(R.layout.testrocket);
fbRocket.login(R.layout.testrocket);
}
}
public void onLoginFail() {
fbRocket.displayToast("Login failed!");
//fbRocket.login(R.layout.correr);
}
public String setFileName(String filename) {
// TODO Auto-generated method stub
TestRocket.currentFileName = filename;
return filename;
}
public void onLoginSuccess(Facebook facebook) {
SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy");
SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
String data = sdf.format(new Date());
String time = sdf1.format(new Date());
try {
facebook.setStatus("Start Walk:"+time+"\n"+ "Day:"+data+"\n"+"Where:"+"\n"
+"http://maps.google.com/?q=http://safesport.site40.net/"+currentFileName);
fbRocket.displayToast("Status Posted Successfully!! ");
return ;
} catch (ServerErrorException e) {
if (e.notLoggedIn()) {
fbRocket.login(R.layout.ciclismo);
} else {
System.out.println(e);
}
}
}
}
I explained the process in detail together with a simple sample code. You can find it here:
http://developer.blog.appxtream.com/?p=34
Download source code from here (https://deepshikhapuri.wordpress.com/2017/04/07/get-location-of-facebook-user-using-graph-api-in-android/)
package facebooklocation.facebooklocation;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
CallbackManager callbackManager;
ImageView iv_image, iv_facebook;
TextView tv_name, tv_email, tv_dob, tv_location, tv_facebook;
LinearLayout ll_facebook;
String str_facebookname, str_facebookemail, str_facebookid, str_birthday, str_location;
boolean boolean_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
getKeyHash();
listener();
}
private void init() {
iv_image = (ImageView) findViewById(R.id.iv_image);
iv_facebook = (ImageView) findViewById(R.id.iv_facebook);
tv_name = (TextView) findViewById(R.id.tv_name);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_dob = (TextView) findViewById(R.id.tv_dob);
tv_location = (TextView) findViewById(R.id.tv_location);
tv_facebook = (TextView) findViewById(R.id.tv_facebook);
ll_facebook = (LinearLayout) findViewById(R.id.ll_facebook);
FacebookSdk.sdkInitialize(this.getApplicationContext());
}
private void listener() {
tv_facebook.setOnClickListener(this);
ll_facebook.setOnClickListener(this);
iv_facebook.setOnClickListener(this);
}
private void facebookLogin() {
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e("ONSUCCESS", "User ID: " + loginResult.getAccessToken().getUserId()
+ "\n" + "Auth Token: " + loginResult.getAccessToken().getToken()
);
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
boolean_login = true;
tv_facebook.setText("Logout from Facebook");
Log.e("object", object.toString());
str_facebookname = object.getString("name");
try {
str_facebookemail = object.getString("email");
} catch (Exception e) {
str_facebookemail = "";
e.printStackTrace();
}
try {
str_facebookid = object.getString("id");
} catch (Exception e) {
str_facebookid = "";
e.printStackTrace();
}
try {
str_birthday = object.getString("birthday");
} catch (Exception e) {
str_birthday = "";
e.printStackTrace();
}
try {
JSONObject jsonobject_location = object.getJSONObject("location");
str_location = jsonobject_location.getString("name");
} catch (Exception e) {
str_location = "";
e.printStackTrace();
}
fn_profilepic();
} catch (Exception e) {
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email,gender,birthday,location");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
if (AccessToken.getCurrentAccessToken() == null) {
return; // already logged out
}
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email"));
facebookLogin();
}
}).executeAsync();
}
#Override
public void onError(FacebookException e) {
Log.e("ON ERROR", "Login attempt failed.");
AccessToken.setCurrentAccessToken(null);
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday"));
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
callbackManager.onActivityResult(requestCode, resultCode, data);
} catch (Exception e) {
}
}
private void getKeyHash() {
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo("facebooklocation.facebooklocation", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
private void fn_profilepic() {
Bundle params = new Bundle();
params.putBoolean("redirect", false);
params.putString("type", "large");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"me/picture",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("Response 2", response + "");
try {
String str_facebookimage = (String) response.getJSONObject().getJSONObject("data").get("url");
Log.e("Picture", str_facebookimage);
Glide.with(MainActivity.this).load(str_facebookimage).skipMemoryCache(true).into(iv_image);
} catch (Exception e) {
e.printStackTrace();
}
tv_name.setText(str_facebookname);
tv_email.setText(str_facebookemail);
tv_dob.setText(str_birthday);
tv_location.setText(str_location);
}
}
).executeAsync();
}
#Override
public void onClick(View view) {
if (boolean_login) {
boolean_login = false;
LoginManager.getInstance().logOut();
tv_location.setText("");
tv_dob.setText("");
tv_email.setText("");
tv_name.setText("");
Glide.with(MainActivity.this).load(R.drawable.profile).into(iv_image);
tv_facebook.setText("Login with Facebook");
} else {
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday,user_location"));
facebookLogin();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
LoginManager.getInstance().logOut();
}
}