gpt4 book ai didi

java - 尽管之前在 AsyncTask 类中定义,但 JSON 对象为空?

转载 作者:行者123 更新时间:2023-11-29 03:32:48 26 4
gpt4 key购买 nike

我试图通过收集 JSON 格式的信息来连接到 MySQL 数据库。我的代码收到这些信息。我创建了一个扩展 AsyncTask 的类,在我的 onPostExecute 类中,我想将完整的 JSONArray 保存到不同的 JSONArrayAsyncTask 类之外。这样做我不会收到错误消息,但是一旦我想使用此对象,我的代码就会崩溃,并且我会收到 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:它在另一个类中。

最佳答案

您当前在 doInBackground(String...) 中返回 Void。这就是您在 onPostExecute 中得到 null 的原因。将您的类(class)更改为:

public class YourTask extends AsyncTask<String,Void,String>{
....

然后在 doInBackground() 中:

....
return result;

关于java - 尽管之前在 AsyncTask 类中定义,但 JSON 对象为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27929126/

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