Hey Guys!
I’m just learning Kotlin after I went through a developement course on java on android (I’ve also done javeFX before that) and I’m up to json implementation with database and paging through a network.
I know my languages and how json works (if not please tell me) but I’ve come across on how to pull database data into a json_encode and go from there, however it’s in php.
What I’ve looked at is that reddit get’s it’s json data from a json file, and it updates instantly. This is either it has listeners when new information has been submitted and creates and overwrites the json file from other code, or, I am missing something.
Here’s an overview of what I’m looking at:
Reddit Json url API
https://www.reddit.com/r/androiddev/hot.json
See that it’s a json file?
My url PHP API
http://json.test/data.php
On a local test server
PHP API Code
<?php
//database constants
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'test');
//connecting to database and getting the connection object
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
//creating a query
$stmt = $conn->prepare("SELECT id, user FROM names LIMIT 2");
//executing the query
$stmt->execute();
//binding results to the query
$stmt->bind_result($id, $user);
$data = array();
//traversing through all the result
while($stmt->fetch()) {
$temp = array();
$temp['id'] = $id;
$temp['user'] = $user;
array_push($data, $temp);
}
//displaying the result in json format
header("Content-Type: application/json; charset=UTF-8");
echo json_encode(array("data"=>$data));
?>
See that the browser recognizes it as json data
{
"data": [
{
"id": 1,
"user": "John"
},
{
"id": 2,
"user": "Mary"
}
]
}
Google Fu has failed me for the last week now, I’m still boggling my mind around this concept.