I'm trying to integrate posting to one's wall from within my app. I already have an area where the user can save his/her username and password (encrypted). I would like my program to recall the saved username and password, pass that to Facebook for authentication, and then allow the app to post simple text (maybe a link too) to the user's wall.
That said, I've read everything on the developer pages at Facebook (the api looks completely foreign to me... I've never done any type of web app development before... just desktop apps), and experimented with the Java libraries here but to be honest, I don't understand any of the various implementations. Some claim to be simple to use, but apparently they are all way above my head.
I've even tried messing with the official Facebook Android SDK, but that uses a webview interface, and I can't pass in the username and password for easy authentication. Plus, I'm still clueless as to how to post to the wall even after correct authentication.
Please help.
Thanks.
Oh, btw I already have a Facebook API key and Application ID.
[UPDATE 1]
For further clarification:
If I use the following code snippet with the official Facebook Android SDK http://github.com/facebook/facebook-android-sdk what should I do next (after the user has logged-in)? This is unclear to me.
Facebook facebookClient = new Facebook();
facebookClient.authorize(this, "[APP ID]", new String[] {"publish_stream", "read_stream", "offline_access"}, this);
where "this" is an Activity that implements a DialogListener, and "[APP ID]" is my Facebook application ID.
Thanks.
[UPDATE 2]
I found a solution (see below), though the only thing missing is the ability to auto-populate the login text boxes with the data I have stored in the app. The official Facebook Android SDK may not allow for this. I'll keep looking into it.
I figured it out, with Tom's help (thanks). The key was creating a dialog with the "stream.publish" API call, using the Facebook Android SDK. Here are the steps:
Download the official Facebook Android SDK : http://github.com/facebook/facebook-android-sdk
Import the project files into Eclipse.
Export the project as a *.jar file. (this might cause a conflict)
[UPDATE]
Facebook recently updated the source code and I noticed the icon file caused resource id conflicts with my projects (Android 1.5+). My solution is to forget about exporting as a jar. Instead, copy the Facebook "com" folder directly into your app's "src" folder (i.e. "com.facebook.android" should be a package in your app... right alongside your source files). If you already have a "com" folder in your "src" folder, don't worry about any dialog boxes that appear about overwriting files, none of your source files should be overwritten. Go back into Eclipse, and refresh the "src" folder and "com.facebook.android" should now be listed as a package. Copy one of the included Facebook icons to your app's "drawable" folder and refresh that as well. Eclipse will complain about the "FbDialog.java" file... just add an import pointing to your app's "R" file to the header of that file (e.g. if your app's package name is "com.android.myapp," then add this: "import com.android.myapp.R;"). Go to #5 if you needed to do this.
Add the .jar file to your project's build path
Look at the following simplified example code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import com.facebook.android.*;
import com.facebook.android.Facebook.DialogListener;
public class FacebookActivity extends Activity implements DialogListener,
OnClickListener
{
private Facebook facebookClient;
private LinearLayout facebookButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.test);//my layout xml
facebookButton = (LinearLayout)this.findViewById(R.id.Test_Facebook_Layout);
}
#Override
public void onComplete(Bundle values)
{
if (values.isEmpty())
{
//"skip" clicked ?
return;
}
// if facebookClient.authorize(...) was successful, this runs
// this also runs after successful post
// after posting, "post_id" is added to the values bundle
// I use that to differentiate between a call from
// faceBook.authorize(...) and a call from a successful post
// is there a better way of doing this?
if (!values.containsKey("post_id"))
{
try
{
Bundle parameters = new Bundle();
parameters.putString("message", "this is a test");// the message to post to the wall
facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
}
catch (Exception e)
{
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
#Override
public void onError(DialogError e)
{
System.out.println("Error: " + e.getMessage());
}
#Override
public void onFacebookError(FacebookError e)
{
System.out.println("Error: " + e.getMessage());
}
#Override
public void onCancel()
{
}
#Override
public void onClick(View v)
{
if (v == facebookButton)
{
facebookClient = new Facebook();
// replace APP_API_ID with your own
facebookClient.authorize(this, APP_API_ID,
new String[] {"publish_stream", "read_stream", "offline_access"}, this);
}
}
}
AsyncFacebookRunner mAsyncRunner;
Facebook facebook =new Facebook("Your app id");
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
facebook.authorize(FbdemoActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
#Override
public void onComplete(Bundle values) {
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
});
public void postOnWall(String msg) {
Log.d("Tests", "Testing graph API wall post");
try {
String response = facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
response = facebook.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
Here is an objective answer to your new question, "What do I do next?"
A quick look at the source code leads me to believe this is what you do:
Check this URL for the REST (http://en.wikipedia.org/wiki/Representational_State_Transfer) API methods you can use to leave a comment/post:
http://developers.facebook.com/docs/reference/rest/
Specifically this: http://developers.facebook.com/docs/reference/rest/links.post
Check out lines 171 through 295 of Facebook.java
http://github.com/facebook/facebook-android-sdk/blob/master/facebook/src/com/facebook/android/Facebook.java
To see how to use the API to make these requests.
You'll probably want this method (it's overloaded, see the code).
/**
* Make a request to Facebook's old (pre-graph) API with the given
* parameters. One of the parameter keys must be "method" and its value
* should be a valid REST server API method.
*
* See http://developers.facebook.com/docs/reference/rest/
*
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
*
* Example:
* <code>
* Bundle parameters = new Bundle();
* parameters.putString("method", "auth.expireSession");
* String response = request(parameters);
* </code>
*
* #param parameters
* Key-value pairs of parameters to the request. Refer to the
* documentation: one of the parameters must be "method".
* #throws IOException
* if a network error occurs
* #throws MalformedURLException
* if accessing an invalid endpoint
* #throws IllegalArgumentException
* if one of the parameters is not "method"
* #return JSON string representation of the response
*/
public String request(Bundle parameters)
To those who have problems, in the new facebook(); , the string is you App_id, and just delete the APP_ID in the authorized call.
Don't know why the error message is shown, but I guess that facebook updated the facebook SDK.
Related
I am new to azure but i know certain things like how to retrieve and store data to azure , i followed azure official documentation for this purpose.
Link is Here - https://azure.microsoft.com/en-in/documentation/articles/mobile-services-android-get-started-data/
But the problem is, this tutorial is only showing How to retrieve and use Data from azure using Adapters and Lists . I want to know , How can i retrieve a single value from azure mobile services and how to use it in android.
Plzz provide me both backend code (if there is any) and java code for this . THANKS in advance
I got it solved. No need to create a custom API.
Just follow the basics , Here is the code :-
final String[] design = new String[1];
private MobileServiceTable<User> mUser;
mUser = mClient.getTable(User.class);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
final MobileServiceList<User> result =
mUser.where().field("name").eq(x).execute().get();
for (User item : result) {
// Log.i(TAG, "Read object with ID " + item.id);
desig[0] = item.getDesignation(); //getDesignation() is a function in User class ie- they are getters and setters
Log.v("FINALLY DESIGNATION IS", desig[0]);
}
} catch (Exception exception) {
exception.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
designation.setText(desig[0]);
}
}.execute();
DON'T forget to create a class User for serialization and all. Also you should define the array .
FEEL FREE to write if you got it not working.
EDIT :-
design[0] is an array with size 1.
eq(x) is equal to x where , x variable contains username for which i want designation from database (azure).
You can do this with a custom API. See this link: https://azure.microsoft.com/en-us/documentation/articles/mobile-services-how-to-use-server-scripts/#custom-api
Code looks like this:
exports.post = function(request, response) {
response.send(200, "{ message: 'Hello, world!' }");
}
It's then reachable at https://todolist.azure-mobile.net/api/APIFILENAME.
If you want to access a table you can do something like:
exports.post = function(request, response) {
var userTable = tables.getTable('users');
permissionsTable
.where({ userId: user.userId})
.read({ success: sendUser });
}
function sendUser(results){
if(results.length <= 0) {
res.send(200, {});
} else {
res.send(200, {result: results[0]});
}
}
You can then follow the instructions for using the API on your Android client here: https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-call-custom-api/
How your app is written will change how this code works/looks, but it looks something like:
ListenableFuture<MarkAllResult> result = mClient.invokeApi( "UsersAPI", MarkAllResult.class );
That invokes the API. You need to write the class and Future to handle the results. The above page explains this in great detail.
The most optimal solution would be to create an api on your server which accepts an ID to return an single object/tablerow.
In your android app, you only have to call:
MobileServiceTable<YourClass> mYourTable;
mClient = new MobileServiceClient(
"https://yoursite.azurewebsites.net/",
mContext);
mYourTable = mClient.getTable(YourClass.class);
YourClass request = mYourTable.lookUp(someId).get();
// request -> https://yoursite.azurewebsites.net/tables/yourclass/someId
YourClass should have the same properties as the object on the server.
I'm currently trying to integrate Facebook into my Android application. I've had no problems getting the app to connect and authenticate. But I'm having a little trouble understanding how I can handle data once the onCompleted(Response response) callback method is executed.
The method below works:
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
new Request(session, "/me", null, HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
JSONObject data = graphObject.getInnerJSONObject();
Log.i(TAG, "My DETAILS: ");
try {
Log.i(TAG, "ID: " + data.getLong("id"));
Log.i(TAG, "Name: " + data.getString("name"));
Log.i(TAG, "Email: " + data.getString("email"));
Log.i(TAG,
"Gender: " + data.getString("gender"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}).executeAsync();
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
When I run my application, Facebook authenticates, the data is retrieved and successfully outputs to the Logcat window. However, I'm at a loss to understand how I can pass the JSONObject back to my fragment for further processing.
Most examples I've looked at online simply set the JSONObject content to views in the fragment, or even less helpful simply say /* Handle response here */ or something similar.
I have another similar method where I want to get a profile image url and download the image, but I can't get the url back to my fragment for further processing.
Should I do something like develop a runnable class that accepts a JSONObject as a parameter and start a separate thread from the onCompleted() method to process it the way I want?
My current goal is to get a list of the users friends who use my app and save their profile pictures for use within the app. Am I going about this the wrong way?
SO if I understand you properly, you are getting all data, you are able to parse the JSON but you are not able to pass the data to your other fragment? Why dont you write to a file, which can be accessible from anywhere?
Why do you want to "DOWNLOAD" the images, that will increase your processing time. Just use this URL: https://graph.facebook.com/"+uid.trim()+"/picture?type=normal Where uid is your users id. Use this in Conjunction with Universal Image Loader to asynchronously load your images in image view. You save your time - you save a headache of manually caching files or saving them on the SD.
But bro, the problem here is that Facebook will stop support to the API you are using by April of 2015. Start porting your app to use the latest facebook API; which however is not so useful in getting users information. Cheers and keep on coding :)
I am attempting to integrate the Dropbox chooser drop-in api into my application. I am running into an abnormal issue. In my app when I launch the dbx chooser, anytime that I select a file the application fails with the following error code:
Sorry, an error has occurred. Please try again later.
Here is the portion of my code that implements the Dropbox API. This portion of the code is where the dropbox api is initially invoked.
public void StartDropboxApplication() {
// create the chooser
DbxChooser chooser = new DbxChooser(APP_KEY);
DbxChooser.ResultType result;
// determine which mode to be in // TODO REMOVE ALL BUT FILE CONTENT TODO SIMPLIFY by making this a setting
switch(( (RadioGroup) ParentActivity.findViewById(R.id.link_type)).getCheckedRadioButtonId() ) {
case R.id.link_type_content:
result = DbxChooser.ResultType.DIRECT_LINK;
break;
default:
throw new RuntimeException("Radio Group Related error.");
}
// launch the new activity
chooser.forResultType(result).launch(ParentActivity, 0);
}
Here is the position where the code should then pick it up although it never does.
protected void onActivityResult( int request, int result, Intent data ) {
Log.i(fileName, "result: " + result);
// check to see if the camera took a picture
if (request == 1) {
// check to see if the picture was successfully taken
if (result == Activity.RESULT_OK) {
onPicture();
} else {
Log.i(fileName, "Camera App cancelled.");
}
} else if (request == 0) {
if ( result == Activity.RESULT_OK ) {
onDropbox(data);
} else {
Log.i(fileName, "dropbox related issue.");
}
}
}
Thank you for any help or suggestions that you are able to provide.
I was able to solve my own issues and get this working. On the off chance that someone else has a similar problem I will detail the solution. The first issue was I was that my APP_KEY was incorrect.
The next issue was that I was attempting to read from a direct link instead of a content link. The direct link provides the application with a link to the file on the Dropbox server whereas the content link provides the application with a cached version of the file. If the file is not present on the device, the SDK downloads a copy for you.
I am new to android. I am developing the new app with email sending option. To send a mail I have used gmail configurations host "smtp.gmail.com", port 465 with SSL true. To send an email I have apache commons API. OnTouch event mail sending method will call. Whenever touch button it shows following errors,
Error : Could not find class 'javax.naming.InitialContext', referenced from method org.apache.commons.mail.Email.setMailSessionFromJNDI
Warning: VFY: unable to resolve new-instance 955 (Ljavax/naming/InitialContext;) in Lorg/apache/commons/mail/Email;
Warning : org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465
I have added uses-permission android:name="android.permission.INTERNET" in my manifest file.
Can i use all java files in android ?
My email code executed correctly as a stand alone java program.
Here is an example of what I am doing in an app. I have an app that has its own email account that sends an email to the user when they fill out a form and press the submit button.
Important make sure you have the libSMTP.jar file referenced in your app. I am using this library for the following code. Here is the following code being used, take from it what you'd like, hope this is useful:
Imports needed:
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;
Submit button to make the request to send email
submit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//-- Submit saves data to sqlite db, but removed that portion for this demo...
//-- Executes an new task to send an automated email to user when they fill out a form...
new sendEmailTask().execute();
}
}
});
Email task to be preformed on seperate thread:
private class sendEmailTask extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPostExecute(Void result)
{
}
#Override
protected void onPreExecute()
{
}
#SuppressLint("ParserError")
#Override
protected Void doInBackground(Void... params)
{
try {
//--Note the send format is as follows: send(from, to, subject line, body message)
send("myAppName#gmail.com", "emailToSendTo#gmail.com", "Form Submitted", "You submitted the form.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Send function being used:
public void send(String from, String to, String subject, String text) throws IOException
{
SMTPClient client = new SMTPClient("UTF-8");
client.setDefaultTimeout(60 * 1000);
client.setRequireStartTLS(true); // requires STARTTLS
//client.setUseStartTLS(true); // tries STARTTLS, but falls back if not supported
client.setUseAuth(true); // use SMTP AUTH
//client.setAuthMechanisms(authMechanisms); // sets AUTH mechanisms e.g. LOGIN
client.connect("smtp.gmail.com", 587);
checkReply(client);
//--Note the following format is as follows: client.login("localhost", (...your email account being used to send email from...), (...your email accounts password ...));
client.login("localhost", "myAppName#gmail.com", "...myAppName email account password...");
checkReply(client);
client.setSender(from);
checkReply(client);
client.addRecipient(to);
checkReply(client);
Writer writer = client.sendMessageData();
if (writer != null)
{
SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);
writer.write(header.toString());
writer.write(text);
writer.close();
client.completePendingCommand();
checkReply(client);
}
client.logout();
client.disconnect();
}
Check reply function being used:
private void checkReply(SMTPClient sc) throws IOException
{
if (SMTPReply.isNegativeTransient(sc.getReplyCode()))
{
sc.disconnect();
throw new IOException("Transient SMTP error " + sc.getReplyCode());
}
else if (SMTPReply.isNegativePermanent(sc.getReplyCode()))
{
sc.disconnect();
throw new IOException("Permanent SMTP error " + sc.getReplyCode());
}
}
From Apache Commons Net 3.3, you can just drop the jar in your classpath and start using the AuthenticationSMTPClient : http://blog.dahanne.net/2013/06/17/sending-a-mail-in-java-and-android-with-apache-commons-net/
I want to post a predefind message with link on facebook wall without user intervention .I mean user just log into facebook and my predefind message should be post with link on user's facebook wall.
Below is my code.
public class PostOnFacebookWall {
public static void postOnWall(Facebook facebook , final Context context, final String placeName) {
Bundle params = new Bundle();
params.putString("message", placeName);
facebook.dialog(context, "feed", params ,new DialogListener() {
public void onFacebookError(FacebookError e) {
}
public void onError(DialogError e) {
}
public void onComplete(Bundle values) {
Toast.makeText(context, placeName+" for today's hangout has been posted on your facebook wall. ", Toast.LENGTH_LONG).show();
}
public void onCancel() {
}
});
}
}
I've looked so many links about my question like below
http://stackoverflow.com/questions/11316683/adding-content-to-facebook-feed-dialog-with-new-facebook-sdk-for-android
which passed all the parameter like "link","description","image" and much more.
Someone is saying that u have to pass all the parameters.I just want to predefind messages and link over that.
My message is should be "Let's hangout at " and here placeName should be a link.
And this complete msg i want to pass from my code .I don't want that my code opens dialog where user enters it's message.
If you need to post a predefined message to a User's Facebook Wall, you shouldn't be using the facebook.dialog method.
For more on why that shouldn't be used, read my answer posted here: https://stackoverflow.com/a/13507030/450534
That being said, to get the result you want, try this piece of code:
Bundle postStatusMessage = new Bundle();
// ADD THE STATUS MESSAGE TO THE BUNDLE
postStatusMessage.putString("message", "Let's hangout at " + placeName);
postStatusMessage.putString("link", "www.the_example_web_address.com");
Utility.mAsyncRunner.request("me/feed", postStatusMessage, "POST", new StatusUpdateListener(), null);
And this is where you can check the response from the Facebook API by parsing the String response:
private class StatusUpdateListener extends BaseRequestListener {
#Override
public void onComplete(String response, Object state) {
}
A point to note here is, you cannot pass a message with a link in it. To elaborate (as the earlier statement might sound confusing), You cannot pass a link in the message tag with a link that will be parsed by Facebook and show up in a post like links on FB do.
To see the difference clearly, post the status update using the code above and see how it looks on Facebook. Then, after having done that, remove this postStatusMessage.putString("link", "www.the_example_web_address.com"); from the code above and include the link in the message tag, post it and see how it looks on Facebook.