Sharing post using Facebook Graph API in Android - android

I'm trying to share post using Facebook APIs inside my application , i created an account on Facebook Developer and i put the app id inside the application , the login process is working fine and if i shared a post from the developer Facebook account , every thing is fine . But when i try to share using any other Facebook account i got nothing shared .
I'm using Facebook SDK 3.5 and below are the sharing code:
/**
* Post message with image
*
* #param imageURl
*/
public void postStatusMessage( byte [] imageURl ) {
if ( checkPermissions( Session.getActiveSession() ) ) {
final CustomProgressDialog progress = new CustomProgressDialog( FBActivity.this ) ;
progress.show() ;
// Filling the needed data for the share
Bundle parameters = new Bundle() ;
parameters.putString( "message" , shareText.getText().toString() ) ; // message
parameters.putString( "description" , name ) ;// description
parameters.putString( "link" , linkUrl ) ;// link if available
parameters.putByteArray( "picture" , imageURl ) ;// byte array for the image so it can be shared as image not as link
Request.Callback callback = new Request.Callback() {
public void onCompleted( Response response ) {
if ( response.getError() == null ) {
// Share post was done succesfully
Toast.makeText( FBActivity.this , getString( R.string.statusUpdateSucc ) , Toast.LENGTH_LONG ).show() ;
onlineActionID = ( String ) response.getGraphObject().getProperty( "id" ) ;
shareSuccesfuly = true ;
} else {
// Fail in share
Toast.makeText( FBActivity.this , "" + getString( R.string.statusUpdateFail ) , Toast.LENGTH_LONG ).show() ;
}
// Dismiss progress dialog
if ( progress.isShowing() )
progress.dismiss() ;
// if share was done sucessfully , navigate back to the previvos page
if ( shareSuccesfuly ) {
finish() ;
}// end if.
else {
finish() ;
}// end else().
}
} ;
// Request should have the me/photos tag so we can share photos in the user profile
Request request = new Request( Session.getActiveSession() , "me/photos" , parameters , HttpMethod.POST , callback ) ;
request.executeAsync() ;
} else {
requestPermissions() ;
}
}

The SDK you are using is very old, I strongly recommend you update to the latest release
You need to get the permissions needed approved by facebook, see this doc
Once done, you need to make your app live from the Status & Review tab
You shouldn't keep asking users for the publish permission, but instead describe why this is needed, see the guidelines here.

Related

How to get Instagram Following List using Instagram graph api

How to get the following list from the Instagram account using the access token
I tried everything but not work.
here some API link which I tried before but none of them work.
I tried this one https://www.instagram.com/urvish_._/?__a=1
also this one
I tried but nothing can help me.
You can get the following (or also follower) list using the code below. Steps:
Make sure you're logged in on instagram.com
Open the API link: https://www.instagram.com/urvish_._/?__a=1 (your target username here is urvish_._)
Open the browser console: normally Ctrl+Shift+J on Windows/Linux or ⌘+Option+J on Mac
Paste this code and press Enter:
const GRAPHQL_MAX_PER_PAGE = 50;
async function getList() {
let pageLimit = 200; // from my testing
let baseInfo = JSON.parse(document.getElementsByTagName('body')[0].innerText);
let userId = baseInfo.graphql.user.id;
let config = { user_edge: 'edge_follow', query_hash: 'd04b0a864b4b54837c0d870b0e77e076', total_count: baseInfo.graphql.user.edge_follow.count };
// for followers instead of followings:
// { user_edge: 'edge_followed_by', query_hash: 'c76146de99bb02f6415203be841dd25a', total_count: baseInfo.graphql.user.edge_followed_by.count }
let after = null, hasNext = true, thisList = [];
for (pageCount = 1; hasNext && (pageCount <= pageLimit); ++pageCount) {
try {
let response = await fetch(`https://www.instagram.com/graphql/query/?query_hash=${config.query_hash}&variables=` + encodeURIComponent(JSON.stringify({
id: userId, include_reel: true, fetch_mutual: true, first: GRAPHQL_MAX_PER_PAGE, after: after
})));
if (!response.ok) {
console.warn(`Failed at page number ${pageCount.toLocaleString()}. HTTP status ${response.status}: ${response.statusText}.`);
break;
}
try {
response = await response.json();
} catch (error) {
console.error(`You may need to verify your account. Stopping. Failed at page number ${pageCount.toLocaleString()}.`, error);
break;
}
hasNext = response.data.user[config.user_edge].page_info.has_next_page
after = response.data.user[config.user_edge].page_info.end_cursor
thisList = thisList.concat(response.data.user[config.user_edge].edges.map(({ node }) => {
return {
id: node.id,
username: node.username,
full_name: node.full_name,
profile_pic_url: node.profile_pic_url,
};
}));
} catch (error) {
console.warn(`Error at page number ${pageCount.toLocaleString()}:`, error);
}
console.log(`${thisList.length.toLocaleString()} of ${config.total_count.toLocaleString()} fetched so far`);
}
console.info(`${thisList.length.toLocaleString()} fetched.`);
console.log(thisList);
}
getList()
Browser console showing a fetched list after code execution
In the code I've set the page limit to 200 so you can get up to 10,000 of your followings.
PS: For a way to visualise your lists and get more details, you can try Instagram Lists, a tool I made.

How to share or post game score on face book wall for android devices using Corona SDK tool?

I want to share some random score of my app on facebook. Everytime I run the app, I log in to fb successfully but the app shows the error.
Here is my listener function called on facebook.login. Else statement executes instead of if ( isAvailable ) statement. I looked everything on internet but still lost.
function listener ( event )
local serviceName = "facebook" --supported values are "twitter", "facebook", or "sinaWeibo"
local isAvailable = native.canShowPopup( "social", serviceName )
if ( isAvailable ) then --- does not execute this statement
local function networkListener( event )
if ( event.isError ) then
print( "Network error: ", event.response )
else
print ( "RESPONSE: " .. event.response )
end
end
accessTokenFromFacebookLogin = facebook.getCurrentAccessToken(); --- gets token of current fb user
facebookUserId = facebook.request("me", "GET", { field = "id" }); --- gets all the data of user in this case user id
local params = {};
params.body = "&score="..tostring(newScore).."&access_token="..accessTokenFromFacebookLogin;
network.request( "https://graph.facebook.com/"..facebookUserId.."/scores", "POST", networkListener, params); --- post the score on desired user id's feed or something
else --- shows this msg instead of executing if statement :(
native.showAlert(
"Cannot post " .. serviceName .. " score.",
"Please setup your " .. serviceName .. " account or check your network connection.",
{ "OK" } )
end
end
Please help me resolve this issue. Any help will be much appreciated. Thank you.
Facebook changed their policies a while back. You can't post pre-filled in text anymore (perhaps with added permissions but I'm not 100% sure of that). You can only post a link or an image. So perhaps you can take a screenshot of the score and upload that image?
Kind regards
Bram

Posting savescreen to FB

I need help to solve this problem: I want to post on FB a save screen from my app (I got save screen by using display.save function). Everything works fine on Android while on my iPad it crashes! Please find the function code below:
local function postonFB( event)
display.save( tab3fields, { filename="ticket.jpg", baseDir=system.DocumentsDirectory, isFullResolution=true, backgroundColor={0, 0, 0, 0} } )
local fbAppID = "4531113981XXXXX"
local function fbListener( event )
if event.phase == "login" then
local attachment = {
message="I am a champion!",
source= {baseDir=system.DocumentsDirectory, filename="ticket.jpg", type="image"}
}
facebook.request("me/photos", "POST", attachment)
native.showAlert("Facebook", "Submitted!")
end
end
-- photo uploading requires the "publish_actions" permission
facebook.login( fbAppID, fbListener, { "publish_actions" } )
end
Please help, I am getting crazy to understand what's wrong!
Thanks a lot. Ubaldo
here is my facebook sharing code:
baseDir = system.DocumentsDirectory
display.save( group , "screenshot.png", system.DocumentsDirectory )
local facebook = require "facebook"
local fbAppID = "898209XXXXXXXXX"
function onLoginSuccess()
attachment = {
message = "i got ".. score .. " blablabla",
source = { baseDir=system.DocumentsDirectory, filename="screenshot.png", type="image" }
}
facebook.request( "me/photos", "POST", attachment )
end
function fbListener( event )
if event.isError then
native.showAlert( "ERROR", event.response, { "OK" } )
else
if event.type == "session" and event.phase == "login" then
onLoginSuccess()
elseif event.type == "request" then
print("upload done")
end
end
end
facebook.login( fbAppID, fbListener, { "publish_stream", "publish_actions" } )
ps do you have this in you build.settings?
plugins =
{
["facebook"] =
{
publisherId = "com.coronalabs"
},
},

Air android/mobile: same sharedobject for different apps?

I have two apps, one is a trial version the other the full version of a game, both made with adobe air. While saving data via the sharedobjects solution is no problem, I would like to use "one" savegame for both appsm, so users can keep their progress when upgrading to the full version. I tried around a little. But code like e.g. ...:
SharedObject.getLocal("myApp","/");
... doesnt work. So the question is, is there a way to have two Air apps using the same shared object? Or maybe if not using, at least "read" the shared object of another Air app?
Thanks in advance,
ANB_Seth
The answer is yes, I actually made a game transfer system for iOS and Android via network connection and 6 digit hash the user has to enter in the newly installed app to fetch the SO from the server. You could do this with a simple file stored locally on the SD card or other local storage device.
/**
* send this user's current save data to the server
*/
public function send():void{
var ba:ByteArray = new ByteArray();
// Main.sv.user - is the registerClassAlias object we write/read locally via SharedObject
ba.writeObject(Main.sv.user);
var name:String = Crypto.hash("Random Secrect Salt - typically user score, name, etc.");
// create 6 digit hash
var key:String = Crypto.hash(name).slice(0, 6).toUpperCase();
var request:URLRequest = new URLRequest ( 'https://sharedobject.com/transfer/save/name/'+name+'/key/'+key );
var loader: URLLoader = new URLLoader();
request.contentType = 'application/octet-stream';
request.method = URLRequestMethod.POST;
request.data = ba;
loader.addEventListener(IOErrorEvent.IO_ERROR, function (evt:Event) {
trace("error - network");
onSaveRestoreEvent(1);
});
loader.addEventListener(Event.COMPLETE, function (evt:Event) {
addChild(new BaseDialog("Save Sent To Server", "Your data has been sent to the server. To get this data back from the server " +
"you will need your secret key. Please write this six digit key down:\n"+name));
});
loader.load( request );
}
/**
* create a GET SO dialog
*/
public function receive():void{
var text:Sprite = new Sprite();
var textInput:TextInput = new TextInput();
textInput.width = Constants.SCREEN_WIDTH-100;
textInput.y = -50;
text.addChild(textInput);
var dialog:BaseDialog = new BaseDialog("Enter Secret Save Key", "Please enter your six digit secret save key in the field below, then press \"Get\".\n\n",
"Get", function():void{
text.removeChildren();
var url:String = "https://sharedobject.com/transfer/get/name/"+textInput.text; //servlet url
var request:URLRequest = new URLRequest(url);
//get rid of the cache issue:
var urlVariables:URLVariables = new URLVariables();
urlVariables.nocache = new Date().getTime();
request.data = urlVariables;
request.method = URLRequestMethod.GET;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, function (evt:Event) {
var loader:URLLoader = URLLoader(evt.target);
var bytes:ByteArray = loader.data as ByteArray;
bytes.position = 0;
if(bytes.length <= 10 || !(bytes.readObject() is User)){
onSaveRestoreEvent(2);
}else{
try{
bytes.position = 0;
Main.sv.user = (bytes.readObject() as User);
Main.sv.save();
onSaveRestoreEvent(0);
}
catch( e : EOFError ){
onSaveRestoreEvent(3);
}
}
});
loader.addEventListener(IOErrorEvent.IO_ERROR, function (evt:Event) {
trace("error - network");
onSaveRestoreEvent(1);
});
loader.load(request);
},
"Close", function():void{text.removeChildren();}, null, null, text);
dispatchEvent(new CreateBaseDialogEvent(dialog));
}
/**
* called after the restore save system is done
* #param prompt int [0 = complete][1 = error network][2 = error key][3 = error EOF]
*/
private function onSaveRestoreEvent(prompt:int):void{
var dialog:BaseDialog;
if(prompt == 0){
dialog = new BaseDialog("Restore Complete!", "All save data has been restored.");
}else if(prompt == 1){
dialog = new BaseDialog("Network Error!", "Please seek an internet connection and try again.");
}else if(prompt == 2){
dialog = new BaseDialog("Invalid Secret Key!", "The key you've entered seems to be invalid, or the save data has expired on the server. " +
"Data only lasts on the server for 24 hours.");
}else{
dialog = new BaseDialog("Error!", "There was an issue getting the file from the server. Please try the transfer again.");
}
dispatchEvent(new CreateBaseDialogEvent(dialog));
}

Zend framework 2 + Android Mobile + ZfcUser Authentication

I need to authenticate via Android on my website (Zend Framework2+ZfcUser+ZfcUserDoctrineORM).
I want to call an url that authenticate me and return a json object that contains my session_id.
I don't know if it is the correct way but whatever i don't know how to do that with zfcUser.
David
Next, i will be able to store this session_id into Shared Preferences storage.
First of all sorry for my English.
In my application i need almost the same.
Ok. So in yoursite.com/module/YourModuleName/Module.php do:
use YourModuleName\Model\YourModuleName;
use YourModuleName\Model\YourModuleName;
class Module {
public function onBootstrap(MvcEvent $e) {
$app = $e->getApplication();
$em = $app->getEventManager();
$sm = $app->getServiceManager();
$auth = $sm->get('zfcuser_auth_service');
$model = new OrdersManager();
if (!$auth->hasIdentity()) {
$em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($app, $sm, $auth, $model) {
$match = $e->getRouteMatch();
// No route, this is a 404
if (!$match instanceof RouteMatch) {
return;
}
$match = $e->getRouteMatch();
$matchParams = $match->getParams();
// $matchParams['hash'] == some url param
if (isset($matchParams['hash'])) {
$model->setDbAdapterColibo($sm->get('dbAdapter'));
$usersSqlObject = $model->getUsers();
$salt = md5('caw');
foreach ($usersSqlObject as $key => $user) {
$hash = hash('sha256', $salt.$param1.$user['user_id']);
if ($hash == $matchParams['hash']) {
$authAdapter = $sm->get('ZfcUser\Authentication\Adapter\AdapterChain');
$request = $app->getRequest();
$request->getPost()->set('identity', $user['email']);
// You may use user password to auth user
$request->getPost()->set('credential', $user['user_id']);
$result = $authAdapter->prepareForAuthentication($request);
$auth->authenticate($authAdapter);
// do your staff with session or other.
// after this you will be redirect to page from where query was
break;
}
}
}
});
}
}
}
Don`t forget about yoursite.com/module/YourModuleName/config/module.config.php
You need to add route with your URL param, to receive it in $matchParams = $match->getParams();
In case I have describe you will be auth and immediately redirect to the site.
Example:
http://example.com/someController/someAction/param1/param2/hash...
the result will be auth and open page http://example.com/someController/someAction/param1/param2/hash...
Ok. This is what i need for my app. Hope this help.
P.S. Some ideas get from Zend Framework 2 - Global check for authentication with ZFCUser

Categories

Resources