我试图以JSON的形式从服务器获取一些数据。我不知道为什么,但我收到的数据是空的。该文件可通过以下链接访问:
http://andreid.imcserver.ro/test/service.php
服务器端代码非常简单:
<?php
// Create connection
$con=mysqli_connect("localhost","*****","*****","******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// --------- This code is just for testing ---------
$minLat = $_REQUEST["minLat"];
$maxLat = $_REQUEST["maxLat"];
$minLon = $_REQUEST["minLon"];
$maxLon = $_REQUEST["maxLon"];
$file_handle = fopen("testFile.txt", "w");
$file_contents = $_POST;
fwrite($file_handle, $minLat);
fwrite($file_handle, $maxLat);
fwrite($file_handle, serialize($file_contents));
fclose($file_handle);
// ---------------------------------------------
$sql = "SELECT * FROM articolePeHarta";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo "{ \"posts\": ";
echo json_encode($resultArray);
echo "}";
}
// Close connections
mysqli_close($con);
?>
我现在使用的代码(我尝试了几种替代方法)就是这个:
ArrayList<Article> articole = new ArrayList<Article>();
JSONArray finalResult;
// url to get all products list
private static String url_all_products = "http://andreid.imcserver.ro/test/service.php";
BufferedReader reader = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Loading products in Background Thread
new LoadAllArticles().execute();
}
...
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllArticles extends AsyncTask<String, String, String> {
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<ContentValues> params = new ArrayList<ContentValues>();
//params.add(new BasicNameValuePair());
// getting JSON string from URL
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_all_products);
//JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
try{
HttpResponse response = client.execute(httppost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if ( statusCode == 200){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
reader = new BufferedReader(new InputStreamReader(content));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
Log.e("------------->",line);
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
finalResult = new JSONArray(tokener);
// looping through All Products
for (int i = 0; i < finalResult.length(); i++) {
JSONObject c = finalResult.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TAG_TITLE);
String subTitle = c.getString(TAG_DETAILS);
Article art = new Article(title,subTitle);
articole.add(articole.size(),art);
}
}else {
Log.e("====>", "Fail to download file");
}
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if(reader!=null) {
showDialog(MapsActivity.this,"It worked", reader.toString());
}
else{
showDialog(MapsActivity.this,"Sorry", "Hai Rapid!");
}
showDialog(MapsActivity.this,"Rapid",String.valueOf( articole.size()));
for (int i = 0; i < articole.size(); i++){
showDialog(MapsActivity.this,"Hai Rapid!", articole.get(i).articleTitle);
}
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
问题在于,没有元素......我做错了什么?
非常感谢你的帮助!
答案 0 :(得分:1)
此行中的错误
finalResult = new JSONArray(tokener);
它不是jsonArray,它是json Object
将其替换为以下内容。
JSONObject job = new JSONObject(tokener);
并像这样创建循环
for (int i = 0; i < job.length(); i++) {
Log.e("json object", job.getString("posts"));
//Do whatever you want here
//Feetch the data from json object
}