how do i get this json data from php server in android - php

how do i get this json data in android
this data is in localhost. I must fetch this data using URL and display in listview in android.Can any one help in coding plz
[
{
"id":"111114",
"name":"Prandar"
},
{
"id":"111115",
"name":"Catmilkend"
},
{
"id":"111110",
"name":"Allan"
},
{
"id":"111111",
"name":"Aircornal"
},
{
"id":"111112",
"name":"Allaxander"
},
{
"id":"111113",
"name":"AppleMacro"
}
]

This is a very common need, but involves several independent steps which could easily be their own StackOverflow question.
1) in a file named info.php you will create the JSON string to return to requests:
<?php
// this may come from a database
$info = array ('id' => '101',
'name'=> 'bill'
)
echo json_encode($info); // returns {"id":'101',"name": "bill"}
?>
2) Send a http GET request to myserver.com/info.php and capture the string response.
http://w3mentor.com/learn/java/android-development/android-http-services/example-of-http-get-request-using-httpclient-in-android/
3) Then parse the JSON into objects or dictionary array with a JSON framework.
http://www.jondev.net/articles/Android_JSON_Parser_Example
4) Use a ListView in Android to display it.
http://developer.android.com/resources/tutorials/views/hello-listview.html

Related

browse a JSON and fill PHP variables [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
i work on project, where there are server that send to my php application json data and then i put it in database.
I receive a POST request from the server and i can get json with this :
receive_json.php:
$payload = file_get_contents('php://input');
and there is the form of the JSON:
{
"applicationID": "123",
"applicationName": "temperature-sensor",
"deviceName": "garden-sensor",
"devEUI": "0202020202020202",
"rxInfo": [
{
"gatewayID": "0303030303030303", // ID of the receiving gateway
"name": "rooftop-gateway", // name of the receiving gateway
"time": "2016-11-25T16:24:37.295915988Z", // time when the package was received (GPS time of gateway, only set when available)
"rssi": -57, // signal strength (dBm)
"loRaSNR": 10, // signal to noise ratio
"location": {
"latitude": 52.3740364, // latitude of the receiving gateway
"longitude": 4.9144401, // longitude of the receiving gateway
"altitude": 10.5, // altitude of the receiving gateway
}
}
],
"txInfo": {
"frequency": 868100000, // frequency used for transmission
"dr": 5 // data-rate used for transmission
},
"adr": false, // device ADR status
"fCnt": 10, // frame-counter
"fPort": 5, // FPort
"data": "...", // base64 encoded payload (decrypted)
"object": { // decoded object (when application coded has been configured)
"temperatureSensor": {"1": 25},
"humiditySensor": {"1": 32}
}
}
i'm new user of JSON, so i put directly the text JSON to my database like this :
$payload = file_get_contents('php://input');
$req = $bdd->prepare( '
INSERT INTO nods(payload)
VALUES (:payload);
' );
$req->execute(array('payload' => $payload));
the result :
I would like to browse " $payload " and put the information in php variables like:
$applicationID = .... ;
$rxInfo[] = .... ;
i already try somthing like "foreach" but i could not succes, can you help me please, thanks :).
Best regard,
DIDOUH JAWAD
You can use json_decode to get a PHP array representation of the JSON
$array = json_decode($payload, true);
var_dump($array);
http://php.net/manual/en/function.json-decode.php

Problems manipulating JSON data in PHP

I'm not that handy with JSON so here goes. I'm receiving Amazon SNS notifications for bouncing email addresses to a listener (in PHP 5.5) which does:
$post = #file_get_contents("php://input");
$object = json_decode($post, true);
This gives me:
Type => Notification
MessageId => #####
TopicArn => #####
Message => {
"notificationType":"Bounce",
"bounce": {
"bounceSubType":"General",
"bounceType":"Permanent",
"bouncedRecipients":[{"status":"5.3.0","action":"failed","diagnosticCode":"smtp; 554 delivery error: dd This user doesn't have a yahoo.com account (testuser#yahoo.com) [0] - mta1217.mail.bf1.yahoo.com","emailAddress":"testuser#yahoo.com"}],
"reportingMTA":"dsn; ######",
"timestamp":"2014-10-27T16:37:42.136Z",
"feedbackId":"######"
},
"mail": {
"timestamp":"2014-10-27T16:37:40.000Z",
"source":"myemail#mydomain.com",
"messageId":"######",
"destination":["testuser#yahoo.com"]
}
}
I was expecting an associative array all the way down but instead it's an array only at the top level and with JSON strings inside. I've tried everything I can think of, including json_decoding further parts of the array, but I'm struggling to access the data in a simple way. What I need is the "destination" email address which should be in $object['Message']['mail']['destination'][0].
Can anyone point out what I'm doing wrong here? Thanks.
It looks like $object['Message'] is also json encoded. Perhaps because it's using some generic container format for service call results. Try this
$post = #file_get_contents("php://input");
$object = json_decode($post, true);
//Message contains a json string
$object['Message'] = json_decode($object['Message'], true);
//Then access the structure using array notation
echo $object['Message']['mail']['destination'][0];

HTML is NULL in JSON object from json_encode

I have a ajax call calling a php file who runs a long php function which returns a JSON encoded array/object. Now I need to send HTML also into the ajax response. I thought about sending the HTML inside the array.
Is that a good practise?
Right now I cannot get it working, I get a NULL as value for that property. Don't know why.
$statHTML = '<table>';
foreach ($toHTML as $key=>$value) {
$statHTML.= '
<tr class="'.$key.'">
<td class="side">'.$value[0].'</td>
<td>'.$value[2].' '.$value[1].'</td>
</tr>';
}
$statHTML.= '</table>';
// echo $statHTML; // - this works
//function return
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => $statHTML
);
return json_encode($answer);
The ajax response from the console before the JSON.parse():
{
"mostSearched": {
"title": "Most serached houses",
"colNames": [21],
"rowNames": [2013],
"rows": [1]
},
"timeOfDay": {
"title": "Time of search",
"colNames": ["07:30"],
"rowNames": ["07:30"],
"rows": [
[1]
]
},
"mostSearchedDays": {
"title": "Most searched days",
"colNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rowNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rows": [
[1, 1, 1, 1, 1, 1, 1]
]
},
"statHTML": null
}
From php.net:
Parameters
value
The value being encoded. Can be any type except a resource.
All string data must be UTF-8 encoded.
So use:
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => utf8_encode($statHTML)
);
return json_encode($answer);
Most likely the build-in JSON parser used by PHP cannot properly parse the HTML, the easiest way to solve the issue is to base64 encode the html on the server, and then decode it on the client, using either the newer atob and btoa base64 methods, or one of the many polyfills out there.
use base64_enccode in this at the time of conversion
$answer = array('statHTML'=>base64_encode('<h1>html in here</h1>'));
echo json_encode($answer);exit;
And at the time of getting response from ajax
atob(response.statHTML);
Hope you understand how it works

Communication between Javascript and MYSQL

I am working on some code using Google Maps API. To sum up shortly, I have MySQL database with a table of information used to generate markers on the map. I connected to the database and am using PHP to draw out the necessary attributes and communicate with my Javascript code using XML.
What I'm currently attempting to do is go in the other direction, I'm trying to send a string of information (for example "1,2,3,45,18") from my Javascript code to MySQL to be set as a session parameter (call it #sparam). What is the process behind passing this value to MySQL?
Would I be able to access a MySQL variable through PHP in the same way I can access tables (for the purpose of getting a value back into Javascript)?
I'd appreciate any insight.
Thanks.
EDIT
Maybe I was unclear in my original post. What I'm asking is how would I be able to pass a string to a MySQL session variable, specifically a set of IDs directly related to the IDs in the table of the MySQL database, and then be able to work with these IDs by calling the necessary procedures in MySQL. In turn, the procedures called in MySQL would generate some output, which would then have to be passed back to the Javascript code.
I created a special JSON (JavaScript Object Notation) php pages that I would call from javascript. Then I would parse those JSON responses.
Simple example:
JAVASCRIPT:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "page_json.php?action=getsession",
type : "GET",
success : function(data) {
//Get Json and loop over it's data
if (data.length>10){
var jsonData = JSON.parse(data);
$.each(jsonData, function(Idx, Value) {
if (Idx>0){
//get values for each vehicle and then remove it's marker from the map and then add new marker on the map (thereofore update the marker)
c_latitude = Value["lat"];
c_longitude = Value["lon"];
c_name = Value["name"];
c_notes= Value["notes"];
removeMarker(c_name); //remove old marker function
addMarker(c_latitude, c_longitude, c_name); //add current marker function
}
});
}
}
});
});
}
PHP: Here I loop over my arrayList and then create a simple array with values. Then I just output it as a json string
foreach ($listOfCars->arrayList as $key => $value) {
$unit = new fleetUnit();
$unit = $value;
//create array for json output
$data[] = array('lat' => $unit->lat,
'lon' => $unit->lon, 'name' => $unit->name, 'notes' => $unit->notes);
}
echo json_encode($data);

Instagram Real time API - PHP - Unable to get POST Update

I'm trying to connect with the instagram API, the connection works fine and I am receiving the updates just as described in the API documentation, the issue is that I cannot access to the data send to my callback function.
According to the doc
When someone posts a new photo and it triggers an update of one of your subscriptions, we make a POST request to the callback URL that you defined in the subscription
This is my code :
// check if we have a security challenge
if (isset ($_GET['hub_challenge']))
echo $_GET['hub_challenge'];
else // This is an update
{
// read the content of $_POST
$myString = file_get_contents('php://input');
$answer = json_decode($myString);
// This is not working starting from here
$id = $answer->{'object_id'};
$api = 'https://api.instagram.com/v1/locations/'.$id.'/media/recent?client_secret='.INSTA_CLI_SECRET.'&client_id='.INSTA_CLI_ID;
$response = get_curl($api); //change request path to pull different photos
$images = array();
if($response){
$decode = json_decode($response);
foreach($decode->{'data'} as $item){
// do something with the data here
}
}
}
Displaying the $myString variable I have this result, don't know why it is not decoded to json :(
[{"changed_aspect": "media", "subscription_id": 2468174, "object":
"geography", "object_id": "1518250", "time": 1350044500}]
the get_curl function is working fine when I hardcode my $id.
I guess something is wrong with my $myString, unfortunately the $_POST cvariable is not populated, Any idea what I am missing ?
Looking at the example JSON response included in your question, I can conclude that the object you are trying to talk with is wrapped in an array (hence the [ and ] around it in the JSON string).
You should access it using $answers[0]->object_id.
If that doesn't work, you can always use var_dump to check out the data in one of your variables.

Categories