how to send long array from android to php server - php

I try to send long array from android to PHP via JSON. I did the same thing with Javascript and worked but with JAVA it gets confusing. When I send the parameters, long array list changes.
This is the part that creates the list.
JSONArray list = new JSONArray();
for (int i = 0; i < users.size(); i++) {
list.put(users.get(i).getId());
}
This is the code in JAVA that send the data.
public JSONObject sendFacebookFriendList(JSONArray list) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("list", list.toString()));
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.getJSONFromUrl(accountServer, params);
return json;
}
And this is the code that receives the data in PHP.
$list = $_POST['list'];
$result = array("success" => 1, "list" => $list);
While sending with Javascript the $list variable was becoming long array directly but I couldn't send it same way with JAVA.
When I send the list back to JAVA from PHP without any change I see that each array element has \" at the head and the end
So this list:
list= ["517565130","523709375","524503024","524620558","524965930", ...
becomes this:
"list":"[\"517565130\",\"523709375\",\"524503024\",\"524620558\", ...
So I cannot parse this array in PHP.
I couldn't find any way to send the long/int array in a proper way.
I appreciate if someone can fix this or suggest another way.
Thanks

I solved the problem. The thing I skipped was decoding the json array that encoded at android part. So after getting the posted data it is needed to be decoded like this;
$list = $_POST['list'];
$obj = json_decode($list);
And then I can use $obj as array.

Related

jsonObject.getString("String in UTF8" ) giving blank

I am fetching a string from my MySql DB on and online server using webservice in JSON format.
I am able to see that Android Studio is fetching it correctly as I see it in debugging mode.
But when I go ahead and add it to a List list, I get nothing.
Here's some more info:
What I am getting:
{"products":[{"veg_name_eng":"Corn","veg_name_hindi":"मक्का"}],"success":1}
My concern is with: "veg_name_hindi":"मक्का"
When I go ahead and try to put it in a dataitem list, I get nothing:
public static List<DataItem> dataItemList;
dataItemList.add(jsonObject.getString(veg_name_eng),jsonObject.getString(veg_name_hindi))
veg_name_eng and veg_name_hindi are the column names at my table.
After the above code I get dataItemList = null, So nothing is adding to it.
In my server side MySql DB, I am using UTF-8 encoding.
I am using android studio.
UPDATE 1:
I am parsing the JSON as :
JSONObject jsonObject = new JSONObject(myJSONString);
veg_list = jsonObject.getJSONArray("products");
try {
while (TRACK < veg_list.length()) {
JSONObject jsonObject = veg_list.getJSONObject(TRACK);
addItem(new DataItem(jsonObject.getString(veg_name_eng), jsonObject.getString(veg_name_hindi)));
TRACK = TRACK + 1;
}
} catch (JSONException e) {
e.printStackTrace();
}
// and the addItem function is as follows:
private static void addItem(DataItem item) {
dataItemList.add(item); //While Debugging, I can see that value of item is correct. (i.e., item: DataItem{veg_name_eng='Cork', veg_name_hindi='मक्का'} )
dataItemMap.put(item.getVeg_id(), item);
}
Firstly, Make a model of the your JSON String using
http://json2java.azurewebsites.net/
and then map your JSON String to your Model using Gson. It's much easy to use.
Another way to get your required String for this particular result is parse json string yourself.
For Example :
String vegNameEng,vegNameHindi;
vegNameEng = vegNameHindi = "";
try{
JSONObject obj = new JSONObject(yourJsonString);
JSONArray arr = obj.getJSONArray("products");
vegNameEng = arr.getJSONObject(0).getString("veg_name_eng");
vegNameHindi = arr.getJSONObject(0).getString("veg_name_hindi");
}catch(JSONException ex){
}
Now vegNameEng and vegNameHindi have the required data.
I figured out, It was a silly mistake, the variable I was using to put data into the database was overwritten by some other variable with the same name. Closing the thread for now. Thanks #Umer-Farooq.

Improving the latency of server response under high-volme traffic [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an e-commerce application and it works perfectly when 5 to 10 users are using it.
But it becomes really slow when it is used by 50-60 people.
Currently I am using MySQL & PHP.
I am calling .php file which has MySQL connectivity code. And from there I am fetching JSON response.
Below is my code:
class Items extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", Itemid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_allitems, "GET",
params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
products = json.getJSONArray(TAG_ITEMS);
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ITEMID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
This is my PHP code:
$result = mysql_query("SELECT * FROM item_master") ;
// check for empty result
if (mysql_num_rows($result) > 0) {
$response["items"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$item = array();
$item["id"] = $row["id"];
$item["code"] = $row["code"];
$item["name"] = $row["name"];
$item["description"] = $row["description"];
$item["price"] = $row["price"];
$item["image1"] = $row["image1"];
// push single product into final response array
array_push($response["items"], $product);
}
// success
$response["psuccess"] = 1;
....
}
So what are the best approaches for optimization in this scenario ? When more than 1000 users will access this app, the app should be responsive and load items quickly.
On the server side, you need to look into techniques for managing a large number of connections, such as enabling servers to handle high-volume traffic, as well as network-level issues like dynamic load balancing.
On the client side, you can make use of Volley with okHttp. You'd also have to enable the usage of okHttp on the server side for that to work properly.
References:
1. Tactics for using PHP in a high-load site.
2. Separating dynamic and static content on high traffic website.
3. How to implement Android Volley with OkHttp 2.0?
4. Using SPDY on Your Web Server.

Android PHP Json

I have looked around for over a few hours and most of the post I see are from way back when, so maybe I just don't understand or it might be outdated. I have two problems.
I have an Json object and Json Array that comes out like this:
{"command":"update", "Data":["first data","second data","third data","fourth data"]}
I want it it to read like this:
{"command":"update", "Data":[{"1":"first data"},{"2":"second data"},{"1":"third data"},{"2":"fourth data"}]}
I am unclear how to add the 1 & 2 so I can know what to pull on the php side.And it might not be the proper format either, but you will get an ideal. Android code:
JSONObject parent = new JSONObject();
JSONArray child = new JSONArray();
child.put("first data");
child.put("second data");
parent.put("Data", child);
Next problem on my php side is pulling the data so I can put it into my database and I am unsure exactly how this is done:
// DECODE OUR JSON FROM ANDROID
$data = json_decode(file_get_contents('php://input'), true);
// FOR LOOP TO INSERT DATA INTO DATABASE
for($i=0; $i<count($obj['Data']); $i+=2)
{
// need to get 1 & 2 values to insert into database
//$first = NEED VALUE OF 1
//$second = NEED VALUE OF 2
// mysqli statement to insert into database
$Q = "INSERT INTO `DATA_TABLE` (data1, data2) VALUES ('$first', '$second');
mysqli_query($conn, $Q);
}
Change your code to
JSONObject parent = new JSONObject();
JSONArray child = new JSONArray();
child.put({ "1", "first data" });
child.put({ "2", "second data" });
But I would more likely store your data as an object inside an array with each object being one insert into your database.
JSONObject parent = new JSONObject();
JSONArray child = new JSONArray();
JSONObject item1 = new JSONObject();
JSONObject item2 = new JSONObject();
...
item1.name = "Item 1 name";
item1.rating = "Item 1 rating";
...
child.put(item1);
child.put(item2);
Then you can iterate through each item in the data array and know that it contains all the data you need to populate your database.

sending array from android to php

I have an array
ArrayList<String> selectedItems = new ArrayList<String>();
and few strings
private String sq,tr;
am sending these values to a remote server via POST request
nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("sq", sq));
nameValuePair.add(new BasicNameValuePair("tr", tr));
nameValuePair.add(new BasicNameValuePair("sub[]", selectedItems);
My problem is am able to send strings but when I try to send the array am getting errors
Please suggest me the best way to send array as well as strings via post method or guide me if am making some mistake.
try to put that in loop
for (int i = 0; i < selectedItems.length; i++) {
nameValuePairs.add(new BasicNameValuePair("sub[]",selectedItems[i]));
}

JSONObject arrayList parsing in php

I am new to JSON. KIndly help me with the JSON parsing in php sent from android.
I have a class A, having members phoneNumber and name. I have an arrayList of object A
private ArrayList<A> contactList = new ArrayList<A>();
contactList.add(a1);
contactList.add(a2); [objects of A]
Now I am trying to send this arrayList to php server using JSON.
JSONObject json = new JSONObject();
json.put("contactList", contactList);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("");
StringEntity se = new StringEntity("JSON: " + json.toString());
post.setEntity(se);
HttpResponse resP = client.execute(post);
Please let me know how to I parse it in the php server side to get phoneNumber and name of each object A.
I tried to create a same class A in the php server side and trying this way.
<?php
$contactList = array();
if(isset($_POST["contactList"])) {
$contactList = json_decode($_POST["contactList"]);
include_once './eachContactClass.php';
foreach ($contactList->contactList as $eachContact) {
$eachObj = new eachContactClass();
$eachObj = $eachContact;
$name = $eachObj->getName();
$phoneNumber = $eachObj->getPhone();
}
}
Please let me know whether the approach is correct, or kindly help me to correct it
First of all, may I suggest you to use a library for handling the JSON serialization/deserialization. GSON would be suited for your work.
Then, you should check the result JSON for validity before sending it to any remote server.
To parse it in PHP, use the json_decode() function that will return your an object representing your JSON. You can also get a hash if you prefer, just look in the doc.
I think your problem is that your JSON is invalid, as the JSONObject doesn't correctly serialize your ArrayList. Your should probably check that.

Categories