I am creating webDialog for sending friend request on facebook.I am able to create web-dialog and send friend request but I don't know to parse bundle date.Once request is send and if there is no error I am getting the response of facebook in the following manner Bundle[{to[0]=100005695389624, to[1]=100002812207673, request=333965433373671}].I want to parse this data.How can I do this.
I am able to get request from the above data but how can i get the to parameter from it.If any one is having any idea then please let me know.
I tried in the following manner.
final String requestId = values.getString("request"); // This value retrieved properly.
char at[] = values.getString("to").toCharArray(); // returns null
String str[] = values.getStringArray("to"); // returns null
String s = values.getString("to"); // return null
I am creating WebDialog for inviting friends of facebook.In response of that I am getting the values in bundle in following format.
Bundle[{to[0]=10045667789624, to[1]=1353002812207673, request=1234555}]
So I was having issues in parsing data of the bundle.I resolved it in the following manner.
Bundle params = new Bundle();
params.putString("message", "Message from Android App.");
WebDialog requestsDialog = (
new WebDialog.RequestsDialogBuilder(ChatRoom.this,
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,FacebookException error) {
if( values != null)
{
final String requestId = values.getString("request");
ArrayList<String> friendsId = new ArrayList<String>();
int i = 0;
String to;
do {
to = values.getString("to[" +i + "]");
if(!TextUtils.isEmpty(to))
{
friendsId.add(to);
}
i++;
} while (to != null);
if (requestId != null) {
Toast.makeText(ChatRoom.this.getApplicationContext(),"Request sent",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(ChatRoom.this.getApplicationContext(),"Request cancelled",Toast.LENGTH_SHORT).show();
}
}
toggle();
}
})
.build();
requestsDialog.show();
Hope this could help someone.
I don't know whether it will work, but try viewing the to array as just a String.
final String requestId = values.getString("request");
final String to0 = values.getString("to[0]");
final String to1 = values.getString("to[1]");
If you don't know how many of these to strings you have, you could create a simple while loop and continue until it returns null. It's not an elegant solution, but it's the only one I can come up with right now. If you know more about the bundle, you can probably find a better solution.
ArrayList<String> to = new ArrayList<String>();
int i = 0;
while (true) {
String x = values.getString("to["+i+"]");
if (x == null) {
break;
} else {
to.add(x);
i++;
}
}
Related
I'm making an Android app that reads and writes data from MySQL database on my pc via shared wi-fi connection. Some of the data are in the form of my own class.
I successfully set up the server and I already managed to GET some data from my databes following this video tutorial.
I somewhat know what I need to do, but my problem is what the format of methods should be for POST and PUT.
Parts of my code that work for GET:
My request is created like this:
//get user by name
#RequestMapping(path="/{name}", method = RequestMethod.GET)
#ResponseBody
public User getUserByName(#PathVariable("name") String name) {return
userService.getUserByName(name);}
In a client class in my app:
// get user by name
public User getUserByName(String name){
return restTemplate.exchange(REST_SERVICE_URI + "/" + name, HttpMethod.GET, null, new ParameterizedTypeReference<User>() {}).getBody();}
and later used by a class inside my activity
private class
HttpRequestAsk extends AsyncTask<Void, Void, User>{
private String name;
public HttpRequestAsk(String name){
this.name = name;
}
#Override
protected User doInBackground(Void... params){
UserRestClient userRestClient = new UserRestClient();
User emptyUser = new User();
emptyUser.emptyUser();
if(userRestClient.getUserByName(name) == null) return emptyUser;
else return userRestClient.getUserByName(name);
}
#Override
protected void onPostExecute(User user) {
EditText passwordText = (EditText) findViewById(R.id.PasswordField);
TextView loginStateTextView = (TextView) findViewById(R.id.LoginStateTextView);
String fail = "Login Failed";
String success = "Login Succeeded";
if(user.getName().equals("empty")) loginStateTextView.setText(fail) ;
else if (user.getPassword().equals(passwordText.getText().toString())) {
loginStateTextView.setText(success);
Intent intent = new Intent(MainActivity.this, ListSelectActivity.class);
intent.putExtra("Extra user data", (Serializable) user);
startActivity(intent);
} else loginStateTextView.setText(fail);
}
}
Then on button click I call execute() for HttpRequestAsk and I get the user.
Now, let's say I want to call this request
//add new user
#RequestMapping(path="/add", method = RequestMethod.POST)
public String addNewUser(#RequestBody User user){
if( !user.getEmail().contains("#") || !user.getEmail().contains(".") ) return "Invalid email";
else if( userService.getUserByName(user.getName()) == null && userService.getUserByEmail(user.getEmail()) == null) {
userService.addUser(user);
return "Saved a user";
}else if( userService.getUserByName(user.getName()) != null && userService.getUserByEmail(user.getEmail() ) != null ) return "Username and email already in use";
else if( userService.getUserByName(user.getName()) != null ) return "Username already in use";
else return "Email already in use";
}
I tried to POST a user like this
//add new user
#SuppressWarnings("unchecked")
public void addNewUser(User user){
restTemplate.postForLocation(REST_SERVICE_URI + "/add", user, User.class);
}
But the app crashes when I use this addNewUser method. I guess I should make and Entity or JSON out of my user, kind of reverse what I did with GET, but I don't really know how.
I try to get only mails from Outbox:
String user = "me";
ListMessagesResponse response = mService.users().messages().list(user).execute();
//set selected labels
//[CATEGORY_PERSONAL, CATEGORY_SOCIAL, Регистрации, CATEGORY_FORUMS, IMPORTANT, CATEGORY_UPDATES, CHAT, SENT, INBOX, TRASH, CATEGORY_PROMOTIONS, DRAFT, SPAM, STARRED, UNREAD]
List<String> labelIds = new ArrayList<>();
labelIds.add("SENT");
List<Message> messages = new ArrayList<Message>();
while (response.getMessages() != null) {
messages.addAll(response.getMessages());
if (response.getNextPageToken() != null) {
String pageToken = response.getNextPageToken();
response = mService.users().messages().list(user).setLabelIds(labelIds).setPageToken(pageToken).execute();
} else {
break;
}
}
but I get Inbox messages too
I need to set filter on the first response line.
This code work:
String user = "me";
//set selected labels
//[CATEGORY_PERSONAL, CATEGORY_SOCIAL, Регистрации, CATEGORY_FORUMS, IMPORTANT, CATEGORY_UPDATES, CHAT, SENT, INBOX, TRASH, CATEGORY_PROMOTIONS, DRAFT, SPAM, STARRED, UNREAD]
List<String> labelIds = new ArrayList<>();
labelIds.add("SENT");
ListMessagesResponse response = mService.users().messages().list(user).setLabelIds(labelIds).execute();
List<Message> messages = new ArrayList<Message>();
while (response.getMessages() != null) {
messages.addAll(response.getMessages());
if (response.getNextPageToken() != null) {
String pageToken = response.getNextPageToken();
response = mService.users().messages().list(user).setPageToken(pageToken).execute();
} else {
break;
}
}
i am using Facebook Graph API to get user's feed. But when i get string which is defined "story", it comes in English what i do. Should i do get it different languages ? How/Where i can use "locale" value(fr_FR or tr_TR) while i am doing query ? Here's my code:
EDIT: FacebookFeed is my POJO class.
LoginManager.getInstance().logInWithReadPermissions(FacebookScreen.getMe(), Arrays.asList("user_posts"));
Bundle parameters = new Bundle();
parameters.putString("fields", "created_time,story,message,link,picture");
GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(), "/v2.3/me/feed", parameters, HttpMethod.GET, new Callback() {
#Override
public void onCompleted(GraphResponse response) {
JSONObject object = response.getJSONObject();
for (int i = 0; i < object.optJSONArray("data").length(); i++) {
FacebookFeed feed = new FacebookFeed();
if (object.optJSONArray("data").optJSONObject(i).optString("story") != null) {
feed.setStory(object.optJSONArray("data").optJSONObject(i).optString("story"));
Log.i("log1", "if1");
}
if (object.optJSONArray("data").optJSONObject(i).optString("message") != null) {
feed.setMessage(object.optJSONArray("data").optJSONObject(i).optString("message"));
Log.i("log2", "if2");
}
if (object.optJSONArray("data").optJSONObject(i).optString("created_time") != null) {
feed.setTime(object.optJSONArray("data").optJSONObject(i).optString("created_time"));
Log.i("log3", "if3");
}
if (object.optJSONArray("data").optJSONObject(i).optString("picture") != null) {
String urlString=object.optJSONArray("data").optJSONObject(i).optString("picture");
feed.setPicture(urlString);
Log.i("log4", "if4");
}
if (object.optJSONArray("data").optJSONObject(i).optString("link") != null) {
feed.setLink(object.optJSONArray("data").optJSONObject(i).optString("link"));
Log.i("log5", "if5");
}
feedList.add(feed);
Log.i("LOG", "added to list");
}
}
});
request.executeAsync();
You can try to add
parameters.putString("locale", "fr_FR");
This works at least in the Graph API Explorer:
I am working with Facebook graph api:
I need to get the list of friends who have already AUTHENTICATED MY APPLICATION.
First question:
IS THIS POSSIBLE?
and if yes please guide me where should I start searching for it.
I have already gone through SO for similar question and none suits in my case.
Please help!
Thank you.
Facebook API provides a boolean field that can help you filter the User's friends with your application Installed. You need to Make a request for User's Friends List and set the required fields to include the "installed" boolean. The following code snippet may help you out.
private void requestMyAppFacebookFriendsWithAppInstalled(Session session) {
Request friendsRequest = createRequest(session);
friendsRequest.setCallback(new Request.Callback()
{
#Override
public void onCompleted(Response response)
{
//SetUpList
List<GraphUser> friends = getResults(response);
GraphUser user;
friendsList=new ArrayList<ACT_friendsListPicker.FB_FriendsListStructure>();
boolean installed = false;
if(friends!=null)
{
for(int count=0;count<friends.size();count++)
{
user = friends.get(count);
if(user.getProperty("installed") != null)
{
installed = (Boolean) user.getProperty("installed");
Log.i("frndsPickerAppInstalled? YES ","user: "+user.getInnerJSONObject());
}
}}}});
private Request createRequest(Session session) {
Request request = Request.newGraphPathRequest(session, "me/friends", null);
Set<String> fields = new HashSet<String>();
String[] requiredFields = new String[] { "id", "name", "picture","hometown",
"installed" };
fields.addAll(Arrays.asList(requiredFields));
Bundle parameters = request.getParameters();
parameters.putString("fields", TextUtils.join(",", fields));
request.setParameters(parameters);
return request;
}
private class FB_FriendsListStructure
{
String Name,ID,ImageUrl;
boolean selected;
}
private List<GraphUser> getResults(Response response) throws NullPointerException
{
try{
GraphMultiResult multiResult = response
.getGraphObjectAs(GraphMultiResult.class);
GraphObjectList<GraphObject> data = multiResult.getData();
return data.castToListOf(GraphUser.class);
}
catch(NullPointerException e)
{
return null;
//at times the flow enters this catch block. I could not figure out the reason for this.
}
}
How can i get a friends last status in Facebook ?
Request r = Request.newMyFriendsRequest(
ParseFacebookUtils.getSession(), new GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users,
Response response) {
if (users != null) {
pb.setVisibility(View.GONE);
ll.startAnimation(fadein);
ll.setVisibility(View.VISIBLE);
friends = users;
f = new ArrayList<String>();
for (int i = 0; i < users.size(); i++) {
f.add(users.get(i).getName());
}
loadRandom();
}
}
});
Bundle params = r.getParameters();
params.putString("fields", "name,id,gender");
r.setParameters(params);
r.executeAsync();
I am using this code, but how can i get their status ?
You could use
params.putString("fields", "name,id,gender,statuses.limit(1)");
to achieve this. Remember that you need the "user_status" permission to do this.