How to get Facebook data in my Android app [closed] - android

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 7 years ago.
Improve this question
I am developing one Android app in which there are two activities.
First activity: With button to go onto Facebook already login page. I want to know how to fetch data (like Name, DOB, Place, Email ID) from Facebook into my app.
Second activity (with EditText): How to match there API or what is required please let me know. I searched everywhere but did not find any answer.
I have done this, but it is showing errors.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
facebook = (Button) findViewById(R.id.facebook);
facebook.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onClickFacebookLogin();
// Intent in = new Intent(FacebookActivity.this,GetDataFromFacebook.class);
// in.putExtra("email", );
// startActivity(in);
}
});
}
public void onClickFacebookLogin() {
// Session.openActiveSession(this, true, new Session.StatusCallback() {
openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
// ((GlobalFilename)Login.this.getApplication()).setfbSession(session);
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user,
Response response) {
// TODO Auto-generated method stub
if (user != null) {
final GraphUser graphuser=user;
try{
new AsyncTask<Void, Void, Void>() {
String fbemail,fname,lname,mediaid,image_url,gender,dob;
ProgressDialog progressDialog;
ImageLoader imageLoader;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (progressDialog == null) {
progressDialog = createProgressDialog(MyAccount.this);
progressDialog.show();
} else {
progressDialog.show();
}
}
#Override
protected Void doInBackground(Void... params) {
Object g = graphuser.asMap().get("email");
if(g==null)
{
fbemail="";
fname=graphuser.getFirstName();
lname=graphuser.getLastName();
mediaid=graphuser.getId();
System.out.println("===>accountname inside null"+fbemail);
return null;
}
else{
fbemail= graphuser.asMap().get("email").toString();
gender =graphuser.asMap().get("gender").toString();
image_url = "https://graph.facebook.com/"+graphuser.getId()+"/picture?type=square";
// image_url=String.format(image_url);
//accountName =graphuser.getProperty("email").toString();
System.out.println("fb email====>"+fbemail);
fname=graphuser.getFirstName();
lname=graphuser.getLastName();
mediaid=graphuser.getId();
dob=graphuser.getBirthday();
System.out.println("Gender"+gender);
System.out.println("Image==>"+image_url);
try {
InputStream in = new java.net.URL(image_url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
if(mIcon11==null)
{
System.out
.println("null in doinbackground");
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), userid, Toast.LENGTH_LONG).show();
System.out.println("fb email====>"+fbemail);
//Toast.makeText(getApplicationContext(), accountName, Toast.LENGTH_LONG).show();
return null;
}
}
#Override
protected void onPostExecute(Void v) {
super.onPreExecute();
progressDialog.dismiss();
tvname.setText(fname+" "+lname);
tvemail.setText(fbemail);
imageLoader = new ImageLoader(MyAccount.this);
System.out
.println("imageurlonpost==>"+image_url);
// imageLoader.DisplayImage(image_url,fbprofileimage);
if (mIcon11 != null
){
// do what you need to do with the bitmap :)
fbprofileimage.setImageBitmap(mIcon11);
}
else{
Toast.makeText(MyAccount.this,"Null",Toast.LENGTH_LONG).show();
}
}
}.execute();
}catch(Exception e) {
//findViewById(R.id.progressbar).setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Facebook configuration error!", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
},Arrays.asList("email"));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}
Showing errors at new Session.StatusCallback()(under onClickFacebookLogin()) & getActiveSession() (at onActivityResult)

Here is the complete working code.Set up your developer account and call this method.Also dont forget to call onActivityResult() once the control return from facebook.
//Method invoked when facebook login button is clicked
public void onClickFacebookLogin() {
// Session.openActiveSession(this, true, new Session.StatusCallback() {
openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
// ((GlobalFilename)Login.this.getApplication()).setfbSession(session);
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user,
Response response) {
// TODO Auto-generated method stub
if (user != null) {
final GraphUser graphuser=user;
try{
new AsyncTask<Void, Void, Void>() {
String fbemail,fname,lname,mediaid,image_url,gender,dob;
ProgressDialog progressDialog;
ImageLoader imageLoader;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (progressDialog == null) {
progressDialog = createProgressDialog(MyAccount.this);
progressDialog.show();
} else {
progressDialog.show();
}
}
#Override
protected Void doInBackground(Void... params) {
Object g = graphuser.asMap().get("email");
if(g==null)
{
fbemail="";
fname=graphuser.getFirstName();
lname=graphuser.getLastName();
mediaid=graphuser.getId();
System.out.println("===>accountname inside null"+fbemail);
return null;
}
else{
fbemail= graphuser.asMap().get("email").toString();
gender =graphuser.asMap().get("gender").toString();
image_url = "https://graph.facebook.com/"+graphuser.getId()+"/picture?type=square";
// image_url=String.format(image_url);
//accountName =graphuser.getProperty("email").toString();
System.out.println("fb email====>"+fbemail);
fname=graphuser.getFirstName();
lname=graphuser.getLastName();
mediaid=graphuser.getId();
dob=graphuser.getBirthday();
System.out.println("Gender"+gender);
System.out.println("Image==>"+image_url);
try {
InputStream in = new java.net.URL(image_url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
if(mIcon11==null)
{
System.out
.println("null in doinbackground");
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), userid, Toast.LENGTH_LONG).show();
System.out.println("fb email====>"+fbemail);
//Toast.makeText(getApplicationContext(), accountName, Toast.LENGTH_LONG).show();
return null;
}
}
#Override
protected void onPostExecute(Void v) {
super.onPreExecute();
progressDialog.dismiss();
tvname.setText(fname+" "+lname);
tvemail.setText(fbemail);
imageLoader = new ImageLoader(MyAccount.this);
System.out
.println("imageurlonpost==>"+image_url);
// imageLoader.DisplayImage(image_url,fbprofileimage);
if (mIcon11 != null
){
// do what you need to do with the bitmap :)
fbprofileimage.setImageBitmap(mIcon11);
}
else{
Toast.makeText(MyAccount.this,"Null",Toast.LENGTH_LONG).show();
}
}
}.execute();
}catch(Exception e) {
//findViewById(R.id.progressbar).setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Facebook configuration error!", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
},Arrays.asList("email"));
}

Related

Android AlertDialog freezes when saving data in database

In my App my I am using AlertDialog in Async. But it freezes at a point when data is saving in database. what can I do to keep it running? It runs perfectly for sometime but stops after certain time when database is accessed.
Here's my code:
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
return null;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
CheckInternetConnection internet = new CheckInternetConnection(
getApplicationContext());
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
return;
} else {
setUpdatedBarcodes();
}
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here after
data is saved in DB
}
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
DB operations should be done in the background thread. Put it in doInBackground() method too.
I modify your code. may it helps..
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
} else {
setUpdatedBarcodes();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
when saving data in database don't do it on main thread do it on background thread. try code
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// do your work
}
},0);
or
new Thread(new Runnable() {
public void run() {
// do your work here
}
}).start();

Request new publish permission into a fragment

I need to ask at the user to authorize publish permission if he dont do it.
I do it with this row of code:
//Into ShareOnFacebookFragment
Session.getActiveSession().requestNewPublishPermissions(new NewPermissionsRequest((SocialSharingActivity)getActivity(), "publish_actions"));
SocialSharingActivity is the Activity related to my Fragment (ShareOnFacebookFragment).
When I run the application the app correctly ask me the publish permission and I accept, but when I do publish I have this error in my logcat:
12-11 12:17:27.277: E/AndroidRuntime(29125): Caused by: java.lang.UnsupportedOperationException: Session: an attempt was made to request new permissions for a session that has a pending request.
Honestly my only hypotesis is that requestNewPublishPermissions run Async in background and then I have the problems when I try to publish. How I can solve this problem ? I post also my Entire fragment code
private final String TAG = "ShareFragment";
private UiLifecycleHelper uiHelper;
// To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the
// Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in
// order to communicate with the Activity.
private Session.StatusCallback callback = new Session.StatusCallback() { //Provides asynchronous notification of Session state changes.
#Override
public void call(Session session, SessionState state,Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state,Exception exception) {
Log.i("CALLBACK: ", "Session state change: "+state);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
};
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
// try {
// mCallback = (OnHeadlineSelectedListener) activity;
// } catch (ClassCastException e) {
// throw new ClassCastException(activity.toString()
// + " must implement OnHeadlineSelectedListener");
// }
//}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
};
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
uiHelper.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
RelativeLayout myRelative = (RelativeLayout) inflater.inflate(R.layout.share_frame, container, false);
shareButton = (Button) myRelative.findViewById(R.id.shareButton);
workoutIdTextView = (TextView) myRelative.findViewById(R.id.workoutIdTextView);
objectCreatedTextView = (TextView) myRelative.findViewById(R.id.objectCreatedTextView);
actionCreatedTextView = (TextView) myRelative.findViewById(R.id.actionCreatedTextView);
return myRelative;
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
Log.i(TAG, "ONACTIVITYCREATED");
SocialSharingActivity caller =(SocialSharingActivity) getActivity();
Log.w(TAG, "caller "+caller.toString());
workoutIdTextView.setText(String.valueOf(caller.getWorkoutId()));
Log.i(TAG, "Data course " + caller.getEwCourse().toString());
Log.i(TAG, "Message Run " + caller.getEwRun().toString());
ewCourseFrag = caller.getEwCourse();
ewRunFrag = caller.getEwRun();
parAct=new Bundle();
parAct.putAll(ewRunFrag.getParams());
parObj = new Bundle();
parObj.putString("access_token", APP_ACCESS_TOKEN);
gson = new Gson();
parObj.putString("object", gson.toJson(ewCourseFrag));
publishSession = Session.getActiveSession();
//------------------------------Batch HTTP request-----------------------------------------------------------------------------------------------------------------
//
//------------------------------Declaration--and--implementation--of--Callback-----------------------------------------------------------------------------------------------------------------
RequestBatch.Callback batchCallback= new RequestBatch.Callback() {
#Override
public void onBatchCompleted(RequestBatch batch) {
Log.w(TAG, "Batch completed: "+ "OK");
//
}
};
//
Request.Callback reqCreateObjCallback= new Request.Callback() {
#Override
public void onCompleted(Response response) {
if(response.getError() == null){
Log.w(TAG,"reqCreateObjCallback: "+ "OK");
objectCreatedTextView.setText("OK object");
}
else {
Log.e(TAG,"reqCreateObjCallback: "+ response.getError().toString());
Log.d(TAG, response.getError().getCategory().toString());
objectCreatedTextView.setText(response.getError().getCategory().toString());
}
//400
}
};
//
Request.Callback reqPublishCallback= new Request.Callback() {
#Override
public void onCompleted(Response response) {
if(response.getError() == null) {
Log.w(TAG, "reqPublishCallback: "+ "OK");
actionCreatedTextView.setText("OK action");
// Toast.makeText(context, "ACTION_CREATED", Toast.LENGTH_LONG).show();
}
else {
Log.e(TAG, "reqPublishCallback: "+ response.getError().toString());
Log.d(TAG, response.getError().getCategory().toString());
actionCreatedTextView.setText(response.getError().getCategory().toString());
}
}
};
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------Create--instance--of--RequestBatch--------------------------------------------------------------------------------------------------------
RequestBatch requestBatch= new RequestBatch();
//------------------------------Request--for-create-the-graph-object---------------------------------------------------------------------------------------------------------------
Request reqCreateObj= new Request(
publishSession,
"app/objects/fitness.course",
parObj,HttpMethod.POST); //Create a Request for a common ObiectGraph of type course
reqCreateObj.setCallback(reqCreateObjCallback); //Set the callback for the Request
reqCreateObj.setBatchEntryName("objectCreate"); //Tag the request name into the Batch with "objectCreate"
requestBatch.add(reqCreateObj); //Add the request to the batch
//------------------------------Request-for-publish-action-------------------------------------------------------------------------------------------------------------------------------
parAct.putString("course",
"{result=objectCreate:$.id}"); //Use the tag to retrieve the informations about the graph object created
//can also add scrape flag to update the object
// par2.putString("end_time", new Date(new Date().getTime()+1000*60*2).toString()); // live text test
Request reqPublish =
new Request(publishSession, //Create a request for publish an action relative to the object;
// Similarly at a phrase, an action is like "verbo", graph object
"me/fitness.runs/",parAct, //is like "complemento oggetto" and the the user is "soggetto"
HttpMethod.POST); //
reqPublish.setCallback(reqPublishCallback); //Set the callback for the Request
requestBatch.add(reqPublish); //Add the request to the batch
requestBatch.addCallback(batchCallback); //Set the callback for the Batch Request
//Check network session opened and permissions
//codice sospeso
if(Session.getActiveSession().isOpened() && hasPublishPermission() && isNetworkAvailable()) {
Toast.makeText(getActivity(), "Session is opened, I have permission, Network is On", Toast.LENGTH_LONG).show();
requestBatch.executeAsync();
}
else if (Session.getActiveSession().isOpened() && isNetworkAvailable()){
Toast.makeText(getActivity(), "I dont have Permissions: " + Session.getActiveSession().getPermissions(), Toast.LENGTH_LONG).show();
Session.getActiveSession().requestNewPublishPermissions(new NewPermissionsRequest((SocialSharingActivity)getActivity(), "publish_actions"));
Toast.makeText(getActivity(), "Permissions: " + Session.getActiveSession().getPermissions(), Toast.LENGTH_LONG).show();
}
else if (Session.getActiveSession().isOpened() && hasPublishPermission()) {
Toast.makeText(getActivity(), "Check your status connection.", Toast.LENGTH_LONG).show();
}
else {
Intent loginIntent = new Intent((SocialSharingActivity)getActivity(),FbLoginActivity.class);
startActivity(loginIntent);
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
}

Facebook sdk 3.0.1 is not working properly

I am trying to login into the Facebook using Facebook sdk .But it not logging in .Its opening the dialog box but after getting the credentials its not working . If i install the Facebook app it opens the Facebook app but login is not completed i cant get the token and user id . I cant post the message to the wall also . But it displays the toast that "message successfully displayed" but it is not posted in the Facebook wall.
Code:
public boolean isSession() {
access_token = sp.getString(TOKEN, "x");
expires = sp.getLong(EXPIRES, -1);
Log.d("TAG", access_token);
if (access_token != null && expires != -1) {
facebook.setAccessToken(access_token);
facebook.setAccessExpires(expires);
}
return facebook.isSessionValid();
}
private class LoginDialogListener implements DialogListener {
#Override
public void onComplete(Bundle values) {
Log.d("TAG", "LoginONComplete");
token =facebook.getAccessToken();
token_expires = facebook.getAccessExpires();
Log.d("TAG", "AccessToken: " + token);
Log.d("TAG", "AccessExpires: " + token_expires);
savePrefs3(EXPIRES,token_expires);
savePrefs(TOKEN,token);
mAsyncRunner.request("me", new IDRequestListener());
}
#Override
public void onFacebookError(FacebookError e) {
Log.d("TAG", "FacebookError: " + e.getMessage());
}
#Override
public void onError(DialogError e) {
Log.d("TAG", "Error: " + e.getMessage());
}
#Override
public void onCancel() {
Log.d("TAG", "OnCancel");
}
}
private class IDRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
try {
Log.d("TAG", "IDRequestONComplete");
Log.d("TAG", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
Uid = json.getString("id");
savePrefs("UID", Uid);
final String name = json.getString("name");
} catch (JSONException e) {
Log.d("TAG", "JSONException: " + e.getMessage());
} catch (FacebookError e) {
Log.d("TAG", "FacebookError: " + e.getMessage());
}
}
#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
}
}
public void postToWall(String message){
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
showToast("Blank response.");
} else {
showToast("Message posted to your facebook wall!");
}
finish();
} catch (Exception e) {
howToast("Failed to post to wall!");
e.printStackTrace();
finish();
}
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
please tell me where i am going wrong . after displaying a toast app gets closed. while loading the fb dialog if i touch the screen it either reloads or switching back to the app window.
Please give immediate reply
The Facebook object is depreciated.You can use the following code in your activity oncreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// setContentView(R.layout.facebook_dialog);
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user == null) {
Toast.makeText(LoginFacebook.this.getApplicationContext(),
"Facebook Error",
Toast.LENGTH_LONG).show();
finish();
}
else
{
Toast.makeText(LoginFacebook.this.getApplicationContext(),
user.getName()+" Logged in Successfully.",
T
Toast.LENGTH_LONG).show();
finish();
}
//login_fb.setEnabled(true);
//progress.setVisibility(View.INVISIBLE);
}
});
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
finish();
}
And use the following code in the Manifest.xml file under the application tag.
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id" />
<activity
android:name="com.facebook.LoginActivity"
android:label="#string/app_name" >
</activity>
After Loging in to post to wall you have to call this method...
private void publishStory(String user) {
try {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("message", messageToPost);
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (Exception e) {
Log.i("Test",
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(ShareOnFacebook.this
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
progress.setVisibility(View.INVISIBLE);
toastmessage="Posted Successfully";
Toast.makeText(ShareOnFacebook.this
.getApplicationContext(),
toastmessage,
Toast.LENGTH_SHORT).show();
}
}
};
Request request = new Request(session, user+"/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(ShareOnFacebook.this
.getApplicationContext(),
"Facebook Error",
Toast.LENGTH_SHORT).show();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
and declare the variables as..
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions","manage_pages","publish_stream");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
Not exactly the answer to your question, but if you are starting to develop your app: usage of Facebook object is deprecated in 3.x API.
In new API you should use Session object, along with UiLifecycleHelper

Android : Facebook Logout

I have a LoginViaFacebook Acitivity and a login button for facebook Login.I use the following code to login to facebook
private String[] permissions = {"publish_stream",
"read_stream", "user_photos", "publish_checkins", "photo_upload",
"email", "user_birthday" };
if (access_token != null) {
Utility.fb.setAccessToken(access_token);
token = access_token;
Log.e("OnCretae Facebook Token------------", token);
}
if (expires != 0) {
Utility.fb.setAccessExpires(expires);
}
btn_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (CheckInternet.checkConn(LoginViaFacebook.this)) {
Utility.fb.authorize(LoginViaFacebook.this, permissions,
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"onFacebookError",
Toast.LENGTH_LONG).show();
Log.e("Sajolllllllllllllllll", e + "");
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"onError", Toast.LENGTH_LONG)
.show();
Log.e("Sajolllllllllllllllll", e + "");
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
editor = sp.edit();
token = Utility.fb.getAccessToken();
Log.e("Token---------", token);
editor.putString("access_token",
Utility.fb.getAccessToken());
editor.putLong("access_expires",
Utility.fb.getAccessExpires());
editor.commit();
Toast.makeText(getApplicationContext(),
"Login Successful",
Toast.LENGTH_LONG).show();
mProgress = ProgressDialog.show(
LoginViaFacebook.this, "",
"Please Wait...", true);
Thread t = new Thread(retriveProfileData);
t.start();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"onCancel", Toast.LENGTH_LONG)
.show();
}
});
}
}
});
I save the access token to login next time directly if user not logout
I have another activity namely Settings and have button Logout.I use following code to logout from facebook
lagoutLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final String[] items = new String[] { "Yes", "No" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
SettingsActivity.this,
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(
SettingsActivity.this);
builder.setTitle("Select Option");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick
// from
// camera
if (item == 0) {
try {
editor.remove("FacebookId");
editor.remove("EmailId");
editor.commit();
Log.e("Pre----------------", sp1
.getString("access_token", "d"));
editor1.remove("access_token");
editor1.remove("access_expires");
editor1.commit();
Log.e("After----------------", sp1
.getString("access_token", "d"));
Log.e("DATATTAT--------",
sp.getString("FacebookId",
"saf")
+ " "
+ sp.getString(
"EmailId", "as"));
String r = Utility.fb
.logout(SettingsActivity.this);
Log.e("Res-----------", r);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else { // pick from file
dialog.dismiss();
}
}
});
dialog = builder.create();
dialog.show();
}
});
The response from Facebook Logout method show true in Log.
But when i again run application it will automatically login to facebook
I can'nt find out the problem.Please help me
I use this code and it worked fine
public void logout() {
if (!isConnected(activity)) {
Toast.makeText(activity, "Internet not connected", Toast.LENGTH_LONG).show();
return;
}
SessionEvents.onLogoutBegin();
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(this.facebook);
asyncRunner.logout(this.context, new LogoutRequestListener());
}
And here is the listener
public class LogoutRequestListener extends BaseRequestListener {
public void onComplete(String response, final Object state) {
// callback should be run in the original thread,
// not the background thread
mHandler.post(new Runnable() {
public void run() {
SessionEvents.onLogoutFinish();
Intent intent= new Intent(activity,Login.class);
activity.startActivity(intent);
activity.finish();
}
});
}
}
For facebook sdk version 3 above
public void logoutFacebook() {
Session session = Session.getActiveSession();
if(session != null && session.isOpened()){
session.closeAndClearTokenInformation();
}
}
if you are extending and using facebook openSession when logging you must close it using closeSession and put it in your logout or you can simply put it onDestroy just like this
public void onDestroy() {
this.closeSession();
super.onDestroy();
}
Try this :
I hope this will be help to you...
if (mFacebook.isSessionValid()) {
try {
String str = mFacebook.logout(getApplicationContext());
SessionStore.clear(getApplicationContext());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are viewing this answer from google suggestion and using facebook sdk v4 or above, just use this lines. It works perfectly.
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}

progress dialog displays after task is finished in asynctask

Hi i want to display progressdialog until a command is executed through telnet.
so i use asynctask for that purpose.
private class AsyncAction extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
pd.dismiss();
}
// pd.dismiss();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
And i call asynctask in oncreate() like below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
The problem is that i could not see progressdialog until command executes.
please help me solve the issue.
Thanks in advance.
EDIT
The code to send and read command
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length()-1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar)
{
if (sb.toString().endsWith(pattern))
{
if (sb.toString().contains("cdkk"))
{
disconnect();
break;
}
else
{
return sb.toString();
}
}
else
{
disconnect();
break;
}
}
else if(sb.toString().contains("Failed"))
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String error="Invalid username or password!";
alertbox.setMessage(error);
alertbox.setTitle("Error");
alertbox.show();
System.out.println("bad user name");
disconnect();
break;
}
ch = (char) in.read();
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
}
catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + " ");
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
Currently you are trying to do Network operations from onPostExecute because this method called from UI Thread . change your code as to get work in proper way
private class AsyncAction extends AsyncTask<String, Void, String>
{
public static boolean status=false;
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
// make status true or false if command successfully executed
status=true;
}
catch (Exception e)
{
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result)
{
pd.dismiss();
// check status if true then show AlertDialog
if(status==true){
AlertDialog.Builder alertbox =
new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
else{
// your code here
}
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
You need to show the progress bar in onPreExecute() do the work in doInBackground() and then hide the progress bar in onPostExecute(). onPreExecute() and onPostExecute() are both executed on the main thread, where as doInBackground is executed in the background.
You are doing your work on onPostExecute() method which should be inside doInBackground()
show your progress dialog inside onPreExecute() and dismiss inside onPostExecute().

Categories

Resources