gpt4 book ai didi

php - 安卓连接mysql

转载 作者:行者123 更新时间:2023-11-30 00:38:30 24 4
gpt4 key购买 nike

我有以下抛出空异常的代码

    HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://exemple.com/android_webservice/index.php");

try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("lat", String.valueOf(l.getLatitude()) ));
nameValuePairs.add(new BasicNameValuePair("lng", String.valueOf(l.getLongitude()) ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

//I belive exception is thrown somewhere above this

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (Exception e){
Toast.makeText(map.getApplicationContext(), "Exception here", Toast.LENGTH_SHORT).show(); // Toast is displayed so the exception is this one
}

它访问的Web服务是PHP。我使用 $_REQUEST 来获取纬度。和脚本内的 lng,我相信这应该不是问题。另外,网络服务器是否有可能不接受手机向其发出的请求?

最佳答案

难道你没有在asynctask或UI-Thread以外的其他线程中访问这个方法/httpresponse吗?所以你得到一个空指针异常,因为你的 reuqest 不起作用并且你没有从服务器得到任何响应?

如果是这样,请记住,从主线程访问网络将导致 NetworkOnMainThreadException

为了避免这种情况,请使用 Asynctask,如下所述: http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

或这里 http://developer.android.com/reference/android/os/AsyncTask.html

关于php - 安卓连接mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21973752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com