I have a program that takes strings from MySQL database, creates SqlLite database with same strings and then displays them in Android application ListView.
Problem is that when I get response from PHP side it shows Lithuanian charactes as "?", but I use
JSON_UNESCAPED_UNICODE
in json_encode function. Where is the problem?
I want to mention that MySql unicode is set to "utf8_lithuanian_ci"
PHP file :
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getMarsrutaiCount();
$a = array();
$b = array();
if ($users != false){
$no_of_users = mysqli_num_rows($users);
while ($row = mysqli_fetch_array($users)) {
$b["id"] = $row["id"];
$b["marsrutas"] = $row["marsrutas"];
$b["pasirinkimas_id"] = $row["pasirinkimas_id"];
array_push($a,$b);
}
echo json_encode($a, JSON_UNESCAPED_UNICODE);
}
JSON Response from Android side :
ArrayList<HashMap<String, String>> usersynclist;
usersynclist = new ArrayList<HashMap<String, String>>();
// Create GSON object
Gson gson = new GsonBuilder().create();
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
// If no of array elements is not zero
if(arr.length() != 0){
// Loop through each array element, get JSON object which has userid and username
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
if(veiksmas == 1) {
JSONObject obj = (JSONObject) arr.get(i);
System.out.println(obj.get("id"));
System.out.println(obj.get("marsrutas"));
System.out.println(obj.get("pasirinkimas_id"));
// DB QueryValues Object to insert into SQLite
queryValues = new HashMap<String, String>();
// Add userID extracted from Object
queryValues.put("id", obj.get("id").toString());
// Add userName extracted from Object
queryValues.put("marsrutas", obj.get("marsrutas").toString());
queryValues.put("pasirinkimas_id", obj.get("pasirinkimas_id").toString());
// Insert User into SQLite DB
controller.insertMarsrutas(queryValues);
Related
I've done a long search before posting, none of solutions work for me.
I'm creating an Android application, using JSON and PHP;
PHP
/**
*
LOT OF USELESS THING
*
*/
//Attributing values of $OUTPUT
$q=mysql_query($query);
if (!$q)
die(mysql_error()); // You'll be notified if there's any syntax error in your query.
$OUTPUT = array(array());
if ($q && #mysql_num_rows($q) > 0) {
// looping through all results
// products node
while($e=#mysql_fetch_assoc($q)){
if (!empty($e['title'])){
$u = Array();
$u['id'] = mb_convert_encoding($e['id'], 'UTF-8');
$u['title'] = mb_convert_encoding($e['title'], 'UTF-8');
$u['location_search_text'] = mb_convert_encoding($e['location_search_text'], 'UTF-8');
$OUTPUT[] = $u;}
//echo "<br>************<br>";*/
//$OUTPUT[] = $e;
}
}
print(json_encode($OUTPUT));
Now, this is the output of json:
[[],{"id":"796","title":"ANSEJ ORAN \/Agence de Soutien \u00e0 l'Emploi des Jeunes d'Oran","locat ...etc
If you see, there's a []; an empty array, which of course causes me problem in Java, when parsing data with
JSONArray jArray = new JSONArray(result);
Occuring me a JSONExcpetion:
Error parsing data org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject
Not $OUTPUT = array(array()); - this create empty array inside
But $OUTPUT = array();
I'm sending a JsonArray from my android application as this:
final JSONArray data = new JSONArray();
try{
for(int i = 0; i<contactsList.size(); i++){
JSONObject jobj = new JSONObject();
ObjectContacts ob = contactsList.get(i);
jobj.put("contactid", ob.getContact_id());
jobj.put("mobile", ob.getNumber());
data.put(jobj);
}
}
And the resulting Array that my server receive.
[
{"contactid":"3","mobile":"(545) 454-5445"},
{"contactid":"1","mobile":"(880) 939-5212"},
{"contactid":"2","mobile":"822895456165"}
]
I need to fetch mobile numbers from this array and perform a Db Operation to look if this mobile number exist or not. How can I access each mobile and perform a Query? The query will consist of looking for mobile number existence and if it's true, it will fetch the name belonging to the mobile number and finally return an array back to the mobile application in JSONArray format which will consist of contact id, mobile, status(Yes or No), name.
Time won't be an issue but sometimes the array may contain 300-400 mobile number depending on user's contact.
Update
Here's the new Php Code that I implemented:
$app->post('/getcontacts', function () use ($app) {
//Verifying the required parameters
verifyRequiredParams(array('data'));
//Creating a response array
$response = array();
//reading post parameters
$data = $app->request->post('data');
$data_array = json_decode($data);
foreach ( $data_array as $obj ) {
$res = array();
$db = new DbOperation();
$r = $db->checkContactExist($obj->mobile);
if($r){
$res["contactid"] = $obj->contactid;
$res["mobile"] = $obj->mobile;
$res["name"] = $obj->name;
$res["status"] = 'yes';
$res["image_small"] = $db->getImageSmall($obj->mobile);
} else {
$res["contactid"] = $obj->contactid;
$res["mobile"] = $obj->mobile;
$res["name"] = $obj->name;
$res["status"] = 'no';
$res["image_small"] = '';
}
}
$response["error"] = false;
$response["message"] = json_encode($res);
echoResponse(201, $response);
});
The response I get from server:
{"contactid":"3","mobile":"(943) 101-9713","status":"no","image_small":""}
While there should be three contacts, it could only read one.
If I just send the incoming data back to application through echo to check whether all the contacts is coming or not, then it works correct. Maybe in the loop I'm adding detail about only one contact.
Second Update
Have solved the issue by putting :
$final_res = array();
and in foreach loop
$final_res[] = $res;
thus sending this back:
json_encode($final_res);
That string will convert to a PHP array of objects, after using json_decode() on the string.
So this is how you process it
<?php
$json_string = '[
{"contactid":"3","mobile":"(545) 454-5445"},
{"contactid":"1","mobile":"(880) 939-5212"},
{"contactid":"2","mobile":"822895456165"}
]';
$json_array = json_decode($json_string);
foreach ( $json_array as $obj ) {
echo $obj->contactid . ' - ' . $obj->mobile . PHP_EOL;
}
Result:
3 - (545) 454-5445
1 - (880) 939-5212
2 - 822895456165
You should be able to take this and add any database access around this simple code
hey i am making an android app where user's request in the format of json . Their request will look like this..
JSONObject j = new JSONObject(createJson());
String url ="http://codemoirai.esy.es/test.php?UserDetails="+j;
Where j = {"Email":"code#gmail.com","Username":"xyz","Password":"xyz"}
This is what I will be sending to the test.php , i want to know how i can fetch this data and display it using php.
<?php
require "init1.php";
$jsonObject = $_GET["UserDetails"];
$obj = json_decode($jsonObject);
$email = $obj->Email;
$password = $obj->Password;
.......
echo $email; //Everthing i fetch from jsonObject is null. Why?
?>
ThankYou, is it correct how i am fetching in php??
In test.php you can catch the data with $_GET['UserDetails'] then decode it with json_decode($_GET['UserDetails')
Then you can iterate it with a foreach loop
Example:
if(isset($_GET['UserDetails'])) {
$details = json_decode($_GET['UserDetails']);
foreach($details as $key => $val) {
echo $key.' = '.$val;
}
I created an array with PHP. I need help how to read it, with Android app.
Encoded array looks like this:
["id","string 1","string 2","string 3","string 3","string 4"]
I have to be able to read all of it's elements, with Android application.
It's created with PHP with code like next:
$res = array();
$res[] = $data['id'];
$res[] = $data['string 1'];
$res[] = $data['string 2'];
$res[] = $data['string 3'];
$res[] = $data['string 4'];
return json_encode($res);
Can you please help me how to solve this?
For your example, you can use the following code to parse the response in Android. I have hardcoded the response that you are getting in the code, so you get the idea. Also I have written it in onCreate of my activity, you may write this wherever is suitable for your app.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String strJson="[\"id\",\"string 1\",\"string 2\",\"string 3\",\"string 3\",\"string 4\"]"; // This is your response, with escaped " and used as a String
try {
//Get the instance of JSONArray that contains Strings
JSONArray jsonArray = new JSONArray(strJson);
for(int i=0; i < jsonArray.length(); i++){
String data = (String)jsonArray.get(i);
Log.d("MyData",data);
}
} catch (JSONException e) {e.printStackTrace(); // Not a good idea. But left it for now}
}
If you monitor the logcat with filter MyData you will find the output as:
D/DATAIS: id
D/DATAIS: string 1
D/DATAIS: string 2
D/DATAIS: string 3
D/DATAIS: string 3
D/DATAIS: string 4
There are a lot of tutorials in web that deals with how to parse JSON in Android. You can study them to get a better idea.
I solved it, when I added names to elements of PHP array:
$res = array();
$res[0] = $data['id'];
$res[1] = $data['string 1'];
$res[2] = $data['string 2'];
$res[3] = $data['string 3'];
$res[4] = $data['string 4'];
And on Android side:
JSONObject mainObject = new JSONObject(ret);
String str1 = mainObject.optString("1").toString();
String str2 = mainObject.optString("2").toString();
String str3 = mainObject.optString("3").toString();
String str4 = mainObject.optString("4").toString();
Thank you all on help.
i have this JSON
{
"count":"3",
"num":"1",
"array":[
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":0
},
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":1
}
]
}
created it in android and send it by **HttpPost**
, i've tried a lot of ways to get the data in the php, my php file is this:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn,true);
$count = $json_data->{'count'};
$num = $json_data["num"];
$response["data"]=$count;
$response["data2"]=$num;
// echoing JSON response
echo json_encode($response);
?>
but $count and $num always returns null, any help please, and thanks.
$json_data = json_decode($josn,true);
this returns an array, not an object (which you are using later in the code). Use this to convert the json string to an object:
$json_data = json_decode($josn);
Or you could just use arrays, in which case your code should look like:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn, true); // using true to get array
$count = $json_data["count"]; // accessing array values as normal
$num = $json_data["num"]; // accessing array values as normal
$response["data"] = $count; // instead of setting $count first you could just add
$response["data2"] = $num; // the json_data array values directly to the response array
// echoing JSON response
echo json_encode($response);