我编写了一个php文件,它接受一个数组,将其展开并执行查询。
问题:
我传递的数组是:127 129 121
在logcat JSON响应的android端只包含第一个数组项的查询结果。
{
"users": [
{
"lat": "0",
"lng": "0",
"uid": "127"
},
{
"lat": "-33.866",
"lng": "151.195",
"uid": "127"
}
],
"success": 1,
"message": "lat lng"
}
但我传递相同的数组并在浏览器中测试文件(使用postman)我得到以下json响应:
{
"users": [
{
"lat": "0",
"lng": "0",
"uid": "127"
},
{
"lat": "-33.866",
"lng": "151.195",
"uid": "127"
}
],
"success": 1,
"message": "lat lng"
}
{
"users": [
{
"lat": "-18.142",
"lng": "178.431",
"uid": "129"
}
],
"success": 1,
"message": "lat lng"
}
{
"users": [
{
"lat": "37.423",
"lng": "-122.091",
"uid": "121"
},
{
"lat": "-31.9906066",
"lng": "148.8977051",
"uid": "121"
}
],
"success": 1,
"message": "lat lng"
}
我希望所有用户的记录都是这个json响应。为什么我在php和android端获得不同的响应?我想要我在数组中传递的所有用户的记录。救命!! PHP代码:
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["uid"]) ) {
$uid= explode(' ', $_GET['uid']);
foreach ($uid as $value) {
$result=mysql_query("SELECT lat,lng,uid FROM location1 WHERE uid='$value' AND date='27-11-2014' ");
if(mysql_num_rows($result) > 0)
{
$response["users"] = array();
while($row = mysql_fetch_array($result))
{
$users = array();
$users["lat"] = $row["lat"];
$users["lng"] = $row["lng"];
$users["uid"] = $row["uid"];
// user node
array_push($response["users"], $users);
}
$response["success"] = 1;
$response["message"] = "lat lng";
// echoing JSON response
echo json_encode($response)."<br>";
}
else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response)."<br>";
}
}
}
?>
HERE是android代码:
package com.example.newtabs;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.utils.Constants;
import com.example.utils.Utils;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class Circle_SubTabFriends_Map extends Activity {
String user_email,user_id;
Button add;
String end_lat;
String end_lng;
String[] lv_items;
int len;
String s;
String detail;
StringBuilder sb;
JSONParser jsonParser = new JSONParser();
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
static String url_circle_friends = Constants.url_circle_friends;
static String url_location_friend_circle = Constants.url_location_friend_circle;
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
private static final String TAG_UID = "uid";
private static final String TAG_NAME = "name";
// users JSONArray
JSONArray users = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// new GetCurrentLocation().execute();
new LoadAllUsers().execute();
new GetCurrentLocation().execute();
//function for maintaining session
user_id=Utils.GetPreferences("user_id",this);
user_email=Utils.GetPreferences("user",this);
if(user_email.length() <0)
{
Intent i = new Intent(getApplicationContext(), Locator_Registration.class);
startActivity(i);
}
setContentView(R.layout.locator_map);
add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching All products Activity
Intent i = new Intent(getApplicationContext(), Circle_SubTabFriends_AddCircle.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all users by making HTTP Request
* */
class LoadAllUsers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", user_email));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_circle_friends, "GET", params);
// Check your log cat for JSON reponse
Log.d("circle_subtabfrinds ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// users found
// Getting Array of users
users = json.getJSONArray(TAG_USERS);
lv_items = new String[users.length()];
len = lv_items.length;
// looping through All Users
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_UID);
String name = c.getString(TAG_NAME);
lv_items[i] = id+","+name;
Log.d("CHECKING! ", id+name);
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all users
//pDialog.dismiss();
}
}
/**
* Background Async Task to Get History
* */
class GetCurrentLocation extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Getting user's history in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
sb = new StringBuilder();
String[] outputStrArr = new String[len];
for (int i = 0; i < len; i++) {
outputStrArr[i] = lv_items[i];
String[] separated = outputStrArr[i].split(",");
s = "";
String idpart = separated[0];
String namepart = separated[1];
detail = idpart + " " ;
Toast.makeText(getApplicationContext(), detail, Toast.LENGTH_LONG)
.show();
sb.append(detail);
}
Toast.makeText(getApplicationContext(), /*selectedItems[i]*/ sb,
Toast.LENGTH_LONG).show();
String a=sb.toString();
a=a.trim();
Log.d("A!", a);
params.add(new BasicNameValuePair("uid", a));
// getting history by making HTTP request
// Note that user history url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_location_friend_circle, "GET", params);
// check your log for json response
Log.d("circle location", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("RUNNN", "SUCCESS");
// successfully received history
users = json.getJSONArray(TAG_USERS); // JSON Array
Log.d("array users", users.toString());
lv_items = new String[users.length()];
len = lv_items.length;
// get first object from JSON Array
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
String lat = c.getString(TAG_LAT);
String lng = c.getString(TAG_LNG);
lv_items[i] = lat + ',' + lng;
Log.d("FOOL!", lv_items[i].toString());
}
} else {
// history not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
GoogleMap map = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
-18.142, 178.431), 2));
sb = new StringBuilder();
String[] outputStrArr = new String[len];
for (int i = 0; i < len; i++) {
outputStrArr[i] = lv_items[i];
String[] separated = outputStrArr[i].split(",");
s = "";
//end_lat = separated[0];
//end_lng = separated[1];
//Toast.makeText(getApplicationContext(), "end"+end_lat+"-"+end_lng,Toast.LENGTH_LONG).show();
String latpart = separated[0];
//Toast.makeText(getApplicationContext(), latpart,Toast.LENGTH_LONG).show();
String lngpart = separated[1];
map.addMarker(new MarkerOptions().position(new LatLng(Double
.valueOf( latpart).doubleValue(), Double
.valueOf(lngpart).doubleValue())));
}
}
}
}