I am trying to integrate facebook sdk with my android application and want to retrieve username,email and profile pic of the person logged in but I am getting a System error. My code is as follow-
package com.example.facebooklogin;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import android.net.ParseException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
// Your Facebook APP ID
private static String APP_ID = "801614236517742"; // Replace your App ID here
//private static String APP_ID = "308180782571605"; // Replace your App ID here
// Instance of Facebook Class
private Facebook facebook;
#SuppressWarnings("deprecation")
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
Button btn;
String name;
String email;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btn=(Button)findViewById(R.id.btnFbLogin);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
loginToFacebook();
//getProfileInformation();
}
#SuppressWarnings("deprecation")
public void loginToFacebook()
{
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[] { "email", "publish_stream" },
new DialogListener()
{
#Override
public void onCancel()
{
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values)
{
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error)
{
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror)
{
// Function to handle Facebook errors
}
});
}
else
getProfileInformation();
}
#SuppressWarnings("deprecation")
public void getProfileInformation()
{
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting name of the user
name = profile.getString("name");
// getting email of the user
email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
Logcat of my app-
05-22 06:55:53.774: W/dalvikvm(3713): VFY: unable to find class referenced in signature (Landroid/support/v4/app/Fragment;)
05-22 06:55:53.774: W/dalvikvm(3713): VFY: unable to find class referenced in signature (Landroid/support/v4/app/Fragment;)
05-22 06:55:53.784: I/dalvikvm(3713): Could not find method android.support.v4.content.LocalBroadcastManager.getInstance, referenced from method com.facebook.Session.postActiveSessionAction
05-22 06:55:53.784: W/dalvikvm(3713): VFY: unable to resolve static method 216: Landroid/support/v4/content/LocalBroadcastManager;.getInstance (Landroid/content/Context;)Landroid/support/v4/content/LocalBroadcastManager;
05-22 06:55:53.784: D/dalvikvm(3713): VFY: replacing opcode 0x71 at 0x0009
05-22 06:55:54.514: D/dalvikvm(3713): GC_FOR_ALLOC freed 224K, 9% free 3058K/3360K, paused 54ms, total 57ms
05-22 06:55:54.604: D/Facebook-Util(3713): GET URL: https://graph.facebook.com/me?access_token=CAAEhug8jDagBAP7mXTSAg9pqFittCCALpgdciZCzhWya9pqRH0sB5puv36fD5bta2dNGTKHctWvaoaIBbCIDKLZACX3fNVFAv75u0YOULJZC7MLEZBiEpSOmUADEmB51gllXRTEAi5ZCLAfJGXuKOJIl9ZBJLqiWZAK51nHs5prITm5HrFOUr64D6f2M26ZAxZAk0Y2l5AZATZCznmzCGSDksXQ&format=json
05-22 06:55:57.034: D/Profile(3713): {"error":{"message":"Error validating application. Application has been deleted.","type":"OAuthException","code":190}}
05-22 06:55:57.044: W/System.err(3713): org.json.JSONException: No value for name
05-22 06:55:57.044: W/System.err(3713): at org.json.JSONObject.get(JSONObject.java:355)
05-22 06:55:57.044: W/System.err(3713): at org.json.JSONObject.getString(JSONObject.java:515)
05-22 06:55:57.044: W/System.err(3713): at com.example.facebooklogin.MainActivity$2.onComplete(MainActivity.java:145)
05-22 06:55:57.084: W/System.err(3713): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:276)
Related
I am developing an android app, where the user should be able to log in with a Facebook account. The application has worked in the first 5-10 min. I could see the layout where i was prompted to give/deny permissions.
When i try to log in, it shows me the "Loading" message from Facebook API but then returns to the previous layout.
The error message i receive is: "Should not pass a read () permission to a request for publish or manage authorization".
I appreciate any help to resolve this issue..
package com.kampusbilisim.sencebence;
import java.io.*;
import java.net.*;
import org.json.*;
import com.facebook.android.*;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.*;
import android.util.Log;
import android.view.*;
import android.widget.*;
#SuppressWarnings("deprecation")
public class FullscreenActivity extends Activity {
String TAG = "SenceBence";
private static String APP_ID = "659712077445489";
private Facebook facebook;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
Button btnFbLogin;
private AsyncFacebookRunner mAsyncRunner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_fullscreen);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnFbLogin = (Button) findViewById(R.id.button1);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginToFacebook();
Toast.makeText(FullscreenActivity.this, "Logging in.. ", Toast.LENGTH_SHORT).show();
}
});
TextView tv = (TextView) findViewById(R.id.girisyazisibeyaz);
tv.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/AvenirNextLTPro-Bold.otf"));
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
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[] { "email" , "publish_actions", "publish_checkins", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
}
MessagesActivity.java
package org.example.fbapp;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import android.app.ListActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MessagesActivity extends ListActivity {
// Your Facebook APP ID
private static String APP_ID = "549603678442054";
ListAdapter adapter;
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_MESSAGE = "message";
// data JSONArray
JSONArray data = null;
// Instance of Facebook Class
#SuppressWarnings("deprecation")
private Facebook facebook = new Facebook(APP_ID);
#SuppressWarnings("deprecation")
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
// Hashmap for ListView
ArrayList<HashMap<String, String>> messages = new ArrayList<HashMap<String, String>>();
private ListView lv;
ListView mylistview;
ArrayList<String> array_months;
ArrayAdapter<String> listAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.contacts_view);
mAsyncRunner = new AsyncFacebookRunner(facebook);
ListAdapter adapter = createAdapter();
setListAdapter(adapter);
}
/**
* Creates and returns a list adapter for the current list activity
*
* #return
*/
#SuppressWarnings("deprecation")
protected ListAdapter createAdapter()
{
mAsyncRunner.request("203153109726651/feed", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("GET POSTS", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject obj = new JSONObject(json);
JSONArray finalObj = obj.getJSONArray("data");
array_months = new ArrayList<String>();
for (int i = 0; i < finalObj.length(); i++) {
final String message = finalObj.getJSONObject(i)
.getString("message");
array_months.add(message);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Name: " + message, Toast.LENGTH_LONG)
.show();
}
});
}
// Create a simple array adapter (of type string) with the test values
//ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, adapter);
adapter = new ArrayAdapter<String>(MessagesActivity.this,
android.R.layout.simple_list_item_1, array_months);
} 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) {
}
});
//setListAdapter(listAdapter);
return adapter;
}
}
FBAppActivity.java
package org.example.fbapp;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
#SuppressWarnings("deprecation")
public class FBAppActivity extends Activity {
// Your Facebook APP ID
private static String APP_ID = "549603678442054";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_MESSAGE = "message";
// data JSONArray
JSONArray data = null;
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
// Hashmap for ListView
ArrayList<HashMap<String, String>> messages = new ArrayList<HashMap<String, String>>();
private ListView lv;
// Buttons
Button btnFbLogin;
Button btnFbGetProfile;
Button btnPostToWall;
Button btnShowAccessTokens;
Button btnFbLogout;
Button btnGetPost;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fbapp);
// facebook = new Facebook(APP_ID);
btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
btnFbLogout = (Button) findViewById(R.id.btn_logout);
btnGetPost = (Button) findViewById(R.id.btn_group_posts);
mAsyncRunner = new AsyncFacebookRunner(facebook);
/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
/**
* Logout button Click event
* */
btnFbLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Logout Button", "button Clicked");
logoutFromFacebook();
}
});
/**
* Getting facebook Profile info
* */
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
/**
* Get Posts from Group
* */
btnGetPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getGroupPosts();
//getGPosts();
startActivity(new Intent(FBAppActivity.this, MessagesActivity.class));
}
});
/**
* Showing Access Tokens
* */
btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAccessTokens();
}
});
}
/**
* Function to login into facebook
* */
#SuppressWarnings("deprecation")
public void loginToFacebook() {
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);
btnFbLogin.setVisibility(View.INVISIBLE);
// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
// Making logout button visible
btnFbLogout.setVisibility(View.VISIBLE);
// Making group posts button visible
btnGetPost.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email", "publish_stream",
"user_groups" }, new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);
// Making logout Button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
// Making logout button visible
btnFbLogout.setVisibility(View.VISIBLE);
// Making group posts button visible
btnGetPost.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Get Profile information by making request to Facebook Graph API
* */
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
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");
JSONObject birthday = profile.getJSONObject("location");
final String location = birthday.getString("name");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"Name: " + name + "\nEmail: " + email
+ "\nLocation: " + location,
Toast.LENGTH_LONG).show();
}
});
} 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) {
}
});
}
/**
* Get Group Posts by making request to Facebook Graph API
* */
#SuppressWarnings("deprecation")
public void getGPosts() {
mAsyncRunner.request("203153109726651/feed", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("GET POSTS", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject obj = new JSONObject(json);
JSONArray finalObj = obj.getJSONArray("data");
for (int i = 0; i < finalObj.length(); i++) {
final String message = finalObj.getJSONObject(i)
.getString("message");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MESSAGE, message);
// adding HashList to ArrayList
messages.add(map);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Name: " + message, Toast.LENGTH_LONG)
.show();
}
});
}
} 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) {
}
});
ListAdapter adapter = new SimpleAdapter(FBAppActivity.this, messages,
R.layout.list_item,
new String[] { TAG_MESSAGE }, new int[] {
R.id.name });
//FBAppActivity.this.setListAdapter(adapter);
}
/**
* Function to post to facebook wall
* */
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
/**
* Function to show Access Tokens
* */
#SuppressWarnings("deprecation")
public void showAccessTokens() {
String access_token = facebook.getAccessToken();
Toast.makeText(getApplicationContext(),
"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}
/**
* Function to Logout user from Facebook
* */
#SuppressWarnings("deprecation")
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
btnFbLogout.setVisibility(View.INVISIBLE);
btnGetPost.setVisibility(View.INVISIBLE);
}
});
}
}
#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) {
}
});
}
/*
* #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the
* menu; this adds items to the action bar if it is present.
* getMenuInflater().inflate(R.menu.fbapp, menu); return true; }
*/
}
When i click on the button, the ListView opens but with no data i.e. Empty set.
Contacts_View.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Empty set"
/>
</LinearLayout>
What i mean here is that both the functions are identical.getGPosts() is called in the FBAppActivity whereas the createAdapter() is called in MessagesActivity.getGPosts() works but createAdapter() does not. Kindly help me understand why is this happening.
Basically i am trying to import posts from a facebook group. My Toast object is working fine from the getGPosts() [it is in the FBAppActivity class] function. This function getGPosts() is called on the button click.I verified that i am getting the data using the Toast object. Now i want to populate the data to a ListView. Which i am unable to do. I have tried various methods, but none has worked out for me.
Because you're calling the setListAdapter(adapter) for implicit (Activity's) ListView in the onCreate(Bundle savedInstanceState) method and in the getGPosts() method you reference the correct (visible) ListView.
Simply change the mentioned call in the onCreate(Bundle savedInstanceState) method to:
myListView = getListView();
myListView.setAdapter(adapter);
And you should be fine! Good luck!
P.S. This solution will work if your ListActivity follows the following requirement:
your own view MUST contain a ListView object with the id "#android:id/list"
from Google's documentation
As I see you are extending ListActivity. So below code must throw a NPE.
lv = (ListView)findViewById(R.id.list);
lv.setAdapter(adapter);
You should use below code at onComplete method instead;
setListAdapter(adapter);
or
getListView().setAdapter(adapter);
I am developing a Facebook Android integration using the below code, but once I log-in through this app then it does not logout from facebook even if I logout from Facebook app or browser both from my device. So this android app can still post on my Facebook wall. How do I logout from this app if I logout from my facebook app or facebook on browser.
package com.facebook.androidhive;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
public class AndroidFacebookConnectActivity extends Activity {
// Your Facebook APP ID
private static String APP_ID = "APP_ID"; // Replace with your App ID
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAsyncRunner = new AsyncFacebookRunner(facebook);
loginToFacebook();
postToWall();
}
/**
* Function to login into facebook
* */
public void loginToFacebook() {
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);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Function to post to facebook wall
* */
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
/**
* Function to Logout user from Facebook
* */
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
}
#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) {
}
});
}
}
You can't force a logout from your app if you logout of the Facebook app, at least no API that we support with our SDK.
In theory, you could find a way to attach some sort of uninstall intent or to parse logs for any messages regarding facebook logout, but it generally is not recommended as best practice to force a logout of another app when another app logs out (its not intuitive to the user that this is going to happen).
try remove this code
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
I used the following code to Login through Facebook in my app. I need to do this with Facebook SSO. I have the correct app_id.
package com.fb.sso;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
public class FBSSOActivity extends Activity {
/** Called when the activity is first created. */
public static final String APP_ID = "my_app_id";
private static final String[] PERMISSIONS = new String[] {
"publish_stream", "read_stream", "offline_access" };
private TextView mText;
private Handler mHandler = new Handler();
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;
byte[] raw;
private SharedPreferences mPrefs;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (APP_ID == null) {
Util.showAlert(this, "Warning",
"Facebook Applicaton ID must be set...");
}
// Initialize the content view
setContentView(R.layout.main);
// Initialize the Facebook session
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
mFacebook.setAccessToken(access_token);
}
if (expires != 0) {
mFacebook.setAccessExpires(expires);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FB Sample App", "onActivityResult(): " + requestCode);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
private class LogoutRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
Log.v("comes here>>.","sucess");
// Only the original owner thread can touch its views
FBSSOActivity.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Thanks for using FB Sample App. Bye bye...");
}
});
// Dispatch on its own thread
mHandler.post(new Runnable() {
public void run() {
}
});
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
Log.v("facebook error","fb error");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem loginItem = menu.findItem(R.id.login);
if (mFacebook.isSessionValid()) {
loginItem.setTitle("Logout");
} else {
loginItem.setTitle("Login");
}
loginItem.setEnabled(true);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Login/logout toggle
case R.id.login:
if (!mFacebook.isSessionValid()) {
mFacebook.authorize(this, new DialogListener() {
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Log.v("Entered ", "No ERRRRRRRRRRRR");
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
mFacebook.getAccessToken());
editor.putLong("access_expires",
mFacebook.getAccessExpires());
editor.commit();
Intent i=new Intent(FBSSOActivity.this,second.class);
startActivity(i);
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}else{
mFacebook.setAccessToken(null);
mFacebook.setAccessExpires(0);
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFacebook);
asyncRunner.logout(this.getBaseContext(), new LogoutRequestListener());
}
break;
default:
return false;
}
return true;
}
}
I logged in to preinstalled Facebook app in my device. And I got this screen only.
And in my Logcat this line appears.
09-28 15:18:24.652: E/ActivityThread(1201): Failed to find provider info for com.facebook.katana.provider.AttributionIdProvider
If I logged out from my preinstalled Facebook app, my application prompts me to login, asking the credentials. That time also, the empty screen appears.But in the preinstalled Facebook app, I can see my updates.( I get Logged in).
Update:
Right now I'm checking the app only. I have not published it to market. I got the key by referring this site http://sean.lyn.ch/2011/07/android-the-facebook-sdk-sso-and-you/. And I added it to the app, like this.
Update 2:
Now I got these lines in logcat:
09-29 12:00:12.552: I/ActivityManager(73): Starting activity: Intent { cmp=com.facebook.katana/.ProxyAuth (has extras) }
09-29 12:00:13.022: I/ActivityManager(73): Displayed activity com.facebook.katana/.ProxyAuth: 436 ms (total 436 ms)
09-29 12:00:15.032: W/InputManagerService(73): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy#434b2e88 (uid=10031 pid=2233)
09-29 12:00:15.032: W/IInputConnectionWrapper(2233): showStatusIcon on inactive InputConnection
Can some one please help me to solve nullpointer exception in my following code in
I've got the following FoodStarLoginActivity. The following line is throwing a NullPointer but I don't understand why :facebook.logout(FoodStarLoginActivity.this); could anyone help me out? I even tried getApplicationcontext() instead of my FoodStarLoginActivity but it didn't work.
I am getting following exception :
java.lang.NullPointerException
at android.context.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
at android.webkit.CookieSyncManager.createInstance(CookiesSyncManager.java:96)
at com.facebook.android.Util.clearCookies(Util.java:241)
at com.facebook.android.Facebook.logout(Facebook.java:617)
at ten.mob.socialapp.FoodStarLoginActivity.logout(FoodStarLoginActivity.java:131)
package ten.mob.socialapp;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import ten.mob.socialapp.FacebookConnector;
import ten.mob.socialapp.SessionEvents;
import ten.mob.socialapp.FacebookConnector.LogoutRequestListener;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
public class FoodStarLoginActivity extends Activity{
private static final String faceBookAppId = "*******************";
private static final String faceBookPermission = "publish_stream";
static Facebook facebook = new Facebook(faceBookAppId);
private SharedPreferences mPrefs;
FacebookConnector facebookConnector ;
AsyncFacebookRunner asyncRunner;
private Handler mHandler = new Handler();
Context context;
#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 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(){}
});
}
if(facebook.isSessionValid()){
Intent intent = new Intent(this,SearchMyActivity.class);
startActivity(intent);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
public void logout(){
try {
facebook.logout(FoodStarLoginActivity.this);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
asyncRunner = new AsyncFacebookRunner(facebook);
System.out.println(asyncRunner);
asyncRunner.logout(FoodStarLoginActivity.this, new LogoutRequestListener() {
public void onComplete(String response, Object state) {}
public void onFileNotFoundException(FileNotFoundException e,Object state) {}
public void onFacebookError(FacebookError e, Object state) {}
});
System.out.println(asyncRunner);
System.out.println(facebook.isSessionValid());
}
private class LogoutRequestListener implements RequestListener {
public void onComplete(String response, Object state) {
mHandler.post(new Runnable() {
public void run() {
SessionEvents.onLogoutFinish();
}
});
}
public void onIOException(IOException e, Object state) {}
public void onFileNotFoundException(FileNotFoundException e,Object state) {}
public void onMalformedURLException(MalformedURLException e,Object state) {}
public void onFacebookError(FacebookError e, Object state) {}
}
}
public class SearchMyActivity(){
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.menu_create:
Intent intent = new Intent(this, CreateRestaurantActivity.class);
startActivity(intent);
break;
case R.id.menu_foodstars:
intent = new Intent(this, RestaurantList.class);
startActivity(intent);
break;
case R.id.menu_logout:
FoodStarLoginActivity logoutFoodStar = new FoodStarLoginActivity();
logoutFoodStar.logout();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}