1
我想從DownloadTask獲取JsonObject。但是我得到的數組值存儲在downloadData中以及存儲在jsonObjectText中的JsonObjects中。在日誌中查看下面。 爲什麼我的代碼返回數組與JsonObject,但我只記錄jsonObject變量的內容。日誌的解析JsonObject時出錯
這裏圖片:
這裏是我的代碼:
package com.example.smarpitsingh.webview;
public class MainActivity extends AppCompatActivity {
String name = "Result";
String result = "",downloadedData,jsonObjectText;
URL url;
HttpURLConnection httpURLConnection;
InputStream inputStream;
InputStreamReader streamReader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask downloadTask = new DownloadTask();
try {
downloadedData = downloadTask.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty").get();
JSONArray jsonArray = new JSONArray(downloadedData);
for (int i=1; i<20; i++){
DownloadTask jasonTask = new DownloadTask();
jsonObjectText = jasonTask.execute("https://hacker-news.firebaseio.com/v0/item/"+jsonArray.getString(i)+".json?print=pretty").get();
Log.i(name,jsonObjectText);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
public class DownloadTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... urls) {
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection)url.openConnection();
inputStream = httpURLConnection.getInputStream();
streamReader = new InputStreamReader(inputStream);
int data = streamReader.read();
while (data != -1){
char count = (char)data;
result += count;
data = streamReader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
`}`