error in using android-facebook-sdk - android

I am just not able to figure out the problem in my code
I want to login with FaceBook for my app
I have followed a tutorial from a youtube video.
in the code , I am able to login using facebook, but I am not able to implement the logout functionality.
i tried doing it. (the code for logging out is also there but still its not working)
the code is as follows:
after i click on login button:
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.fb_button:
try{
//to check if already logged in.
//my code never enters the following block.
if(fb.isSessionValid()){
Toast.makeText(getBaseContext(), "loging out", Toast.LENGTH_LONG).show();
try {
fb.logout(getBaseContext());
// update_fb_buttonimage() is a function to change the image of button
//if logged in: it shows logout
// else it shows login.
//but somehow its not working
update_fb_buttonimage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//following is working fine.
// but every time i click n the button, it enters this bolok of code.
//which is not what i want. this is tobe executed only if user is not logged in
//even if user is logged in , program enters this code only.
// instead of this th above "if" block should be executed.
else{
Toast.makeText(getBaseContext(), "logging in", Toast.LENGTH_LONG).show();
fb.authorize(LoginPage.this,new DialogListener(){
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
update_fb_buttonimage();
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "You can't login to the facebook", Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "unIdentified Error", Toast.LENGTH_LONG).show();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "onCancel", Toast.LENGTH_LONG).show();
}} );
} }catch(Exception e){
System.out.print(e.toString());
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
break;
}
Where is my error?

just replace the MainActivity.this with yours and updateButtonImage()
if(fb.isSessionValid())
{
try {
fb.logout(getApplicationContext());
updateButtonImage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//button close session
}
else
{
fb.authorize(MainActivity.this,new String[] {"publish_stream"}, new DialogListener(){
#Override
public void onFacebookError(FacebookError e)
{
Toast.makeText(MainActivity.this, "on Facebook error", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e)
{
Toast.makeText(MainActivity.this, "on error", Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values)
{
updateButtonImage();
}
#Override
public void onCancel()
{
}
});
//login in to facebook
}

Related

Using access token on graph api

I am trying to get JSON data from this url.
As you can see I need access token to get this.
So far I am able to login to facebook and get user access token
`fb.authorize(MainActivity.this, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "OnFbError", Toast.LENGTH_SHORT);
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "OnError", Toast.LENGTH_SHORT);
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "OnComplete", Toast.LENGTH_SHORT);
Editor editor=sp.edit();
editor.putString("access_token", fb.getAccessToken());
editor.putLong("access_expires", fb.getAccessExpires());
editor.commit();
try {
updateButtonImage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent(MainActivity.this, NewsFeed.class);
startActivity(i);
}`
How to use this access token to access the json data?
By using Facebook SDK you can manage authentication and token by the Session class. getAccessToken() method in session class is responsible to provide token.
Session session = Session.getActiveSession();
if (session != null && session.getState().isOpened()){
Log.i("sessionToken", session.getAccessToken());
Log.i("sessionTokenDueDate", session.getExpirationDate().toLocaleString());
}
By using this access token u can get user image as:
https://graph.facebook.com/me/picture?access_token=<your_access_token_here>

How to get Facebook user name in android app

I added Facebook login function to my application. it was successfully connect and logout from the application.
I want to print that login user name in my application.
Can anyone help meto find this?
I used This as example
This is my code.
fbLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(fb.isSessionValid()){
try {
fb.logout(getApplicationContext());
updateButtonImage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
fb.authorize(MainActivity.this, new String[]{"email"}, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "fbError", Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
updateButtonImage();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "onCancel", Toast.LENGTH_LONG).show();
}
});
}
}
});
you need to refer this link facebook sdk
and get information from user object.
Bundle params = new Bundle();
params.putString("fields", "name,first_name,last_name");
friendsRequest.setParameters(params);
// Get current logged in user information
Request meRequest = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
FacebookRequestError error = response.getError();
if (error != null) {
Log.e(FriendSmashApplication.TAG, error.toString());
handleError(error, true);
} else if (session == Session.getActiveSession()) {
// Set the currentFBUser attribute
((FriendSmashApplication)getApplication()).setCurrentFBUser(user);
}
}
});
or you can try this example.
http://www.androiddevelopersolution.com/2012/09/android-facebook-integration.html
I would follow this Facebook doc on how to fetch the user's data after he logged into your application.

Add Data to post on facebook wall in android not displaying any message to post

I am using the following code and trying to post message on facebook wall along with the picture url. Both message and picture url is empty. Can any one find out and direct me in the right direction?
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
public void postToWall() {
Bundle params = new Bundle();
params.putString("message","test to post");
params.putString("url", URLEncoder.encode("http://a.espncdn.com/photo/2010/0523/pg2_a_cricket_576.jpg"));
try {
String response = facebook.request("me/feed", params, "POST");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 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() {
}
});
}
set this permission as public
private String[] PERMISSIONS = new String[]
{ "publish_stream", "read_stream", "offline_access" };
This will check is session exist if yes then it will direct update if not then ask user permission to update on wall.
Button click event
facebookConnector = new FacebookConnector(APP_ID, activity.getParent(),
activity.getApplicationContext(),PERMISSIONS);
if (facebookConnector.getFacebook().isSessionValid())
{
postMessageInThread(position); // see method below
}
else
{
SessionEvents.AuthListener listener = new SessionEvents.AuthListener()
{
#Override
public void onAuthSucceed()
{
postMessageInThread(position);
}
#Override
public void onAuthFail(String error)
{
}
};
SessionEvents.addAuthListener(listener);
facebookConnector.login();
}
This will update your data on wall
private void postMessageInThread(final int position)
{
Thread t = new Thread()
{
public void run()
{
try
{
facebookConnector.postMessageOnWall(
"Your Text Data",
"Your Email URL","Description");
mFacebookHandler.post(mUpdateFacebookNotification);
} catch (Exception ex)
{
Log.e("", "Error sending msg", ex);
}
}
};
t.start();
}
Note: : Here Position is my list record so manage your data according to that.

integrate yahoo messenger with android app

i surfed net to find some code snippet or some help to integrate yahoo messenger in android application. i could not find some thing helpful.
Please Help me by providing some link, tutorial or code sample so that i could integrate the yahoo messenger.
Thanks
Finally got solution for yahoo messenger integration i used openymsg a library and using below link
http://edwin.baculsoft.com/2011/11/creating-a-simple-yahoo-messenger-auto-response-with-java-and-openymsg-library/
changed my code in activity as below worked like a charm :)
public class SimpleYahoo extends Activity implements SessionListener{
/** Called when the activity is first created. */
private Logger logger = Logger.getAnonymousLogger();
private Session session = new Session();
Button sendButton;
boolean isLoginsuccess;
ListView resultTextView;
EditText editText;
Handler handler;
ArrayList<String> replymessage;
String reply;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
replymessage=new ArrayList<String>();
try {
session.login("yahooid", "password");
} catch (AccountLockedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LoginRefusedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FailedLoginException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.addSessionListener(this);
sendButton=(Button) findViewById(R.id.button);
resultTextView=(ListView) findViewById(R.id.result);
editText=(EditText) findViewById(R.id.input);
sendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
doLogin();
}
});
handler=new Handler()
{
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what==0)
{
replymessage.add(reply);
setListAdapter();
}
}
};
}
private void doLogin() {
try {
// insert your yahoo id
// as for this example, im using my yahoo ID "dombaganas"
session.sendMessage("targetyahooid", editText.getText().toString());
} catch (Exception e) {
Log.e(e.getMessage(), e.getMessage());
}
}
#Override
public void dispatch(FireEvent fe) {
// TODO Auto-generated method stub
ServiceType type = fe.getType();
SessionEvent sessionEvent = fe.getEvent();
if (type == ServiceType.MESSAGE) {
try {
// log request message
reply=sessionEvent.getMessage();
Log.i("message","message from " + sessionEvent.getFrom() + " \nmessage " + sessionEvent.getMessage() );
// give an automatic response
// session.sendMessage(sessionEvent.getFrom(), "hi, you are sending " + sessionEvent.getMessage());
// session.
handler.sendEmptyMessage(0);
} catch (Exception e) {
Log.e(e.getMessage(), e.getMessage());
}
}
}
public void setListAdapter()
{
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.multi_line_list_item,replymessage);
resultTextView.setAdapter(arrayAdapter);
resultTextView.setSelection(replymessage.size()-1);
}
}

AsyncTask Execution Debugging

I have used ASyncTask before and have not faced any problems. I don't understand why this code is not working. I have to access an ftp server to download a text file that i set to a TextView. The code within the ASyncTask works fine. I have checked it. For some reason I am getting a problem when I call the new thread 'new GetStory().execute'. Any help would be great.
package com.amazingstories;
import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayStory extends Activity {
String path;
TextView story;
FTPClient ftp = new FTPClient();
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
path = getIntent().getExtras().getString("path");
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.displaystory);
story = (TextView) findViewById(R.id.tvStory);
story.setText(path);
file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"temp.txt");
new GetStory().execute();
// try{
// new GetStory().execute();
// }catch(Exception e){
// Toast.makeText(getApplicationContext(), e.toString(),
// Toast.LENGTH_SHORT).show();
//
// }
}
public class GetStory extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Try",
Toast.LENGTH_SHORT).show();
try {
Toast.makeText(getApplicationContext(), "Try",
Toast.LENGTH_SHORT).show();
if (!ftp.isConnected()) {
ftp.connect(".....");
Toast.makeText(getApplicationContext(),
"connected to server", Toast.LENGTH_SHORT).show();
ftp.login("....", ".....");
}
Toast.makeText(getApplicationContext(), "FTP Connected",
Toast.LENGTH_SHORT).show();
ftp.changeDirectoryUp();
ftp.download(path, file, new FTPDataTransferListener() {
//ProgressDialog dialog;
#Override
public void aborted() {
// TODO Auto-generated method stub
// dialog.dismiss();
story.setText("Transfer Aborted");
}
#Override
public void completed() {
// TODO Auto-generated method stub
//dialog.dismiss();
}
#Override
public void failed() {
// TODO Auto-generated method stub
//dialog.dismiss();
story.setText("Transfer Failed");
}
#Override
public void started() {
// TODO Auto-generated method stub
//dialog = ProgressDialog.show(DisplayStory.this, "",
// "Loading. Please wait...", true);
}
#Override
public void transferred(int arg0) {
// TODO Auto-generated method stub
}
});
// tv.setText(test.toString());
Toast.makeText(getApplicationContext(), "Done",
Toast.LENGTH_SHORT).show();
} catch (FTPException e) {
Toast.makeText(getApplicationContext(),
"Exception Caught " + e, Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),
"Exception Caught " + e, Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),
"Exception Caught " + e, Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (FTPIllegalReplyException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),
"Exception Caught " + e, Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (FTPDataTransferException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),
"Exception Caught " + e, Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (FTPAbortedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
ftp.logout();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FTPIllegalReplyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FTPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
getFileData get = new getFileData();
try {
story.setText(get.getData(file));
Toast.makeText(getApplicationContext(), "Set TextView",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
file.delete();
}
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Try",
Toast.LENGTH_SHORT).show();
You are not allowed to call Toast inside doInBackground.
doInBackground method runs in non-ui thread so you can not manipulate or sidplay Toast on UI.It must be done in onPreExecute or in onPostExceute.
The methods onPreExecute(), onPostExecute(), and onProgressUpdate() are the only methods during an AsyncTask execution that are called on the main (UI) thread, and therefore are the only places you can directly make calls to UI methods (like TextView.setText() and Toast.makeText()).
Your program is likely crashing because you cannot create a Toast from a thread where "a Looper has not been prepared", which is what happends when you do so from doInBackground(); this causes an exception and a crash.

Categories

Resources