【发布时间】:2017-01-02 17:46:03
【问题描述】:
我尝试从外部服务器上的 mysql 数据库获取单个数据行。到目前为止,它工作得很好。现在我尝试从服务器获取 JSONArray 以在 ListView 中显示它。我试图解释我遇到的问题。
备注:我删除了真实的 url,经过测试,url 和 php-script 都正常工作。如果我在浏览器中输入 url,脚本会以 JSON 格式提供请求的数据。
这里是我的代码部分:
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(AllProductsActivity.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) { //type must be a problem
try {
url = new URL("http://somewhere");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Post Parameter an URL anhängen
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("loge", params[0]);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "exception";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JSONObject jsonObject = new JSONObject(result.toString());
// Pass data to onPostExecute method
return jsonObject.toString(); //this might be a problem
// return (result.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
//if something went wrong, return null
return null;
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
protected void onPostExecute(String result) {
//no idea how to get ths JSONObject in the parameterlist and convert it to ArrayList
ArrayList<String> listdata = new ArrayList<String>();
String jArray = (String) result;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray(i));
}
}
第一个问题,doInBackground 函数选择哪种类型,而且我的返回应该不正确?
第二个,如何将jsonObject传递给我的函数onPostExecute?在这个位置应该使用哪种类型?
最后一个,如何将 jsonObject 变量的内容获取到我的 ArrayList 中?
另外:是的,我阅读了许多其他帖子和一些教程,但我无法将我得到的信息转移到我的示例中。
EDIT1:字符串的一部分,来自服务器:
[{"nr":"317","datum":"2016-02-09","zeit":"19:30:00","thema":"","kopfnr":"2 ","typ":"2"},{"nr":"318","datum":"2016-02-23","zeit":"20:00:00","thema":"Wandern ","kopfnr":"2","typ":"6"},{"nr":"319","datum":"2016-03-01","zeit":"18:45:00 ","thema":"Instruktion","kopfnr":"2","typ":"7"},{"nr":"320","datum":"2016-03-01","zeit ":"20:00:00","thema":"Eine Schwester stellt sich vor","kopfnr":"2","typ":"7"},{"nr":"321","datum ":"2016-03-08","zeit":"19:30:00","thema":"明镜周刊","kopfnr":"2","typ":"5"},{" nr":"322","datum":"2016-03-22","zeit":"20:00:00","thema":null,"kopfnr":"2","typ":" 6"}]
EDIT2:我按照解释错误消失了!我明白它是如何工作的。谢谢
我只剩下一个问题,如何从protected void onPostExecute( ArrayList<String> result) 获取数组列表
我以前对 asyncTask 函数的调用是:new LoadAllProducts().execute(loge); 但我可能无法 onPostExecute 更改具有返回值的函数,因为它是在 asyncTask 过程中自动调用的,对吧?
之后一切都完成了,我保证
【问题讨论】:
-
显示从
result中的服务器获取的字符串 -
JSON 字符串包含许多要添加到 ArrayList 中的项目?
-
我强烈建议您改用 Retrofit 之类的东西。您可以使用转换器自动解析这样的响应。
-
@orbit 我不明白你的意思,你能举个例子吗
-
@ρяσѕρєя K 是的,最后我想展示所有的栏目,以便开始有一个更好的想法,一切是如何运作的,如果它显示 nr 我很高兴 :-)
标签: java android json arraylist