【发布时间】:2018-07-09 00:50:31
【问题描述】:
我正在尝试从 url 获取 JSON 字符串并将其保存到我的 android 应用程序中的 SQLite 中。
我正在尝试一些教程,然后意识到建议的方法具有 void 返回类型。有没有更简单直接的方法来获取 JSON 字符串并将其放入准备保存到 SQLite 中的数组列表中?
下面是我被困在从 url 获取数据的帮助类 正如他们所说,主线程 OnCreate 不允许这样的后台进程。有没有办法改变 AsyncTask 的返回类型,或者有没有更简单的方法来用 android 获取 JSON 字符串?
public class FetchData extends AsyncTask<Void, Void, Void> {
@Override
protected void doInBackground(ArrayList<String>... voids) {
try {
URL url = new URL("http://192.168.403.211/api/wordsupdate.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader(inputStream));
String line ="";
while (line != null) {
line = bufferedReader.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
【问题讨论】:
-
所以你想在没有任何第三方库的情况下这样做吗?如果是,你的代码是可以的,如果不是,使用retrofit
-
不,代码是不是好的,请看下面我的回答
-
你可以使用Retrofit或者Volley下载JSON文件,然后用Gson就可以轻松解析。我会选择 Retrofit 和 Gson,但这只是我的偏好
-
most simple straight forward完全基于意见。没有人知道你的most simple straight forward是哪条路。