I'm creating a android game that integrates with facebook to retrieve their photo and first name and other information using the graph, I've found out how to retrieve their photo using the below code which works perfectly but I'm struggling to find working examples of extracting other information like first_name etc...
The code I'm using to retrieve the photo and display it in a ImageView is below.
public void showPhoto(View v) {
try {
ImageView MyProfilePicImageView = (ImageView)findViewById(R.id.temp);
URL MyProfilePicURL = new URL("https://graph.facebook.com/me/picture?type=normal&method=GET&access_token="+ access_token );
Bitmap MyprofPicBitMap = null;
try {
MyprofPicBitMap = BitmapFactory.decodeStream(MyProfilePicURL.openConnection().getInputStream());
MyProfilePicImageView.setImageBitmap(MyprofPicBitMap);
}
catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
I've searched high and low but can't seem to find information on how to retrieve the other information using the graph, other information meaning first_name etc... including here on the facebook developer website (https://developers.facebook.com/docs/reference/api/) but can't find a working example.
Can anybody show me a working example to retrieve the first_name of the user so I can display it in a textview?
using this url"https://graph.facebook.com/me/friends?access_token="+accessToken you can get your friends which contains thier names and ids to get info about any of them just use `"https://graph.facebook.com/"+yourFriendId+"?access_token="+accessToken'
this will return json that you can parse and useExample
HttpClient httpclient = new DefaultHttpClient();
String url = "https://graph.facebook.com/me/friends?access_token=" + URLEncoder.encode(token);
HttpGet httppost = new HttpGet(url);
try {
HttpResponse response = httpclient.execute(httppost);
// to get the response string
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
// used to construct the string
String res = "";
for (String line = null; (line = reader.readLine()) != null;) {
res += line + "\n";
}
// here we will parse the response
JSONObject obj = new JSONObject(new JSONTokener(res));
JSONArray data = obj.getJSONArray("data");
int len = data.length();
for (int i = 0; i < len; i++) {
JSONObject currentResult = data.getJSONObject(i);
String name = currentResult.getString("name");
String icon = currentResult.getString("id");
// do what ever you want
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If you change your request URL to just /me (i.e. https://graph.facebook.com/me?type=normal&method=GET&access_token=...) you'll get all available profile information for the currently authenticated user.
This JSON object should have first_name and last_name, among other attributes foud here.
Check out this handy API explorer tool to play around with what you should be seeing.
Related
I want to get response after post data but it fails. I want to create a login system, I have successfully submited data to php file, everything is working fine now I want to get response from same function but I'm unable to know where the issue is.
Here is the Java function:
public class PostDataGetRes extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
postRData();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}
public void postRData() {
String result = "";
InputStream isr = null;
final String email = editEmail.getText().toString();
final String pass = editPass.getText().toString();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://website.com/appservice.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", email));
nameValuePairs.add(new BasicNameValuePair("stringdata", pass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
resultView.setText("Inserted");
HttpEntity entity = response.getEntity();
isr = entity.getContent();
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("first_name")+"\n\n";
//"User ID : "+json.getInt("user_id")+"\n"+
//"Name : "+json.getString("first_name")+"\n"+
//"Email : "+json.getString("email")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
resultView.setText("Done");
}
And here is php code:
if($id){
$query = mysql_query("SELECT first_name FROM users where email = '$id' ");
while($row=mysql_fetch_assoc($query)){
$selectedData[]=$row;
}
print(json_encode($selectedData));
}
Please help me I have tried so far but could not achieve any results. Please help me how can I get response from php file after query execution.
At first be sure you get correct JSON object from your website - try printing it as Toast.makeText(). As far the web browsers keep the html comments away, android gets it in response.
AsyncTask objects and classes aren't designed to be made the way u provided and also you can't make any UI operations in doInBackground(). AsyncTask is made in a way to not to block GUI.
Here is a not much different example how it uses methods you have in AsyncTask class:
class Logging extends AsyncTask<String,String,Void>{
JSONObject json=null;
String output="";
String log=StringCheck.buildSpaces(login.getText().toString());
String pas=StringCheck.buildSpaces(password.getText().toString());
String url="http://www.mastah.esy.es/webservice/login.php?login="+log+"&pass="+pas;
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Operation pending, please wait", Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.addHeader("User-Agent", "User-Agent");
HttpResponse response;
try {
response = client.execute(request);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line="";
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) {
result.append(line);
}
output=result.toString();
} catch (ClientProtocolException e) {
Toast.makeText(getApplicationContext(), "Connection problems", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Conversion problems", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void w) {
try {
json = new JSONObject(output);
if(json.getInt("err")==1){
Toast.makeText(getApplicationContext(), json.getString("msg"), Toast.LENGTH_LONG).show();
}else{
String id_user="-1";
Toast.makeText(getApplicationContext(), json.getString("msg"), Toast.LENGTH_LONG).show();
JSONArray arr = json.getJSONArray("data");
for(int i =0;i<arr.length();i++){
JSONObject o = arr.getJSONObject(i);
id_user = o.getString("id_user");
}
User.getInstance().setName(log);
User.getInstance().setId(Integer.valueOf(id_user));
Intent i = new Intent(getApplicationContext(),Discover.class);
startActivity(i);
}
} catch (JSONException e) {
}
super.onPostExecute(w);
}
}
PHP file content:
$data = array(
'err' => 0,
'msg' => "",
'data' => array(),
);
$mysqli = new MySQLi($dbhost,$dbuser,$dbpass,$dbname);
if($mysqli->connect_errno){
$data['err'] = 1;
$data['msg'] = "Brak polaczenia z baza";
exit(json_encode($data));
}
if(isset($_GET['login']) && isset($_GET['pass'])){
$mysqli->query("SET CHARACTER SET 'utf8';");
$query = $mysqli->query("SELECT banned.id_user FROM banned JOIN user ON user.id_user = banned.id_user WHERE user.login ='{$_GET['login']}' LIMIT 1;");
if($query->num_rows){
$data['err']=1;
$data['msg']="User banned";
exit(json_encode($data));
}else{
$query = $mysqli->query("SELECT login FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
if($query->num_rows){
$query = $mysqli->query("SELECT pass FROM user WHERE pass ='{$_GET['pass']}' LIMIT 1;");
if($query->num_rows){
$data['msg']="Logged IN!";
$query = $mysqli->query("SELECT id_user FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
$data['data'][]=$query->fetch_assoc();
exit(json_encode($data));
}else{
$data['err']=1;
$data['msg']="Wrong login credentials.";
exit(json_encode($data));
}
}else{
$data['err']=1;
$data['msg']="This login doesn't exist.";
exit(json_encode($data));
}
}
}else{
$data['err']=1;
$data['msg']="Wrong login credentials";
exit(json_encode($data));
}
I have created there small dictionary $data for my app. I used its err key as a flag to know if any error appeared, msg to inform user about operation results and data to send JSON objects.
Thing you would want to do with if(response == true) if it had exist is similar to construction i used in my onPostExecute(Void w) method in AsyncTask:
if(json.getInt("err")==1){
//something went wrong
}else{
//everything is okay, get JSON, inform user, start new Activity
}
Also here is the way I used $data['data'] to get JSON response:
if($query->num_rows){
while($res=$query->fetch_assoc()){
$data['data'][]=$res;
}
exit(json_encode($data));
}
I am creating a Http request to access OData services. I am getting the response but I don't know how to parse the response into a String objects so that I can add them to a ArrayList.
Here is my code:
protected List<StatusResponse> doInBackground(Void... params)
{
// TODO Auto-generated method stub
// Execute HTTP Post Request
mResponseList = new ArrayList<StatusResponse>();
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(myOdataQueryUrl);
try
{
HttpResponse responsenext = httpclient.execute(httpget);
HttpEntity entitynext = responsenext.getEntity();
AddedResult= EntityUtils.toString(entitynext);
jsonArray = new JSONArray(AddedResult);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject menuObject = jsonArray.getJSONObject(i);
String createdBy = menuObject.getString("CreatedBy");
String comment = menuObject.getString("Comment");
String location = menuObject.getString("Location");
String slot = menuObject.getString("Slot");
String reachingAt = menuObject.getString("StartTime");
String lunch = menuObject.getString("Lunch");
mResponseList.add(new StatusResponse(createdBy, comment, location, slot, reachingAt, lunch));
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mResponseList;
}
I get this response:--
{
"odata.metadata":"mysite/odata/$metadata#OStatus","value":[
{
"StatusId":2151,"Location":"Office","Slot":"Running late","StartTime":"2014-09-29T12:30:00","Comment":"-","Lunch":null,"CreatedBy":"","ModifiedBy":null,"Created":"2014-09-29T04:39:10.443","Modified":null
}
]
}
I get the following error if I try to parse it like above:
Value {"value":[{"Created":"2014-09-29T04:39:10.443","Modified":null,"StatusId":2151,"ModifiedBy":null,"Slot":"Running late","CreatedBy":"","Comment":"-","Location":"Office","Lunch":null,"StartTime":"2014-09-29T12:30:00"}],"odata.metadata":"https:\/\/mySite\/odata\/$metadata#OStatus"} of type org.json.JSONObject cannot be converted to JSONArray
You're trying to convert a normal JSON object into a JSON Array.
It also seems that you're declaring that array to be a field in stead of a local variable to your method. Are you sure that is what you need?
First of all please look at my code below:
List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
qsList.add(new BasicNameValuePair("oauth_token", accessToken));
String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
HttpGet userInfoRequest = new HttpGet(id + "?" + queryString);
DefaultHttpClient defaultHttpClientclient = new DefaultHttpClient();
HttpResponse userInfoResponse;
try {
userInfoResponse = defaultHttpClientclient.execute(userInfoRequest);
String responseBody = EntityUtils.toString(userInfoResponse.getEntity());
System.out.println("User info response: " + responseBody);
System.out.println("");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I got an access token from Salesforce. Now I request user's information via that token. In the responseBody I got all infomation of that user like username, id, language,... Now I need to take only username from the response. What should I do to take it?
The response is likely in JSON. If so you can parse the data you need. I won't repost the code, instead please see: How to parse JSON in Java
JSONObject responseJSON = new JSONObject(EntityUtils.toString(userInfoResponse.getEntity());
String username = responseJSON.getString("username");
I'm tearing my hair out over this problem I am having. I am trying to allow a user to upload some data from their android application to a website service which I have developed.
The data is to be uploaded using JSON and Android to a PHP web service which will then 'INSERT' the data into my PostgreSQL database.
I am unsure where the logic error is in my whole application as the app produces no errors at runtime but when I check the database records of my PostgreSQL server space there has been no data committed.
Please see below the code I am using and please try to help identify where I am going wrong. I have looked for tutorials on Google but they all are based on reading data FROM a PHP web service to an android app but I am looking to send the original data from the android app.
DataPost Activity
public void postData() throws JSONException{
Toast.makeText(DataSummary.this, "Done! Check your profile online to see your record.", Toast.LENGTH_LONG).show();
Thread trd = new Thread(new Runnable(){
public void run(){
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://users.aber.ac.uk/dwd/mfb/php/jsonscript.php");
JSONObject json = new JSONObject();
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), i);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba, i);
try {
//JSON data:
json.put("photo", ba1.toString());
json.put("name", name);
json.put("description", description);
json.put("latitude", latitude);
json.put("longitude", longitude);
json.put("project", project);
json.put("owner", username);
JSONArray postjson = new JSONArray();
postjson.put(json);
//Post the data
httppost.setHeader("json", json.toString());
httppost.getParams().setParameter("jsonpost", postjson);
//Execute HTTP Post Request
System.out.println(json);
HttpResponse response = httpclient.execute(httppost);
//for JSON
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try{
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
} catch (IOException e){
e.printStackTrace();
} finally {
try {
is.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
} catch(ClientProtocolException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
trd.start();
}
PHP Webservice
<?php
session_start();
$conn = pg_connect("database_string");
//VARIABLES TO BE WRITTEN TO THE DATABASE
$photo = $_REQUEST["photo"];
echo $photo;
$binary=base64_decode($photo);
header('Content-Type: bitmap; charset=utf-8');
$name = json_decode(stripslashes($_POST["name"]));
$safe_name = pg_escape_string($name);
$desc = json_decode(stripslashes($_POST["description"]));
$safe_desc = pg_escape_string($desc);
$latitude = json_decode(stripslashes($_POST["latitude"]));
$longitude = json_decode(stripslashes($_POST["longitude"]));
$project = json_decode(stripslashes($_POST["project"]));
$owner = json_decode(stripslashes($_POST["owner"]));
$id = pg_query("SELECT * FROM users WHERE email = $owner");
$id_assoc = pg_fetch_assoc($id);
$id_res = $id_assoc['u_id'];
//SQL STATEMENT HERE FOR INSERT
$res = pg_query("INSERT INTO records (photo, name, description, latitude, longitude, project, owner) VALUES ('$photo', '$safe_name', '$safe_desc', '$latitude', '$longitude', '$project', '$id_res'");
pg_close($conn);
?>
Anyone who can provide some advice/tutorials/code solutions would be a hero in my book!
Does the SELECT query return anything? I'm not a PHP expert but to me it looks like you're sending the variables wrong so there shouldn't be:
$id = pg_query("SELECT * FROM users WHERE email = $owner");
But
$id = pg_query("SELECT * FROM users WHERE email ='".$owner."'");
Similar for the INSERT query.
Other thoughts:
don't do a SELECT * when you just want one column it will be slower. For example with index-only-scans in 9.2 you could return the id straight from the index(email,id)
if you want to use just the id of the user it's better to put it in the subquery of the insert query
INSERT INTO records ( ... ,owner) VALUES (... ,(SELECT id FROM users WHERE email='".$owner."')")
You could even add RETURNING owner at the end to get the owner id out from the insert query if you need it somewhere else.
i am trying to Json parsing in my android app the link is https://www.buzzador.com/apps/present_software/webservice/index.php?op=ProductQ&campaign_id=607&userid=10776
when i put it into Json object it gives errors to me
error is :
08-31 14:40:52.281: WARN/System.err(416): org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
public static String getmyproductquestiondetails(String userid,
String campaignid) {// https://www.buzzador.com/apps/present_software/webservice/index.php?op=EducationResult&userid=1&questionid=1,2,3&answergivenbyuser=1,1,0
String data = null;
try {
URL url = new URL(
"http://dignizant.com/buzz/webservice/index.php?op=getProductQuestion&userid="
+ userid + "&campaign_id=" + campaignid);
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url
.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
} else {
http = (HttpURLConnection) url.openConnection();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Utils utils = new Utils();
try {
data = utils.convertStreamToString(http.getInputStream());
System.out.println("getproduct details response :: " + data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
data = e.toString();
}
return data;
}
try {
JSONObject jo = new JSONObject(response);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
char[] utf8 = null;
StringBuilder properString = new StringBuilder("");
utf8 = Response.toCharArray();
for (int i = 0; i < utf8.length; i++) {
if ((int) utf8[i] < 65000) {
properString.append(utf8[i]);
}
}
System.out.println("Response of Login::"
+ properString.toString());
Had similar problem. At first my app was working great on both androids 4.0+ and 4.0- (2.3.3 2.2 etc). after a revision i have that problem. JSonarray could parse on 2.3.3
PROBLEM: Json STRING (response from server) comes with a character ' in front
so actual response= '[{"1":"omg"}] and not the correct one [{"1":"omg"}]
Solution:
if string dosent start with [ then edit response string (remove the ' character)
if (result.startsWith("["))
{
}
else
{
result= result.substring(1);
}
after then everything worked fine for me
If you are a using json-lib-2.4 as library, which I assume, you can parse strings with :
JSONSerializer.toJSON(yourString).toString()
instead of using the JsonObject class
To remove character like (\n) or unwanted character in json string used commons-lang3:3.4 library in program . i used this class to remove unwanted character in json string "StringEscapeUtils.unescapeJava(string)".
this will help you.