Post method not working in AsyncHttpClient in Android - java

Hi I am developing android app using java restfull webservices Here I am getting one issue in calling web service through post method when I use client.post("") my all values get null while calling webservice. I dont know why it is happening. And when I use client.get("") its working properly.And I am able to do register properly through client.get. But I want to use client.post Please help me let me know what I am mistaking.
public void registerUser(View view){
String name = nameET.getText().toString();
String email = emailET.getText().toString();
String password = pwdET.getText().toString();
RequestParams params = new RequestParams();
if(Utility.isNotNull(name) && Utility.isNotNull(email) && Utility.isNotNull(password)){
if(Utility.validate(email)){
control
params.put("name", name);
params.put("username", email);
params.put("password", password);
// Invoke RESTful Web Service with Http parameters
invokeWS(params);
}
}
public void invokeWS(RequestParams params){
System.out.println("params===== "+params);
prgDialog.show();
**AsyncHttpClient client = new AsyncHttpClient();
client.post("http://localhost:8080/DemoForAndroid/register/doregister",params ,new AsyncHttpResponseHandler()** {
// When the response returned by REST has Http response code '200'
public void onSuccess(String response) {
// Hide Progress Dialog
System.out.println("response======= "+response);
prgDialog.hide();
try {
// JSON Object
JSONObject obj = new JSONObject(response);
// When the JSON response has status boolean value assigned with true
if(obj.getBoolean("status")){
// Set Default Values for Edit View controls
setDefaultValues();
// Display successfully registered message using Toast
Toast.makeText(getApplicationContext(), "You are successfully registered!", Toast.LENGTH_LONG).show();
}
// Else display error message
else{
errorMsg.setText(obj.getString("error_msg"));
Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
// When the response returned by REST has Http response code other than '200'
public void onFailure(int statusCode, Throwable error,
String content) {
// Hide Progress Dialog
prgDialog.hide();
// When Http response code is '404'
if(statusCode == 404){
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if(statusCode == 500){
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else{
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
System.out.println("Client======= "+client);
}
log file
01-28 12:10:26.307: W/KeyCharacterMap(106): No keyboard for id 0
01-28 12:10:26.307: W/KeyCharacterMap(106): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
01-28 12:11:33.238: I/System.out(274): params===== username=raju#mail.com&name=Raju &password=123456
01-28 12:11:33.328: D/dalvikvm(274): GC_FOR_MALLOC freed 5941 objects / 275504 bytes in 57ms
01-28 12:11:33.378: I/System.out(274): Client======= com.loopj.android.http.AsyncHttpClient#44ef5638
01-28 12:11:33.578: I/System.out(274): response======= {"tag":"register","status":false,"error_msg":"Error occured"}
01-28 12:11:33.678: I/ARMAssembler(58): generated scanline__00000077:03515104_00000000_00000000 [ 33 ipp] (47 ins) at [0x360af8:0x360bb4] in 405396 ns
01-28 12:11:33.745: W/InputManagerService(58): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#450aa070
Restful Webservice code
#Path("/register")
public class Register {
// HTTP Get Method
User usr = new User();
#POST
// Path: http://localhost/<appln-folder-name>/register/doregister
#Path("/doregister")
// Produces JSON as response
#Produces(MediaType.APPLICATION_JSON)
// Query parameters are parameters: http://localhost/<appln-folder-name>/register/doregister?name=pqrs&username=abc&password=xyz
public String doLogin(#QueryParam("name") String name, #QueryParam("username") String uname, #QueryParam("password") String pwd){
String response = "";
System.out.println("Inside doLogin "+uname+" "+pwd);
int retCode = registerUser(name, uname, pwd);
System.out.println("ret code= "+retCode);
if(retCode == 0){
response = Utitlity.constructJSON("register",true);
}else if(retCode == 1){
response = Utitlity.constructJSON("register",false, "You are already registered");
}else if(retCode == 2){
response = Utitlity.constructJSON("register",false, "Special Characters are not allowed in Username and Password");
}else if(retCode == 3){
response = Utitlity.constructJSON("register",false, "Error occured");
}
return response;
}
private int registerUser(String name, String uname, String pwd){
System.out.println("Inside checkCredentials");
System.out.println("name= "+name);
System.out.println("uname= "+uname);
System.out.println("pwd= "+pwd);
int result = 3;
if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
try {
System.out.println("add user---------------");
/* if(DBConnection.insertUser(name, uname, pwd)){*/
usr.setName(name);
usr.setUsername(uname);
usr.setPassword(pwd);
new UserDao().addUser(usr);
System.out.println("RegisterUSer if");
result = 0;
/* }*/
} /*catch(SQLException sqle){
System.out.println("RegisterUSer catch sqle");
//When Primary key violation occurs that means user is already registered
if(sqle.getErrorCode() == 1062){
result = 1;
}
//When special characters are used in name,username or password
else if(sqle.getErrorCode() == 1064){
System.out.println(sqle.getErrorCode());
result = 2;
}
}*/
catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Inside checkCredentials catch e ");
result = 3;
}
}else{
System.out.println("Inside checkCredentials else");
result = 3;
}
return result;
}
}
webservice log
Inside doLogin null null
Inside checkCredentials
name= null
uname= null
pwd= null
Inside isNotNull
Inside checkCredentials else
ret code= 3

replace #QueryParam with #FormParam in doLogin()
i think #QueryParam will be more like a GET param expected.

Related

Check if JSON response contains certain value

So I'm building an Android app in Android Studio for an excisting webpage with a login feature. I connected the app succesfully to the websites database already and I can login and get a response from the server. The app is looking for an error value in the response, but the response contains no error value.
This is the code in my app:
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
This is the response the server gives when the login was succesfull:
Login Response: {"howislife":1,"rekeningnummer":"212220","soortuser":"student","datum":"05 Sep 2017"}
So when the login was succesfull it says "howislife:1", when the password or username is incorrect it says "howislife:2" or "howislife:3". So the code in my Android app needs to check what value "howislife" is. How can I do that? Thanks in advance!
Try this code,
int howislife = (!jsonObjects.isNull("howislife")) ?
jsonObjects.optInt("howislife") : 0;
if (howislife == 1) {
//login sucess
} else {
//login failed
}
I assume your api gives response always with those parameters and if the response comes empty or null then check for it before converting to JSONObject, then you could try below code, it will work.
JSONObject jObj = new JSONObject(response);
if(jObj.getInt("howislife")==1){
System.out.println("Login success");
}else{
System.out.println("Login fail");
}
There is a function "has()" to check keys for JSONObject in Android.
boolean has (String name)
Returns true if this object has a mapping for name. The mapping may be NULL.
More details:
https://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
I solved it using this code already, thanks!
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
int login1 = jObj.getInt("howislife");
System.out.println(login1);
//Check for error node in json
if (login1 == 1) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else if(login1 == 2) {
Toast.makeText(getApplicationContext(), "Wachtwoord verkeerd", Toast.LENGTH_LONG).show();
} else if(login1 == 3) {
Toast.makeText(getApplicationContext(), "Gebruikersnaam of/en wachtwoord verkeerd", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Er is iets fout gegaan, probeer opnieuw.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}

org.json.JSONException: No value for id - IMPOSSIBLE TO SOLVE

http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-2/
Hi,
This is a tutorial about building a group chat app using socket programming. This app allows us to chat between multiple devices like android mobiles and web.
I want to send more than one "String" at a time to the server. I'm having trouble figuring that out.
The link to the tutorial where I downloaded the code is pasted above. I've already made the dynamic web page and I have it hosted on eapps.com At the very bottom of the this email is the edited code for the app. If you click the link above, you can see how I changed it.
The way it works is..
A web socket is created using WebSocketClient class and it has all the callback methods like onConnect, onMessage and onDisconnect.
In onMessage method parseMessage() is called to parse the JSON received from the socket server.
In parseMessage() method, the purpose of JSON is identified by reading the flag value.
When a new message is received, the message is added to list view data source and adapter.notifyDataSetChanged() is called to update the chat list.
sendMessageToServer() method is used to send the message from android device to socket server.
playBeep() method is called to play device’s default notification sound whenever a new message is received.​
When you click the btnSend. it uses this method from the UtilsXd class. I've changed it a little in an attempt to pass an extra value.
public String getSendMessageJSONXD(String message, String whichPicIndex) {
String json = null;
try {
JSONObject jObj = new JSONObject();
jObj.put("flag", FLAG_MESSAGE);
jObj.put("sessionId", getSessionId());
jObj.put("message", message);
jObj.put("id", id);
json = jObj.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
First of all, what I still don't understand is, where did the values for
String sessionId = jObj.getString("sessionId");
and
String onlineCount = jObj.getString("onlineCount");​
from this method
private void parseMessage(final String msg, String idINDEX) {
come from.
They were't added in the JSON object created in the UtilsXD class so how are they created?
That's not the problem I'm having. This is.
superString is the value I want to pass to dictate which picture to show.
superString = (sharedPrefs.getString("prefSyncAvatar", "1"));​
You can change your picture in from the settings.
When a message is received, a switch/case statement changes the picture of/ for the message received according to the value passed by superString.
I should be able to sit there and just receive messages, and whatever number the user passes, the profilePicture should be set according to that number.
Here's where the problem begins.
This constructer builds a message based of the message that's just been parsed.
// Message m = new Message(fromName, message, isSelf);
Message m = new Message(fromName, message, isSelf, id, name,
image, status, profilePic, timeStamp, url);
In this method.
private void parseMessage(final String msg, String idINDEX) {
I can pass an value to the string "id" excluding the JSON I need it to.
String id = idINDEX;​
this works,
String id = "0";
this works,
String id = utils.getPictureId();
this works,
String id = jObj.getString("id");
This doesn't work.
This is the error I'm getting.
org.json.JSONException: No value for id (this is the issue)
I've added the key/value pair
jObj.put("id", id);
in
public String getSendMessageJSONXD(String message, String whichPicIndex) {​
but it's not coming though to the message.
Here's where I think the problem is.
The method onMessage, isn't can't take an extra parameter because it's from a library project. And I can't find that method to make a new constructor.
#Override
public void onMessage(String message) {
Log.d(TAG, String.format("Got string message! %s", message));
parseMessage(message, superString);
}
#Override
public void onMessage(byte[] data) {
Log.d(TAG, String.format("Got binary message! %s",
bytesToHex(data)));
String hello = "99";
parseMessage(bytesToHex(data), superString);
}
/////// Here's the final code below ////////
// JSON flags to identify the kind of JSON response
private static final String TAG_SELF = "self", TAG_NEW = "new",
TAG_MESSAGE = "message", TAG_ID = "id", TAG_EXIT = "exit";
#SuppressWarnings("deprecation")
#SuppressLint({ "NewApi", "CutPasteId" })
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_chat);
showUserSettings();
getActionBar().setTitle("City Chat - Beta 1.3");
superString = (sharedPrefs.getString("prefSyncAvatar", "1"));
listView = (ListView) findViewById(R.id.list_view_messages);
feedItems = new ArrayList<FeedItem>();
// We first check for cached request
vollewStuff();
//
//
// THis is where this fun begins
btnSend = (Button) findViewById(R.id.btnSend);
inputMsg = (EditText) findViewById(R.id.inputMsg);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
utils = new UtilsXD(getApplicationContext());
// Getting the person name from previous screen
Intent i = getIntent();
name = i.getStringExtra("name");
Integer.parseInt((sharedPrefs.getString("prefSyncAvatar", "1")));
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Sending message to web socket server
sendMessageToServer(utils.getSendMessageJSONXD(inputMsg
.getText().toString(), superString), superString);
utils.storePictureId((sharedPrefs.getString("prefSyncAvatar",
"1")));
// Clearing the input filed once message was sent
inputMsg.setText("");
}
});
listMessages = new ArrayList<Message>();
adapter = new MessagesListAdapter(this, listMessages, feedItems);
listViewMessages.setAdapter(adapter);
/**
* Creating web socket client. This will have callback methods
* */
client = new WebSocketClient(URI.create(WsConfig.URL_WEBSOCKET
+ URLEncoder.encode(name)), new WebSocketClient.Listener() {
#Override
public void onConnect() {
}
/**
* On receiving the message from web socket server
* */
#Override
public void onMessage(String message) {
Log.d(TAG, String.format("Got string message! %s", message));
parseMessage(message, superString);
// parseMessage(message,
// (sharedPrefs.getString("prefSyncAvatar", "1")));
}
#Override
public void onMessage(byte[] data) {
Log.d(TAG, String.format("Got binary message! %s",
bytesToHex(data)));
String hello = "99";
parseMessage(bytesToHex(data), superString);
// Message will be in JSON format
// parseMessage(bytesToHex(data),
// (sharedPrefs.getString("prefSyncAvatar", "1")));
}
/**
* Called when the connection is terminated
* */
#Override
public void onDisconnect(int code, String reason) {
String message = String.format(Locale.US,
"Disconnected! Code: %d Reason: %s", code, reason);
showToast(message);
//
// clear the session id from shared preferences
utils.storeSessionId(null);
}
#Override
public void onError(Exception error) {
Log.e(TAG, "Error! : " + error);
// showToast("Error! : " + error);
showToast("Are you sure you want to leave?");
}
}, null);
client.connect();
}
/**
* Method to send message to web socket server
* */
private void sendMessageToServer(String message, String id) {
if (client != null && client.isConnected()) {
client.send(message);
client.send(id);
}
}
/**
* Parsing the JSON message received from server The intent of message will
* be identified by JSON node 'flag'. flag = self, message belongs to the
* person. flag = new, a new person joined the conversation. flag = message,
* a new message received from server. flag = exit, somebody left the
* conversation.
* */
private void parseMessage(final String msg, String idINDEX) {
try {
jObj = new JSONObject(msg);
// JSON node 'flag'
String flag = jObj.getString("flag");
String id = idINDEX;
// if flag is 'self', this JSON contains session id
if (flag.equalsIgnoreCase(TAG_SELF)) {
String sessionId = jObj.getString("sessionId");
// Save the session id in shared preferences
utils.storeSessionId(sessionId);
Log.e(TAG, "Your session id: " + utils.getSessionId());
} else if (flag.equalsIgnoreCase(TAG_NEW)) {
// If the flag is 'new', new person joined the room
String name = jObj.getString("name");
String message = jObj.getString("message");
// number of people online
String onlineCount = jObj.getString("onlineCount");
showToast(name + message + ". Currently " + onlineCount
+ " people online!");
} else if (flag.equalsIgnoreCase(TAG_MESSAGE)) {
// if the flag is 'message', new message received
String fromName = name;
String message = jObj.getString("message");
String sessionId = jObj.getString("sessionId");
// switch (Integer.parseInt((sharedPrefs.getString(
// "prefSyncAvatar", "1"))))
boolean isSelf = true;
switch (Integer.parseInt(utils.getPictureId())) {
case 1:
profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatlion.png";
break;
case 2:
profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatmatt.png";
break;
case 3:
profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatroboman.png";
break;
case 4:
profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatalien.png";
break;
case 5:
profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatkitty.png";
break;
case 10:
profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatkitty.png";
break;
}
// Checking if the message was sent by you
if (!sessionId.equals(utils.getSessionId())) {
fromName = jObj.getString("name");
// profilePic = jObj.getString("profilePic");
//
//
//
//
jObj.getString("message");
isSelf = false;
profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatalien.png";
}
// profilePic =
// "http://clxxxii.vm-host.net/clxxxii/citychatlion.png";
Integer.parseInt(utils.getPictureId());
String name = "clxxxii";
String image = "http://i.huffpost.com/gen/1716876/thumbs/o-ATLANTA-TRAFFIC-facebook.jpg";
String status = "status";
String timeStamp = "1403375851930";
String url = "url";
// Message m = new Message(fromName, message, isSelf);
Message m = new Message(fromName, message, isSelf, id, name,
image, status, profilePic, timeStamp, url);
// Appending the message to chat list
appendMessage(m);
} else if (flag.equalsIgnoreCase(TAG_EXIT)) {
// If the flag is 'exit', somebody left the conversation
String name = jObj.getString("name");
String message = jObj.getString("message");
showToast(name + message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
///////// I've updated the socket server from the first project. /////// I've added the JSON value "id" successfully /// But I how do I change the value without having to type in "5" please see below..
//
This is the JSONutilty method I changed.
//
public String getSendAllMessageJson(String sessionId, String fromName,
String message, String photoId) {
String json = null;
try {
JSONObject jObj = new JSONObject();
jObj.put("flag", FLAG_MESSAGE);
jObj.put("sessionId", sessionId);
jObj.put("name", fromName);
jObj.put("message", message);
jObj.put("id", photoId);
json = jObj.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
}
This is the method that is being used by SocketServer. I can successfully send a message from this activity, to the utility method to send over the network.
// Normal chat conversation message
json = jsonUtils //
.getSendAllMessageJson(sessionId, name, message, "5");
How can I retrieve a value sent over the network to place in spot where I have "5" instead of hard coding it?
Thanks!!!
jobj doesn't have the value id. Example of the JSON object looks like this:
{
"message": " joined conversation!",
"flag": "new",
"sessionId": "4",
"name": "Ravi Tamada",
"onlineCount": 6
}
(as shown in the part1 of the same tutorial).
That solves the first issue of onlineCount and sessionId.
Thanks #miselking, you where correct, The server was missing the JSON string "id". To actually solve the problem of post.
"I want to send more than one "String" at a time to the server. I'm having trouble figuring that out."
This is how you do it.
Step 1)
Adding the string photoId to the method
public String getSendAllMessageJson(String sessionId, String fromName,
String message, String photoId) {
String json = null;
try {
JSONObject jObj = new JSONObject();
jObj.put("flag", FLAG_MESSAGE);
jObj.put("sessionId", sessionId);
jObj.put("name", fromName);
jObj.put("message", message);
jObj.put("id", photoId);
json = jObj.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
}
Step 2)
Add the string to the correct sting to the method.
String json = null;
json = jsonUtils
.getSendAllMessageJson(sessionId, name, message,
photoId);
Step 3) Parse the JSON
try {
JSONObject jObj = new JSONObject(message);
msg = jObj.getString("message");
photoId = jObj.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}

facebook like returns Error finding the requested story

I want to use FB SDK to do a like on a postId.
The post is in a 3rd part fb page.
Usually it works. But when I try to do like few days after the post was created I get this response:
Error finding the requested story
here is my code:
Request request = new Request(session,
takeFromPublicMacrosOrServer(currentOffer.fbPostId)
+ "/likes", null, HttpMethod.POST,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Request complete
if (response.getError() == null) {
UnlockRequestToServer unlockRequestToServer = new UnlockRequestToServer(
mOffersListActivity,
PublicMacros.TYPE_UNLOCK_FB_LIKE,
currentOffer.fbPostId);
} else {
final String errorMsg = "error: "
+ response.getError().toString();
Log.e(MyLogger.TAG, errorMsg);
mToaster.showToastInUiThread(errorMsg);
}
String re = response.toString();
}
});
request.executeAsync();

Returning success on query successfully in PHP to java

I need to check if the username is already present in the database.If so then only Login. After login,I need a response to be sent from php file to java class saying success.
When I access the result array in my java file using Json,it is giving NULL though the Username is already present in Database.
Any Help?
I am using the below Php and java code
<?php
include("db_config.php");
$myusername = $_GET['username'];
$mypassword = $_GET['password'];
$sql="SELECT id FROM tablename WHERE username='$myusername' and password='$mypassword'";
echo $sql;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
if($count==1)
{
$result['login'] == 'success';
}
else
{
$result['login'] == 'failed';
}
echo json_encode($result);
This is my Java code
btnLogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
username= textFieldUserName.getText().toString();
password = textFieldPassword.getText().toString();
// discount = textFieldDiscount.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username",username));
params.add(new BasicNameValuePair("password",password ));
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
try {
status = json.getString(TAG_SUCCESS);
System.out.println(" status is "+status);
if(status.equalsIgnoreCase("success"))
{
System.out.println("Login success");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Also,I tried
if(response.getStatusLine().getStatusCode()==200)
which returns 200 if OK from the from the server.
[Edit: Code ReFormation]
use this code for java
JSONObject json = (JSONObject)jParser.makeHttpRequest(url_all_products, "GET", params);
try {
//status = json.getString(TAG_SUCCESS);
String status = (String) json.get("login");
System.out.println(" status is "+status);
if(status.equalsIgnoreCase("success"))
{
System.out.println("Login success");
}
}

Permissions Error - Trying to get friends using android facebook sdk

I am trying to add a feature to my android app that allows users to "checkin" with other people tagged to the checkin.
I have the checkins method working no problem and can tag some one by adding the user ID as a parameter (see code below)
public void postLocationTagged(String msg, String tags, String placeID, Double lat, Double lon) {
Log.d("Tests", "Testing graph API location post");
String access_token = sharedPrefs.getString("access_token", "x");
try {
if (isSession()) {
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", access_token);
parameters.putString("place", placeID);
parameters.putString("Message",msg);
JSONObject coordinates = new JSONObject();
coordinates.put("latitude", lat);
coordinates.put("longitude", lon);
parameters.putString("coordinates",coordinates.toString());
parameters.putString("tags", tags);
response = mFacebook.request("me/checkins", parameters, "POST");
Toast display = Toast.makeText(this, "Checkin has been posted to Facebook.", Toast.LENGTH_SHORT);
display.show();
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}
This works fine (I've posted it in case it is of help to anyone else!), the problem i am having is i am trying to create a list of the users friends so they can select the friends they want to tag. I have the method getFriends (see below) which i am then going to use to generate an AlertDialog that the user can select from which in turn will give me the id to use in the above "postLocationTagged" method.
public void getFriends(CharSequence[] charFriendsNames,CharSequence[] charFriendsID, ProgressBar progbar) {
pb = progbar;
try {
if (isSession()) {
String access_token = sharedPrefs.getString("access_token", "x");
friends = charFriendsNames;
friendsID = charFriendsID;
Log.d(TAG, "Getting Friends!");
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", access_token);
response = mFacebook.request("me/friends", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}
When i look at the response in the log it reads:
"got responce: {"error":{"type":"OAuthException", "message":"(#200) Permissions error"}}"
I have looked through the graphAPI documentation and searched for similar questions but to no avail! I'm not sure if i need to request extra permissions for the app or if this is something your just not allowed to do! Any help/suggestions would be greatly appreciated.
You might need the following permissions:
user_checkins
friends_checkins
read_friendlists
manage_friendlists
publish_checkins
Check the related ones from the API docs. Before that, make sure that which line causes this permission error and try to fix it.
The solution is to implement a RequestListener when making the request to the Facebook graph API. I have the new getFriends() method (see below) which uses the AsyncGacebookRunner to request the data.
public void getFriends(CharSequence[] charFriendsNames,String[] sFriendsID, ProgressBar progbar) {
try{
//Pass arrays to store data
friends = charFriendsNames;
friendsID = sFriendsID;
pb = progbar;
Log.d(TAG, "Getting Friends!");
//Create Request with Friends Request Listener
mAsyncRunner.request("me/friends", new FriendsRequestListener());
} catch (Exception e) {
Log.d(TAG, "Exception: " + e.getMessage());
}
}
The AsyncFacebookRunner makes the the request using the custom FriendsRequestListener (see below) which implements the RequestListener class;
private class FriendsRequestListener implements RequestListener {
String friendData;
//Method runs when request is complete
public void onComplete(String response, Object state) {
Log.d(TAG, "FriendListRequestONComplete");
//Create a copy of the response so i can be read in the run() method.
friendData = response;
//Create method to run on UI thread
FBConnectActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
//Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
//Get the JSONArry from our response JSONObject
JSONArray friendArray = json.getJSONArray("data");
//Loop through our JSONArray
int friendCount = 0;
String fId, fNm;
JSONObject friend;
for (int i = 0;i<friendArray.length();i++){
//Get a JSONObject from the JSONArray
friend = friendArray.getJSONObject(i);
//Extract the strings from the JSONObject
fId = friend.getString("id");
fNm = friend.getString("name");
//Set the values to our arrays
friendsID[friendCount] = fId;
friends[friendCount] = fNm;
friendCount ++;
Log.d("TEST", "Friend Added: " + fNm);
}
//Remove Progress Bar
pb.setVisibility(ProgressBar.GONE);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Feel free to use any of this code in your own projects, or ask any questions about it.
You can private static final String[] PERMISSIONS = new String[] {"publish_stream","status_update",xxxx};xxx is premissions

Categories

Resources