我正在开发一个使用PHP和JSON作为解析器访问MySQL数据库的android应用程序。目前,我开发它只是为了从数据库表中检索数据。它在模拟器2.2(froyo)上运行良好,但是当我尝试在更高版本的模拟器上运行它时,它不会检索数据。 (我已经搜索了与此相关的主题,但没有找到任何主题)。

我猜我正在使用JSON类,或者在JSON中未使用HTTP连接器。
在这里,我粘贴了我的JsonParse.java代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.*;
import android.util.Log;
public class JsonParse {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JsonParse() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error Converting Result" + e.toString());
    }

    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error Parsing Data" + e.toString());
    }
    return jObj;

}
}


我正在使用的DefaultHTTPClient是否有东西,还是应该再使用另一个?

对于URL,我使用一个名为ServerProcessor.java的单独类,该类仅包含一种这样的方法:

public class ServerProcessor extends DbConnection {
String URL = "http://10.0.2.2/myURL/serverandroid.php";
String url = "";
String response = "";

public String retrieveData() {
    try {
        url = URL + "?operation=retrieve";
        response = call(url);
    } catch (Exception e) {
    }
    return response;
}
}


请帮我解决问题。
提前致谢

最佳答案

似乎您没有使用AsyncTask发出请求。较旧的android版本将在主线程中执行此操作,但较新的版本将在执行此操作时引发异常。

因此,您应该在logcat中查看是否发生异常

开发人员指南中有关联网的更多信息:http://developer.android.com/training/basics/network-ops/connecting.html

10-07 19:38
查看更多