Jsoup symbol error - java

I'm writing an IRC bot that is supposed to grab the artist name from this webpage http://whatthefuckshouldilistentorightnow.com/artist.php?artist=e&x=36&y=30 if someone types in !music. This is part of the code:
public void onMessage(String channel, String sender, String login, String hostname, String message) {
if (messageIC.startsWith("!music ")) {
String musicy = "id=\"artist\">"
try {
Document doc = Jsoup.connect("http://whatthefuckshouldilistentorightnow.com/artist.php?artist=e&x=36&y=30").get();
}
catch (IOException e){
}
String texty = doc.body().text(); // "An example link"
if (texty.contains(musicy)) {
String artisty = texty.substring(musicy);
int artsy1 = artisty.indexOf(">") + 1;
int artsy2 = artisty.indexOf("</div>");
artisty = artisty.substring(artsy1, artsy2);
sendMessage(channel, "artisty: " + artisty); // */
}
else {
sendMessage(channel, "Something went wrong.");
}
}
}
However, I am receiving an error message at String texty = doc.body().text();. The message is:
"cannot find symbol
symbol: method body()"
Any ideas as to what is wrong or how to improve on the code would be appreciated.

This is because you are declaring your var inside the try catch. You should either use it inside the try-catch or declare it before. Try this for example...
Document doc = null;
try {
doc = Jsoup.connect("http://whatthefuckshouldilistentorightnow.com/artist.php?artist=e&x=36&y=30").get();
} catch (IOException e){}
// rest of code

Related

FTPClient FTPFile details not available

I am trying to get the list of files from remote FTP server. The ftpClient.listFiles() returned null and I had to set setUnparseableEntries to true to get the list of files. Even then the list of files do not have any information like name and only information it has is rawlisting and others are null. So I cannot do ftpFile.getName. Here is the code
public FTPFile[] process() throws Exception {
String message = null;
FTPFile[] files = null;
FTPClient ftpClient = new FTPClient();
FTPClientConfig config = new FTPClientConfig();
config.setServerTimeZoneId("America/Chicago");
config.setUnparseableEntries(true);
ftpClient.configure(config);
if ( !connectToServer() ) return null;
if ( !changeDirectory() ) {
disconnectFromServer();
return null;
}
files = getListofFiles();
disconnectFromServer();
return files;
}
private boolean connectToServer() {
boolean result = true;
String message = null, url = null;
// attempt to connect to the target server
try {
url = fo.getServerInfo().getConnectionURL();
LOGGER.debug("Connecting to: " + url);
ftpClient.connect(fo.getServerInfo().getHostName(),
fo.getServerInfo().getHostPort());
ftpClient.enterLocalPassiveMode();
} catch(SocketException e) {
result = false;
message = "Could not connect to server at " + url;
} catch(IOException e) {
result = false;
message = "Could not connect to server at " + url;
}
if ( !result ) return result;
// After connection attempt, you should check the reply code to verify success.
Integer replyCode = ftpClient.getReplyCode();
if ( !FTPReply.isPositiveCompletion(replyCode) ) {
message = "Reply Code - " + replyCode.toString() + " is negative.";
try {
ftpClient.disconnect();
} catch(Exception e) {
message = "Could not disconnect cleanly from server.";
LOGGER.error(message);
}
} else {
message = "Reply Code - " + replyCode.toString() + " is positive.";
}
Boolean logonOk = false;
try {
logonOk = ftpClient.login(fo.getServerInfo().getUserName(),
fo.getServerInfo().getUserPassword());
} catch(IOException e) {
message = "IOException during logon attempt.";
LOGGER.error(message);
}
if ( !logonOk ) {
result = false;
message = "Logon UNsuccessful.";
} else {
message = "Logon successful.";
LOGGER.error(message);
executionMessageLog.add(message);
}
if ( !result ) return result;
// attempt to log onto the target server
return result;
}
Following method is trying to get the list of files. I could see the file name using listNames and also listFiles shows list of files but name, modified date are empty and only has value in rawlisting in the format "04-01-20 11:31AM 8975 test.TXT". So how to get the name and modified date from the raw listing and why I could not get FTPFile name using getName
private FTPFile[] getListofFiles(){
String message = null;
FTPFile[] files = null;
try {
String[] filenames = ftpClient.listNames(fileListInfo.getFilePath());
files = ftpClient.listFiles(); /*Has only rawlisting and others are null*/
}
catch(IOException e) {
message = "IOException during getListofFiles attempt:";
LOGGER.error(message);
executionMessageLog.add(message);
message = e.getMessage();
LOGGER.error(message);
executionMessageLog.add(message);
}
return files;
}
04-01-20 11:31AM 8975 test.TXT
That's quite unusual format. So it's possible that Apache Commons Net library cannot parse it with the default configuration.
You might need to explicitly specify one of the available parsers. The available parsers are in src\main\java\org\apache\commons\net\ftp\parser. Or if there's no parser specifically compatible with your server, you might need to build your own (you can base it on ConfigurableFTPFileEntryParserImpl).
Though actually, for an ad-hoc solution, easier would be that you just parse the "rawlisting" you already have.

HAPI HL7 Validation throws Exceptions

I am working on a Java endpoint that I intend to use for HL7 message validation. I have a basic app running that uses a variation of the standard HAPI HL7 validation example. If I pass in a valid message I get the "Success" response. If I pass in a invalid message I still get a "Success" response.
The only way I get an error response is if the HL7 is badly formatted and the PipeParser throws an exception. In that case it gets caught in the catch block.
What I want to see is if I pass in an invalid message that it actually gets validated and returns all the validation errors. But I don't ever actually see any validation. It either parses or crashes trying to parse.
What am I missing here?
HapiContext context = new DefaultHapiContext();
ValidationContext validationContext = ValidationContextFactory.defaultValidation();
context.setValidationContext(validationContext);
try
{
context.getParserConfiguration().setUnexpectedSegmentBehaviour(UnexpectedSegmentBehaviourEnum.THROW_HL7_EXCEPTION);
Message messageValidationResults = context.getPipeParser().parse(hl7Message);
SimpleValidationExceptionHandler handler = new SimpleValidationExceptionHandler(context);
handler.setMinimumSeverityToCollect(Severity.INFO);
Validator<Boolean> validator = context.getMessageValidator();
if (!validator.validate(messageValidationResults, handler))
{
if (handler.getExceptions().size() == 0)
{
hl7ValidationResult = "SUCCESS - Message Validated Successfully";
}
else
{
hl7ValidationResult = "ERROR - Found " + handler.getExceptions().size() + " problems\n\n";
for (Exception e : handler.getExceptions())
{
hl7ValidationResult += (e.getClass().getSimpleName() + " - " + e.getMessage()) + "\n";
}
}
}
}
catch (Exception e)
{
hl7ValidationResult = "ERROR - " + e.getMessage();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String sStackTrace = sw.toString();
hl7ValidationResult += "\n\n" + sStackTrace;
}
Please ignore the answer if do you think is not correct, I stopped to work with HL7 but, looking at my old project I have found this and maybe it can help you to find the solution of your problem:
{
DefaultValidationBuilder builder = new DefaultValidationBuilder() {
private static final long serialVersionUID = 1L;
#Override
protected void configure() {
super.configure();
forVersion(Version.V26);
}
};
HapiContext context = new DefaultHapiContext();
context.setValidationRuleBuilder(builder);
PipeParser hapiParser = context.getPipeParser();
try {
hapiParser.parse(hl7Message);
} catch (ca.uhn.hl7v2.HL7Exception e) {
// String error, String language, String requisitionNumber, String controlId, String processinId, String senderApplication, String senderFacility
errors.add(new HL7ValidationError(
"HAPI Validator error found: " + e.getMessage(),
extractor.accessPatientDirectly().getLanguage(),
extractor.accessPatientDirectly().getRequisitionNumber(),
extractor.accessPatientDirectly().getControlID(),
"",
extractor.accessPatientDirectly().getSenderApplication(),
extractor.accessPatientDirectly().getSenderFacility())
);
log.debug("HAPI Validator error found: " + e.getMessage());
}
try {
context.close();
}
catch (Exception ex) {
log.debug("Unable to close HapiContext(): " + ex.getMessage());
}
}
Basically I used hapiParser.parse(hl7Message); and catch the HL7Exception

java.io.EOFException: End of input at line 1 column 1 path $ in Gson parser

I'm parsing a JSON string by using Gson and Retrofit. I have this JSON string:
{"message":["Email has already been taken"]}
I get the below exception still and don't know why:
java.io.EOFException: End of input at line 1 column 1 path $
at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1393)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:549)
at com.google.gson.stream.JsonReader.peek(JsonReader.java:425)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:205)
at com.google.gson.TypeAdapter.fromJson(TypeAdapter.java:260)
at com.google.gson.TypeAdapter.fromJson(TypeAdapter.java:273)
People who know how to get the value of message field please help me.
BaseApiDto.java
public class BaseApiDto {
#SerializedName("message")
public String[] message;
public String getError() {
return message[0];
}
}
HandErrorUtils.java
public static void handleError(FragmentActivity activity, Throwable e) {
String msg = null;
if(e instanceof HttpException){
// Error message in json
Gson gson = new Gson();
TypeAdapter<BaseApiDto> adapter = gson.getAdapter(BaseApiDto.class);
ResponseBody body = ((HttpException) e).response().errorBody();
// Status code
HttpException httpException = (HttpException) e;
int statusCode = httpException.code();
if (statusCode == 500) {
showErrorDialog(activity, activity.getString(R.string.dialog_msg_error_401), true);
} else if (statusCode == 401) {
showErrorDialog(activity, activity.getString(R.string.dialog_msg_error_401), true);
} else {
try {
Timber.w("body.string() " + body.string());
// TODO : EXCEPTION HAPPEN IN HERE
BaseApiDto errorDto = adapter.fromJson(body.string());
msg = errorDto.getError();
Timber.w("msg " + msg);
} catch (Exception ex) {
// TODO : EXCEPTION HAPPEN IN HERE
ex.printStackTrace();
}
showErrorDialog(activity, msg, false);
}
}
}
UPDATE I assign body.toString() to variable, somehow it worked.
String response = body.string();
BaseApiDto errorDto = adapter.fromJson(response);
It worked because I didn't call body.string() twice.
I assign body.toString() to variable, somehow it worked.
String response = body.string();
BaseApiDto errorDto = adapter.fromJson(response);

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();
}

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