Android: Get data from MySQL Database - java

I have watched more than 5 hours YouTube tutorials but im simply dont getting how to make this work. There is always something that I dont understand or that with me doesnt work.!
I want to get data from Database and bring it to my Android. I have read this might work with JSON.
Here is the link to my JSON DB export. Is this correct?
http://web2page.ch/apps/FruityNumber/recordShow2.php
The API I use:
compileSdkVersion 23
I'm hoping you could help me out step by step. I'm looking for the simplest way.

There are several ways to perform this. You can perform a Http request to the server and fetch the results, parse them manually into java objects. Or use a library like Gson that would save you the work to parse manually and serialize the JSON string to java objects.
But what I would recommend is using Retrofit an Http client that would let you easily download the JSON data and parse it into a POJO (Plain Old Java Object). Retrofit uses coverters for this purpose like Gson, Jackson, Moshi etc.
Using Retrofit is fairly simple,
Define an interface (Synchronous or Asynchronous) and define API end-points
Build a Retrofit object with the Base URL
If performing a synchronous request, retrofit will generate an implementation for your interface and you will have to make sure that you make the request in a background thread
If performing asynchronous request, you will need to register a call back through which you will get the response
Finally a POJO class for your response,
public class Item {
public String id;
public String user;
public String highscore;
}
Here is a complete guide on how to use Retrofit.

It would be easier to use a library like GSON to convert JSON to Java objects.
The way it works you create a model class for example:
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
#Generated("org.jsonschema2pojo")
public class Result{
#SerializedName("id")
#Expose
private String id;
#SerializedName("user")
#Expose
private String user;
#SerializedName("highscore")
#Expose
private String highscore;
/**
*
* #return
* The id
*/
public String getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* #return
* The user
*/
public String getUser() {
return user;
}
/**
*
* #param user
* The user
*/
public void setUser(String user) {
this.user = user;
}
/**
*
* #return
* The highscore
*/
public String getHighscore() {
return highscore;
}
/**
*
* #param highscore
* The highscore
*/
public void setHighscore(String highscore) {
this.highscore = highscore;
}
}
This is makes it very easy:
Gson gson = new Gson();
List<Result> results = gson.fromJson(json, new TypeToken<List<Result>>(){}.getType());
Example:
for(Result res : results){
Log.d(LOG_TAG, "id = " + res.getId());
}

There are many ways to get your work done. But I am going with simple one.
First of all bring all json data from server side to client side(means app side) by making HTTP request. You can do using android preferred HttpUrlConnection Class. You can visit here for doing this.
http://syntx.io/how-to-send-an-http-request-from-android-using-httpurlconnection/
Once you have brought your data on app side. You have to parse that json format data using JSONObject and JSONArray class.For that you have to make a model class.For doing this, you can visit
http://androidexample.com/JSON_Parsing_-_Android_Example/index.php?view=article_discription&aid=71&aaid=95
I think you should change your json format like this:
{
"Results": [
{
"id": "1",
"user": "ero",
"highscore": "13 Sek"
},
{
"id": "2",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "3",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "4",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "5",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "6",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "7",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "8",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "9",
"user": "",
"highscore": ""
},
{
"id": "10",
"user": "Stefano",
"highscore": "alle"
},
{
"id": "11",
"user": "Test001",
"highscore": "Test001"
},
{
"id": "12",
"user": "",
"highscore": ""
},
{
"id": "13",
"user": "Stefano",
"highscore": "5sek"
},
{
"id": "14",
"user": "sven",
"highscore": "1"
},
{
"id": "15",
"user": "sven",
"highscore": "1"
},
{
"id": "16",
"user": "sven",
"highscore": "1"
},
{
"id": "17",
"user": "",
"highscore": ""
},
{
"id": "18",
"user": "kiala",
"highscore": ""
},
{
"id": "19",
"user": "kiala",
"highscore": "angola"
},
{
"id": "20",
"user": "kiala",
"highscore": ""
}
]
}
It looks pretty relevant and easy to parse. For changing your json format, you can code in your php file.
$sql = mysqli_query("SELECT ...");
$resluts = array();
while($row = mysqli_fetch_assoc($sql)) {
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["user"] = $row["user"];
$tmp["highscore"] = $row["highscore"];
array_push($results["Results"], $tmp);
}
echo json_encode($results);

Related

Transform json data to another json using java and apache camel

How can i convert a json object from one structure to another in apache camel using java?
I have tried using jsonpath but I'm not sure if i am going in the right direction or how it's going to look at in the end.
ReadContext ctx = JsonPath.parse(json);
LinkedHashMap full = ctx.read("$");
String fulldata = full.toString()
.replace("date_of_birth", "birth")
.replace("name", "person_name")
.replace("full_name", "fullname")
.replace("last_name", "last")
.replace("middle_name", "middle")
.replace("first_name", "first")
This is how my json looks like now
"person": {
"country_of_residence": [
"USA"
],
"document_number": "1",
"document_type": "passport",
"full_name": {
"last_name": "John",
"middle_name": "Jack",
"first_name": "Dan"
}
"document_expiration_date": "2020-12-03",
}
This is what I am trying to achieve
{
"label": [
"user"
],
"property": {
"person_name": "name",
"fullname": {
"last": "John",
"middle": "Jack",
"first": "Dan"
}
}
"id": {
"expiry_date": "2020-12-03",
}

How to send array request in body parameter retrofit android

This is my Request which i need to send in #Post request with Data as a key. Please help me, I am stuck since 2 days.
[
{
"barcodeList": "abc",
"fieldboyId": "17",
"lattitude": "37.4219513",
"longitude": "-122.0841169",
"quantity": "2",
"refrenceId": "1",
"sampleId": null,
"sampleName": null,
"sampleType": null,
"type": "Barcode"
},
{
"barcodeList": "acd",
"fieldboyId": "17",
"lattitude": "37.4219513",
"longitude": "-122.0841169",
"quantity": "1",
"refrenceId": "1",
"sampleId": null,
"sampleName": null,
"sampleType": null,
"type": "Barcode"
}
]
You could make these classes:
public class RequestBody {
List<Data> data;
public class Data {
String barcodeList;
String fieldboyId;
String lattitude;
String longitude;
String quantity;
String refrenceId;
String sampleId;
String sampleName;
String sampleType;
String type;
}
}
and in the interface something like
#POST("/api/path")
Call<Something> myPostRequest(#Body requestBody: RequestBody);

Spring Data Rest + Spring Data Mongo - can't update numer of elements on list in object

so I have got a problem with updating object which contain a list of elements. My object definition:
public class Project {
private String _id;
private String name;
private List<Pair> config;
}
And the Pair object:
public class Pair {
private String key;
private String value;
}
I'm using Spring Rest repository to provide the Rest Api and everything is stored in mongodb. Just using the simple interface to create mongoRepository
#RepositoryRestResource(collectionResourceRel = "project", path = "projects")
public interface ProjectRepository extends MongoRepository<Project, String>{
Project findByName(String name);
}
When I create a project object with json (sending POST to /projects):
{
"name": "test_project",
"config": [{
"key": "port",
"value": "12"
},{
"key": "port2",
"value": "123"
}]
}
I have got the proper response and object has been created:
{
"_id": "58c916fad76a3a186731ad28",
"name": "test_project",
"createdAt": "2017-03-15T10:27:06.295+0000",
"modifiedAt": "2017-03-15T10:27:06.295+0000",
"config":[
{
"key": "port",
"value": "12"
},
{
"key": "port2",
"value": "123"
}]
}
So right now I would like to send PUT to update my object and I'm getting strange results:
For example sending following body with PUT to
localhost:8151/projects/58c916fad76a3a186731ad28
{
"name": "test_project",
"config": [{
"key": "port",
"value": "12"
}]
}
So I want to remove one element from list. The response is (Status OK):
{
"_id": "58c916fad76a3a186731ad28",
"name": "test_project",
"createdAt": "2017-03-15T10:27:06.295+0000",
"modifiedAt": "2017-03-15T10:27:06.295+0000",
"config":[
{
"key": "port",
"value": "12"
},
{
"key": "port2",
"value": "123"
}]
}
So the number of elements didn't change what I expected (my expectations was that the new list replace the old one). Next test:
I would like to add one new element to list:
{
"name": "test_project",
"config": [{
"key": "port",
"value": "12"
},{
"key": "port1",
"value": "13"
},{
"key": "port2",
"value": "14"
}]
}
Gives following result:
{
"_id": "58c916fad76a3a186731ad28",
"name": "test_project",
"createdAt": "2017-03-15T10:27:06.295+0000",
"modifiedAt": "2017-03-15T10:27:06.295+0000",
"config":[
{
"key": "port",
"value": "12"
},
{
"key": "port1",
"value": "13"
}]
}
New element hasn't been added but the second element has changed.
It looks like instead of List mongo save it as an array and can't change the size but can update the element. Am I right?
But, if it would be true the next test should return the same result:
I'm sending the empty list of config and I'm expect that I will have an two-element list.
{
"name": "test_project",
"config": []
}
But what is strange for me I have got the following result:
{
"_id": "58c916fad76a3a186731ad28",
"name": "test_project",
"createdAt": "2017-03-15T10:27:06.295+0000",
"modifiedAt": "2017-03-15T10:27:06.295+0000",
"config":[]
}
So the number of elements has been updated.
To be honest right now I'm totally confused how it works. Could anyone explain how Spring rest repository handle this action and propose a proper solution for this problem?
I am having the same issue. As a workaround you can send a PATCH request. This updates the array properly.

Parsing Json array from webservice to android

I am trying to parse this json data from web service to android using volley.
This is the json array to be parsed.
[
{
"id":"1",
"conf_room_name":"Tadoba"
},
{
"id":"2",
"conf_room_name":"Melghat"
},
{
"id":"3",
"conf_room_name":"Ranthambore"
},
{
"id":"4",
"conf_room_name":"Corbett"
},
{
"id":"5",
"conf_room_name":"Pench"
}
]
[
{
"id":"1",
"area":"Mafatlal"
},
{
"id":"2",
"area":"Andheri"
}
]
[
{
"id":"1",
"type":"Is Personal"
},
{
"id":"2",
"type":"Meeting"
}
]
I am using this code to get the value out of my json array object ot different arraylists.
RequestQueue requestQueue2= Volley.newRequestQueue(this);
// RequestQueue requestQueue3= Volley.newRequestQueue(this);
// Create json array request
JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST,"http://170.241.241.198/test.php",new Response.Listener<JSONArray>(){
public void onResponse(JSONArray jsonArray){
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject jsonObject=jsonArray.getJSONObject(i);
stringArray_conf.add(jsonObject.getString("conf_room_name"));
stringArray_area.add(jsonObject.getString("area"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Error", "Unable to parse json array");
}
});
requestQueue2.add(jsonArrayRequest);
Only 1st array is being filled properly not the other one. I get outofboundsindex exception whenever i try using values from my 2nd arraylist.
All this happens on a button click only i want this to happen when i load my page.
Any help will be appreciated.
Make JSON as Array as below:
[
[
{
"id": "1",
"conf_room_name": "Tadoba"
},
{
"id": "2",
"conf_room_name": "Melghat"
},
{
"id": "3",
"conf_room_name": "Ranthambore"
},
{
"id": "4",
"conf_room_name": "Corbett"
},
{
"id": "5",
"conf_room_name": "Pench"
}
],
[
{
"id": "1",
"area": "Mafatlal"
},
{
"id": "2",
"area": "Andheri"
}
],
[
{
"id": "1",
"type": "Is Personal"
},
{
"id": "2",
"type": "Meeting"
}
]
]
Or Object (easier to reading and understanding):
{
"rooms": [
{
"id": "1",
"conf_room_name": "Tadoba"
},
{
"id": "2",
"conf_room_name": "Melghat"
},
{
"id": "3",
"conf_room_name": "Ranthambore"
},
{
"id": "4",
"conf_room_name": "Corbett"
},
{
"id": "5",
"conf_room_name": "Pench"
}
],
"areas": [
{
"id": "1",
"area": "Mafatlal"
},
{
"id": "2",
"area": "Andheri"
}
],
"types": [
{
"id": "1",
"type": "Is Personal"
},
{
"id": "2",
"type": "Meeting"
}
]
}
PHP code maybe like below:
<?php
$sqlroom = mysql_query("SELECT * FROM `room_table`");
$room_rows = array();
while($r = mysql_fetch_assoc($sqlroom)) {
$room_rows[] = $r;
}
$sqlarea = mysql_query("SELECT * FROM `area_table`");
$area_rows = array();
while($r = mysql_fetch_assoc($sqlarea)) {
$area_rows[] = $r;
}
$sqltype = mysql_query("SELECT * FROM `type_table`");
$type_rows = array();
while($r = mysql_fetch_assoc($sqltype)) {
$type_rows[] = $r;
}
$result = array();
$result["rooms"] = $room_rows;
$result["areas"] = $area_rows;
$result["types"] = $type_rows;
echo json_encode($result);
?>
You seem to be trying to parse three different types of data: conference rooms, areas (which presumably contain conference rooms?) and some information about either one (although it's not clear which). It therefore doesn't make sense to try and store these in a single array as each element contains a different data structure compared to the other two.
If the type is a description of one of the other two objects then it should be compassed within that object, not treated as a separate one. A room doesn't necessarily have to sit within an area but it might also make sense to have it there.
You say you are "pulling all these values from a mysql server and then using php to encode the json data which gives me the structure of the json array" which implies you do not have direct access to the JSON structure, but you should still have access to the PHP structure. The JSON encoder will use the design of the PHP array / object to structure the JSON so, for this to work you need to create more-or-less matching PHP and Java objects at either end of the serialization process.
For instance:
$obj = (object) array
('id' => '1', 'area' => 'Mafatlal', 'rooms' => array
('id' => '1', 'conf_room_name' => 'Tadoba', 'type' => 'Is Personal'),
...
('id' => '2', 'area' => 'Andheri', 'rooms' => array...
);
and
public class Area {
private int id;
private String area;
private Room[] rooms;
}
public class Room {
private int id;
private String conf_room_name;
private String type;
}
Note that, in contrast to the usual Java camel-case naming convention, object variables will usually have to match the incoming JSON variable name (i.e.: conf_room_name instead of confRoomName).
You need to add values using for loop.
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.toString.contains("conf_room_name"))
stringArray_conf.add(jsonObject.getString("conf_room_name"));
else if(jsonObject.toString.contains("area"))
stringArray_area.add(jsonObject.getString("area"));
} catch (JSONException e) {
e.printStackTrace();
}
}

Parsing Facebook Graph API response

I'm working on Facebook Scores API for an android app. I query for the user score by accessing the user graph:
https://graph.facebook.com/user_id/scores&access_token={user_access_token}
I get a response like:
{
"data": [
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 1200,
"application": {
"name": "QuizzlePeople",
"namespace": "quizzlepeople",
"id": "176694722487191"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 1,
"application": {
"name": "Friend Smash!",
"namespace": "friendsmashsample",
"id": "480369938658210"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 0,
"application": {
"name": "Wordox",
"namespace": "wordox-the-game",
"id": "227993680602156"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 0,
"application": {
"name": "SongPop",
"namespace": "songpop",
"id": "323595464361460"
}
}
]
}
How do I extract useful data from this?
I'm trying to take something as a JSONObject, using:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("https://graph.facebook.com/me?fields=score&access_token=" + token);
HttpResponse resp = client.execute(get);
Log.i("info1", resp.toString());
// Parse the response
HttpEntity responseEntity = resp.getEntity();
String response = EntityUtils.toString(responseEntity);
Log.i("info1", response);
JSONObject result = new JSONObject(response);
JSONArray arr = result.getJSONArray("data");
Log.i("info2", arr.toString());
just to see if I can take anything, say, the array named 'data'. Yet the logcat does not show me anything. It shows the first 2 logs, but not the 3rd. Any ideas?
That looks like JSONObject. You can loop thru it and do whatever you wish with the data.
Have a look at http://json.org/ for documentation for a specific language (I presume you need java so click on the java link).
I appended the data to a table to give you an idea ( jquery / javascript ):
fiddle:http://jsfiddle.net/H8LNB/4/

Categories