I am trying to develop a Facebook application for Android. I am unable to integrate the "Add Comment" feature to photos in Facebook Albums. Using the Graph API, I can show the previously made comments on a photo. However, I just can't add new comments to a photo.
Can somebody provide me some helpful advice?
here is simple example on doing that..
// post comment to single photo
Bundle parameters = new Bundle();
String target = "";
target = "<PHOTO_ID>/comments";
parameters.putString("message", "post Comment testing");
mAsyncRunner.request(target, parameters, "POST", new FacebookRequestListener(target+" (post comment)"));
and here is a simple example for the listener (you can get this from examples of facebook-android-sdk too)
public class FacebookRequestListener extends BaseRequestListener {
String caller = "default";
public FacebookRequestListener() {
}
public FacebookRequestListener(String caller) {
this.caller = caller;
}
public void onComplete(final String response) {
try {
Log.d(TAG, "FacebookRequestListener|"+caller+":" + response);
} catch (Exception e) {
Log.w(TAG, "Error:"+e.getMessage());
}
}
}
Related
I'm implement Razorpay with PaymentResultWithDataListener. Actually i need order_id and signature so i use PaymentResultWithDataListener not used PaymentResultListener because there are no option to get order_id and signature. And I have follow these links
https://docs.razorpay.com/v1/page/orders#verifying-the-signature
https://razorpay.com/mobile/
https://github.com/razorpay/razorpay-android-sample-app
But not getting any solution.
Menifest File
<meta-data
android:name="com.razorpay.ApiKey"
android:value="rzp_test_PLbERPkkqGZkOF" />
build.gradle
api 'com.razorpay:checkout:1.5.4'
I got an error
{"code":"BAD_REQUEST_ERROR","description":"ay_order_id is not a valid id"}
I am trying with this code
public class CheckoutActivity extends AppCompatActivity implements View.OnClickListener, PaymentResultWithDataListener {
private static final String TAG = CheckoutActivity.class.getSimpleName();
Button mCheckOutView;
String OrderId = "";
String signature = "";
String order_id = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_method);
Checkout.preload(getApplicationContext());
mCheckOutView = findViewById(R.id.check_out);
mCheckOutView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == mCheckOutView) {
startPayment();
}
}
public void startPayment() {
/*
You need to pass current activity in order to let Razorpay create CheckoutActivity
*/
final Activity activity = this;
final Checkout co = new Checkout();
try {
JSONObject options = new JSONObject();
options.put("name","Test");
options.put("description", getString(R.string.app_name));
options.put("key", getString(R.string.api_key));
options.put("order_id","razorpay_order_id");
options.put("signature","razorpay_signature");
options.put("currency", "INR");
options.put("amount", 100);
JSONObject preFill = new JSONObject();
preFill.put("email", "test#gmail.com");
preFill.put("contact", "9999999999");
options.put("prefill", preFill);
JSONObject notesData=new JSONObject();
notesData.put("Order Id","order123");
notesData.put("address","Test Address");
options.put("notes", notesData);
JSONObject theme=new JSONObject();
theme.put("color","#738598");
theme.put("emi_mode",true);
options.put("theme", theme);
co.open(activity, options);
} catch (Exception e) {
Toast.makeText(activity, "Error in payment: " + e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public void onPaymentSuccess(String s, PaymentData paymentData) {
String paymentId = paymentData.getPaymentId();
String signature = paymentData.getSignature(); // got null
String orderId = paymentData.getOrderId(); // got null
}
#Override
public void onPaymentError(int i, String s, PaymentData paymentData) {
Log.e(TAG,s); //error {"code":"BAD_REQUEST_ERROR","description":"ay_order_id is not a valid id"}
}
}
If i remove these 2 lines then this error not comes.
options.put("order_id","razorpay_order_id");
options.put("signature","razorpay_signature");
But paymentData.getSignature() and paymentData.getOrderId() is null.
Any help will be appreciated.
options.put("order_id","**razorpay_order_id**");
you need to generate this order_id from razorpay Order_ID API, only after this order_id which comes as a response from the API you would be able to process smoothly. After getting this Order_id from API, send it in above code in value (in place of razorpay_order_id)
options.put("signature","razorpay_signature");
This is not required in request. This will be generated at your server and will be used when a response is received in PaymentResultWithDataListener function. Read Signature generation method in official Documentation here : https://razorpay.com/docs/payment-gateway/android-integration/standard/
According to the official docs, by the time you start the checkout, you get the order_id when the merchant's backend starts an order with the RazorPay backend.
See the diagram here`.
As for the signature, according with the docs that's not something you put but something that comes from server responses and which you have to validate on your end. Check this
want to start development with AWS IOT using Android app
I am seeking for example for IOT in android. need to start basic configuration on AWS console and android app. i already tested temperature demo but didn't get any clue from that! need a basic steps on shadow, policy , role. how to configure them step by step and use of cognito.
below getshadow() method is called onCreate , need to update value on real time basis not ony onCreate.
public void getShadows() {
GetShadowTask getControlShadowTask = new GetShadowTask("TemperatureControl");
getControlShadowTask.execute();
}
private class GetShadowTask extends AsyncTask<Void, Void, AsyncTaskResult<String>> {
private final String thingName;
public GetShadowTask(String name) {
thingName = name;
}
#Override
protected AsyncTaskResult<String> doInBackground(Void... voids) {
try {
GetThingShadowRequest getThingShadowRequest = new GetThingShadowRequest()
.withThingName(thingName);
GetThingShadowResult result = iotDataClient.getThingShadow(getThingShadowRequest);
// Toast.makeText(getApplication(),result.getPayload().remaining(),Toast.LENGTH_LONG).show();
byte[] bytes = new byte[result.getPayload().remaining()];
result.getPayload().get(bytes);
String resultString = new String(bytes);
return new AsyncTaskResult<String>(resultString);
} catch (Exception e) {
Log.e("E", "getShadowTask", e);
return new AsyncTaskResult<String>(e);
}
}
#Override
protected void onPostExecute(AsyncTaskResult<String> result) {
if (result.getError() == null) {
JsonParser parser=new JsonParser();
JsonObject jsonObject= (JsonObject) parser.parse(result.getResult());
response=result.getResult();
setPoint=jsonObject.getAsJsonObject("state").getAsJsonObject("reported")
.get("current_date").getAsString();
textView.setText(setPoint);
// Toast.makeText(getApplication(),setPoint,Toast.LENGTH_LONG).show();
Log.i(GetShadowTask.class.getCanonicalName(), result.getResult());
} else {
Log.e(GetShadowTask.class.getCanonicalName(), "getShadowTask", result.getError());
Toast.makeText(getApplication(),result.getError().toString(),Toast.LENGTH_LONG).show();
}
}
}
UPDATE
Thing Shadow
{
"desired": {
"welcome": "aws-iot"
},
"reported": {
"welcome": "aws-iot",
"current_date": "06-Sep-2017 1:26:40 PM"
}
}
AWS has provided a complete Github repo of Android samples. In the samples do the PubSubWebSocket to connect, subscribe and publish the data to the shadow.
If you have a closer look into the PubSubWebSocket example you will find a detailed information on how to to make a thing policy and role. It cannot be more concise and clear than that.
For understanding and using Cognito follow AmazonCognitoAuthDemo example to make the identity pool and use it in the PubSubWebSocket example.
To get a better understanding of roles and Cognito. Please read the AWS documentation.
Update:
In the IoT thing policy did you give appropriate permissions to connect, subscribe and publish. The option can be found in AWS IoT->Security->Policy->Create Policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:*",
"Resource": "arn:aws:iot:us-east-2:293751794947:topic/replaceWithATopic"
}
]
}
The above policy gives all access to the user. Also, make sure your pool which you created is for unauthenticated users.
To get the changes to the shadow type the following in the sample android(WebSocketAwsPubSub) edit box $aws/things/thing_name/shadow/update/accepted
And to publish the data to the shadow type $aws/things/thing_name/shadow/update
Update 2:
Android Code where you will receive the reported messaged. Its suscribing to the device. Its the copy of the snippet from PubSubWebSocketSample.
public void AwsSubscribe(){
final String topic = "$aws/things/D1/shadow/update/accepted";
Log.d(LOG_TAG, "topic = " + topic);
try {
mqttManager.subscribeToTopic(topic, AWSIotMqttQos.QOS0,
new AWSIotMqttNewMessageCallback() {
#Override
public void onMessageArrived(final String topic, final byte[] data) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
String message = new String(data, "UTF-8");
Log.d(LOG_TAG, "Message arrived:");
Log.d(LOG_TAG, " Topic: " + topic);
Log.d(LOG_TAG, " Message: " + message);
tvLastMessage.setText(message);
} catch (UnsupportedEncodingException e) {
Log.e(LOG_TAG, "Message encoding error.", e);
}
}
});
}
});
} catch (Exception e) {
Log.e(LOG_TAG, "Subscription error.", e);
}
}
If you want to create a topic, just change the value of this variable final String topic = "YOUR TOPIC" then subscribe to it by using the sample code.
I need a working example for a custom API for Microsoft Azure App Service.
I could not get any useful or working information/examples for that, or they just show each time different approaches which are outdated?!?!
For now I have a working table controller which gets information from database and returns it back to my Android client. Now I need to define a custom API Controller to get a string back. In the examples they are all sending an object to the service in order to get an object back. I do not want to send anything to the API, just retrieve some information back from a GET Request.
Regards
// EDIT - Added / edited client / server code to Post a String.
You can use the following code to do a GET request on the auto generated API controller Visual Studio creates (ValuesController).
private void getStringFromAzure() throws MalformedURLException {
// Create the MobileService Client object and set your backend URL
String yourURL = "https://yourApp.azurewebsites.net/";
MobileServiceClient mClient = new MobileServiceClient(yourURL, this);
// Your query pointing to yourURL/api/values
ListenableFuture<JsonElement> query = mClient.invokeApi("values", null, GetMethod, null);
// Callback method
Futures.addCallback(query, new FutureCallback<JsonElement>() {
#Override
public void onSuccess(JsonElement jsonElement) {
// You are expecting a String you can just output the result.
final String result = jsonElement.toString();
// Since you are on a async task, you need to show the result on the UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFailure(Throwable throwable) {
Log.d(TAG, "onFailure: " + throwable.getMessage());
}
});
}
public void sendString(final String someString) throws MalformedURLException {
// Your query pointing to /api/values/{String}
ListenableFuture<JsonElement> query = mClient.invokeApi("values/" + someString, null, PostMethod, null);
// Callback method
Futures.addCallback(query, new FutureCallback<JsonElement>() {
#Override
public void onSuccess(JsonElement jsonElement) {
// You are expecting a String you can just output the result.
final String result = jsonElement.toString();
}
#Override
public void onFailure(Throwable throwable) { }
});
}
The backend API: (ValuesController)
{
// Use the MobileAppController attribute for each ApiController you want to use
// from your mobile clients
[MobileAppController]
public class ValuesController : ApiController
{
// GET api/values
public string Get()
{
return "Hello World!";
}
// POST api/values/inputString
public string Post(string inputString)
{
return inputString;
}
}
}
You can also send parameters along in the following way:
List<Pair<String, String>> parameters = new ArrayList<>();
parameters.add(new Pair<>("name", "John"));
parameters.add(new Pair<>("password", "fourwordsalluppercase"));
ListenableFuture<JsonElement> query = client.invokeApi("yourAPI", PostMethod, parameters);
Or as json in the body:
JsonObject body = new JsonObject();
body.addProperty("currentPassword", currentPassword);
body.addProperty("password", password);
body.addProperty("confirmPassword", confirmPassword);
ListenableFuture<JsonElement> query = mClient.invokeApi("yourAPI", body, PostMethod, null);
Based on my understanding, I think there are two parts in your question which include as below. And I think you can separately refer to two sections to get the answers and write your own example.
How to define a custom API on Azure Mobile App to retrieve data from database? Please refer to the section Custom APIs to know how to do with Azure Mobile App backend.
How to call a custom API from Android App? Please refer to the section How to: Call a custom API to know how to do with Android SDK.
I'm developing an app using the ArcGIS Runtime SDK for Android. I'm accessing tiled basemaps from arcgis.com using the following code which works fine.
UserCredentials creds = new UserCredentials();
creds.setUserToken("token", "referer");
String mapUrlUsaTopo = "https://services.arcgisonline.com/arcgis/rest/services/USA_Topo_Maps/MapServer";
mBasemapLayer = new ArcGISTiledMapServiceLayer(mapUrlUsaTopo, creds);
But... when I attempt to download the map tiles for offline use I get the following error:
com.esri.core.io.EsriSecurityException: Message: Unable to generate token. Details: 'username' must be specified., 'password' must be specified.
Here's the download code:
String tileUrlUsaTopo = "https://tiledbasemaps.arcgis.com/arcgis/rest/services/USA_Topo_Maps/MapServer";
final ExportTileCacheTask exportTileCacheTask = new ExportTileCacheTask(tileUrlUsaTopo, creds);
Is the only option hard coding the username and password?
Andrew from Esri support was very helpful. To do "application" authentication (without a user name and password) using your app id and secret key you need something like the code below. However, there is a bug (BUG-000092420) in the android sdk and the code below does not work at the present time. I'm being told that the fix may make in into the Quartz final release.
private class AppLoginTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Log.d("MyApp", "AppLoginTask");
Portal p = new Portal("https://www.arcgis.com", null);
try {
p.doOAuthAppAuthenticate(APP_SECRET, APP_ID, new CallbackListener<Portal>() {
#Override
public void onCallback(Portal portal) {
Log.d("MyApp", "login callback");
//mCreds = new UserCredentials();
mCreds = portal.getCredentials();
setMapDataMode(MapDataMode.ONLINE);
}
#Override
public void onError(Throwable throwable) {
Log.e("MyApp", "login error");
}
});
} catch (Exception e) {
Log.d("MyApp", "login exception");
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void results) {
Log.d("MyApp", "login post execute");
//setMapDataMode(MapDataMode.ONLINE);
}
}
I am curious if I can get some help with Open Graph since I can't seem to make any sense out of the Facebook API that I have read.
Right now I have setup my Open Graph Application on Facebook. It has been approved. I am trying to submit my "objects" via the bundle params but I am curious how I setup a bundle param object like the following. Where myObject has multiple values associated with it.
Bundle params = new Bundle();
param.putString("myObject", ""); // My object has multiple values
I guess I really need to figure out how you submit something in the Bundle that has multiple properties associated with it. If anyone has any insight on this please help me out.
At first I had tried something like this.
Bundle myObject = new Bundle();
myObject("property1", "property1Value");
myObject("property2", "property2Value");
myObject("property3", "property3Value");
Bundle params = new Bundle();
params.putString("myObject", myObject);
But in hindsight I figured out why this wouldn't work.
Edit 1
Maybe this will shed some light. Keep in mind this is an Open Graph action which is not a part of the Graph API.
//Build recipe
JSONObject recipe = new JSONObject();
recipe.put("type", "myappns:recipe");
recipe.put("recipe_name", "Thai Island");
recipe.put("cook_time", "1hr. 30min.");
//Build cookbook
JSONObject cookbookParams = new JSONObject();
cookbookParams.put("type", "myappns:book");
cookbookParams.put("title", "Hot & Spicy");
cookbookParams.put("description", "This book consists of hot & spicy foods");
cookbookParams.put("recipes", new JSONArray().put(recipe));
Bundle params = new Bundle();
params.putString("cookbook", cookbookParams.toString());
AsyncFacebookRunner request = new AsyncFacebookRunner(facebook);
request.request("me/myappns:used", params, "POST", new addToTimelineListener(), null);
Here is a question though as I have been digging more into the Open Graph system. I believe I need to actually have a website setup somewhere, is this correct? I was lead to believe through the introductory documentation of Open Graph that I could create and use my Facebook application on Android without the need of any website. That is use the Open Graph system, I know I can use the application to post feeds and what not which I have done successfully.
Thanks again!
Edit 2
Dont even worry about replying I understand what my problem was now...I have to have a website somewhere hosting a Facebook application for the posts to link back too. Makes perfect sense, I haven't seen where the documentation was very direct about this...oh well now I know.
I use this code to publish on wall for multiple object properties.
private void publishPhoto(String imageURL) {
Log.d("FACEBOOK", "Post to Facebook!");
try {
JSONObject attachment = new JSONObject();
attachment.put("message",text);
attachment.put("name", "MyGreatAndroidAppTest");
attachment.put("href", "http://stackoverflow.com/users/909317/sunny");
attachment.put("description","Test Test TEst");
JSONObject media = new JSONObject();
media.put("type", "image");
media.put("src", imageURL);
media.put("href",imageURL);
attachment.put("media", new JSONArray().put(media));
JSONObject properties = new JSONObject();
JSONObject prop1 = new JSONObject();
prop1.put("text", "Text or captionText to Post");
prop1.put("href", imageURL);
properties.put(text, prop1);
// u can make any number of prop object and put on "properties" for ex: //prop2,prop3
attachment.put("properties", properties);
Log.d("FACEBOOK", attachment.toString());
Bundle params = new Bundle();
params.putString("attachment", attachment.toString());
facebook.dialog(MyProjectActivity.this, "stream.publish", params, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("FACEBOOK", "Dialog Success! post_id=" + postId);
Toast.makeText(MyProjectActivity.this, "Successfully shared on Facebook!", Toast.LENGTH_LONG).show();
} else {
Log.d("FACEBOOK", "No wall post made");
}
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
} catch (JSONException e) {
Log.e("FACEBOOK", e.getLocalizedMessage(), e);
}
}
To see a complete example look at the wishlist example.
A complete example for Android is included. The package includes the files to be uploaded on the server and a readme file that explain how to set up all the stuff on the open graph panel.