我试图通过收集JSON格式的信息来获得与MySQL数据库的连接。我的代码收到这些信息。我创建了一个扩展AsyncTask
的类,在我的onPostExecute
类中,我希望将完整的JSONArray
保存到JSONArray
类之外的其他AsyncTask
。这样做我没有收到错误消息,但是一旦我想使用这个对象,我的代码崩溃了,我得到一个java.lang.NullPointerException
,我的新JSON数组为空。
有人能帮助我吗?
class task extends AsyncTask<String, String, Void>
{
InputStream is = null ;
protected Void doInBackground(String... params) {
String url_select = "http://pois.lima-city.de/test1.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
//Toast.makeText(MainActivity.this, "Please Try Again", Toast.LENGTH_LONG).show();
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
try {
LatLng coordinates;
String between = "";
JSONArray JarrayP = new JSONArray(result);
myJSONArray = JarrayP;
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
PS:它在另一个班级里面。
答案 0 :(得分:0)
如果仅将其用于创建json数组,那么我没有看到使用该result
字符串的重点。尝试从sb.toString()
返回doInBackground
(而不是null)。为此,您需要修改您的asynctask。您的第三个通用变量应该是String,并且需要在postExecute
标头中设置String参数。然后用该字符串创建你的json数组。
答案 1 :(得分:0)
您目前正在Void
返回doInBackground(String...)
。这就是为什么你在onPostExecute
中获得null的原因。将您的班级更改为:
public class YourTask extends AsyncTask<String,Void,String>{
....
然后在doInBackground()
:
....
return result;