Coder Social home page Coder Social logo

fb wall posting about facebook-android-sdk HOT 3 CLOSED

facebook avatar facebook commented on April 25, 2024
fb wall posting

from facebook-android-sdk.

Comments (3)

Korriged avatar Korriged commented on April 25, 2024

Here is a code you can use after having corrected the bug #3:


/**
 * Publishes information on Facebook wall of the connected user
 * Note: the user shall be logged in
 * 
 * @param callingContext Context of the calling Activity 
 * @return true if publication is possible
 */
public boolean publish(Context callingContext) {

    // Checks if there is a connection / if the user is logged in
    if(!facebookConnection.isSessionValid()) {
        return false;
    }


    // Builds the pieces of information to be displayed on Facebook wall
    // Note that it is not possible to jump to next line (e.g. \n, <br/>)

    // Builds the message
    String message = transformToHTML("Message");

    // Builds the title
    String title = transformToHTML("Title");

    // Builds image URL
    String url = transformToHTML("http://www.kratiroff.com/logo-facebook.jpg");

    // Builds the 1st line
    String firstLine = transformToHTML("1st line");

    // Builds the 2nd line
    String secondLine = transformToHTML("2nd line");

    // Builds the name of the link
    String anotherLinkName = transformToHTML("Another link name");

    // Builds the name of the action link
    String actionLinkName = transformToHTML("Action link");

    // Builds URL information
    String url = transformToHTML("http://www.facebook.com");

    // Creates the publish request to be sent to Facebook
    // Refer to http://wiki.developers.facebook.com/index.php/Stream.publish
    //  for parameters to send in the request
    Bundle parameters = new Bundle();

    // Builds message attachment JSON string
    parameters.putString("message", message);

    // Builds attachment JSON string with name=title, caption=1st line, description=2nd line
    // Hyperlink to url on title and image/logo
    String attachments = "{\"name\":\""+title + "\", \"href\":\""+url + "\", \"caption\":\""+firstLine + "\", \"description\":\""+secondLine + "\", \"media\":[{\"type\":\"image\", \"src\":\""+image + "\", \"href\":\""+url + "\"}], \"properties\":{\"another link\":{\"text\":\""+anotherLinkName+",\"href\":\""+url+"\"}}}";
    parameters.putString("attachment", transformToURL(attachments));

    // Builds action links (only 1 is taken into account by Facebook) JSON string to the url
    String actionLinks = "[{\"text\":\""+actionLinkName+ "\", \"href\":\""+url + "\"}]";
    parameters.putString("action_links", transformToURL(actionLinks));


    // Sends the publish request to Facebook
    // in a new thread since the SDK request() method is blocking
    try {
        ThreadPublish threadPublish = new ThreadPublish(this, callingContext, parameters, travelInformation.currentTravel);
        threadPublish.setName("Facebook publish thread");
        threadPublish.setDaemon(true);
        threadPublish.start();
        return true;
    } catch( IllegalThreadStateException e ) {
        myLog.debug(e.toString());
        return false;
    }

} // publish()


public class ThreadPublish extends Thread {

    // Calling context
    Context callingContext = null;

    // Publish parameters, between the constructor and run()
    Bundle params = null;

    // Travel to publish
    TravelBean travel = null;

    /**
     * run() method, called by start() does not allow parameters
     * -> new constructor
     * 
     * @param callingThread Thread which launched this one
     * @param params Publication parameters
     */
    public ThreadPublish(Context callingContext, Bundle params) {
        super();
        this.callingContext = callingContext;
        this.params = params;
        this.travel = travel;
    }

    /**
     * Thread runner
     * Sends the publication request
     * and treats the response
     */
    public void run() {

        // Should be transparent and included in the SDK (facebook-android-sdk)
        // but...
        params.putString("method", "stream.publish");

        try {
            // Could display a progress dialog here

            // Using the old REST API (http://developers.facebook.com/docs/reference/rest)
            String response = facebookConnection.request(params);
            // Using the new Graph API (http://developers.facebook.com/docs/api#publishing)... not working yet!
            // 'me' = current user, 'feed' = his/her wall

            // Decodes the response
            // and change the status as a consequence
            decodePublishReturn(response);
            // Kills this thread
            return;
        } catch(MalformedURLException e) {
            // Kills this thread
            return;
        } catch(IOException e) {
            // Kills this thread
            return;
        }
    }

} // class ThreadPublish

from facebook-android-sdk.

Korriged avatar Korriged commented on April 25, 2024

And please find Utils methods here after:

    /**
     * Decodes the return string of Facebook/request()
     * The string can contain:
     * - an HTML error (HTML page: <HTML>...</HTML>
     * - a Facebook error (JSON)
     * - the id. of the published message if publication succeed
     * 
     * @param publishReturn String to transform         * 
     * @return String conformed with RFC 1738
     */
    private boolean decodePublishReturn(String publishReturn) {
        if((publishReturn==null) || (publishReturn.length()<=0)) {
        }
        // publishReturn = error code in an HTML page if HTTP error
        else if((publishReturn.contains("<HTML>"))||(publishReturn.contains("<html>"))) {
            int errorCode = Integer.parseInt(publishReturn.substring(6, 6+3));
            myLog.debug("Error: HTTP error "+errorCode);
            switch(errorCode) {
                case 102:
                    logout(callingContext);
                    break;
                case 200:
                    logout(callingContext);
                    break;
                default:
            }
        }
        // response = error code as JSON if Facebook error
        else if(publishReturn.contains("error_code")) {
            try {
                //JSONObject json = Util.parseJson(publishReturn);
                //final String errorCode = json.getString("error_code");
                myLog.debug("Error: Facebook error "+Util.parseJson(publishReturn).getString("error_code"));
            } catch(FacebookError e) {
            } catch(JSONException e) {
            }
        }
        // response = error if Facebook error
        else if(publishReturn.contains("error")) {
        }
        else {
            // Published!
            // response = post id (Long as a string)
            // Toast.makeText(context, "Published!", Toast.LENGTH_LONG).show();
            return true;
        }
        // Toast.makeText(context, "Publish error :(", Toast.LENGTH_LONG).show();
        return false;
    }




/**
 * Replaces non 7-bit ASCII characters with &#nnn; (where nnn is the ASCII code of the character)
 * e.g. à é è -> &#224; &#233; &#232; 
 * 
 * @param input String to transform
 * 
 * @return String conformed with HTML specifications
 */
public static String transformToHTML(String input) {
    StringBuffer temp = new StringBuffer(input);

    // Replaces \n by the corresponding HTML tag
    for(int i=0; i<temp.length();i++) {
        if(temp.charAt(i)=='\n') {
            temp.replace(i, i+2, "<br />");
        }
    }

    // HTML: non-7bit-ASCII characters -> &nnn; (where nnn is the ASCII code of the character)
    for(int i=0; i<temp.length();) {
        char character = temp.charAt(i); 
        // Skips control characters
        if(character<' ') {
            temp.replace(i, i+1, "");
        // Keeps spaces
        } else if(character==' ') {
            i++;
        // Keeps digits and letters,
        // and replaces other characters by &#nnn; (nnn=ascii code in decimal)
        } else if((character<'0')
                || ((character>'9') && (character<'A'))
                || ((character>'Z') && (character<'a'))
                || (character>'z')) {
            int asciiCode = (int)character;
            String asciiCodeString = String.valueOf(asciiCode);
            String completeWith0;
            if(asciiCodeString.length()==1) {
                completeWith0 = "00";
            } else if(asciiCodeString.length()==2) {
                completeWith0 = "0";
            } else {
                completeWith0 = "";
            }
            temp.replace(i, i+1, "&#"+completeWith0+asciiCodeString+";");
            i+=6;
        }
        else {
            i++;
        }
    }
    return new String(temp);
}

/**
 * Replaces special characters to characters valid to be sent through an URL
 *  (e.g. HTTP GET):
 *  e.g. ? & = -> %3F %26 %3D
 *  as defined in RFC 1738
 * 
 * @param input String to transform
 * 
 * @return String conformed with RFC 1738
 */
public static String transformToURL(String input) {
    StringBuffer temp = new StringBuffer(input);

    // URL: key characters -> %nn

/*
return URLEncoder.encode(new String(temp));
/
/

XOR:
*/
for(int i=0; i<temp.length();) {
switch(temp.charAt(i)) {
case '\t': temp.replace(i, i+2, "%09"); i+=3; break;
case ' ': temp.replace(i, i+1, "%20"); i+=3; break;
case '"': temp.replace(i, i+1, "%22"); i+=3; break;
case '#': temp.replace(i, i+1, "%23"); i+=3; break;
case '%': temp.replace(i, i+1, "%25"); i+=3; break;
case '&': temp.replace(i, i+1, "%26"); i+=3; break;
case '(': temp.replace(i, i+1, "%28"); i+=3; break;
case ')': temp.replace(i, i+1, "%29"); i+=3; break;
case '+': temp.replace(i, i+1, "%2B"); i+=3; break;
case ',': temp.replace(i, i+1, "%2C"); i+=3; break;
//case '.': temp.replace(i, i+1, "%2E"); i+=3; break;
case '/': temp.replace(i, i+1, "%2F"); i+=3; break;
case ':': temp.replace(i, i+1, "%3A"); i+=3; break;
case ';': temp.replace(i, i+1, "%3B"); i+=3; break;
case '<': temp.replace(i, i+1, "%3C"); i+=3; break;
case '=': temp.replace(i, i+1, "%3D"); i+=3; break;
case '>': temp.replace(i, i+1, "%3E"); i+=3; break;
case '?': temp.replace(i, i+1, "%3F"); i+=3; break;
case '@': temp.replace(i, i+1, "%40"); i+=3; break;
case '[': temp.replace(i, i+1, "%5B"); i+=3; break;
case ']': temp.replace(i, i+1, "%5D"); i+=3; break;
case '^': temp.replace(i, i+1, "%5E"); i+=3; break;
case ''': temp.replace(i, i+1, "%60"); i+=3; break;
case '{': temp.replace(i, i+1, "%7B"); i+=3; break;
case '|': temp.replace(i, i+1, "%7C"); i+=3; break;
case '}': temp.replace(i, i+1, "%7D"); i+=3; break;
case '~': temp.replace(i, i+1, "%7E"); i+=3; break;
default: i++;
}
}
return new String(temp);
}

from facebook-android-sdk.

veradismail avatar veradismail commented on April 25, 2024

Thanks Korriged.
ll try it tonite.

from facebook-android-sdk.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.