我试图编写一个从网站获取JSON的应用程序,将其转换为数组,然后将该数组的特定元素放入应用程序表的不同位置。我编写了获取JSON数据并将其转换为Eclipse中的ArrayList的代码。那里很棒。我现在尝试在Android Studio中实现代码,但无法正常工作。我有以下代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.table_layout);
TextView textview = (TextView) findViewById(R.id.textView8);
try{
textview.setText(MainActivity.get_data().toString());
}
catch (Exception e){
textview.setText(e.getClass().getCanonicalName());
}
}
public static ArrayList<String> get_data() throws Exception{
String[] ids = new String[] {(here are some ids)};
ArrayList<String> alldata = new ArrayList<>();
for(int r=0;r<ids.length;r++) {
String url = "https://ktrax.kisstech.ch/backend/tracking?db=aviation&sw_lat=40.97765930663377&sw_lon=-26.280096606906117&ne_lat=43.01854550507729&ne_lon=-23.407171802218617&ktrax_id=icao%3a" +ids[r]+"&format=json";
URL ktraxURL = new URL(url);
JSONArray test = Networkaccess.getJSONarr(ktraxURL);
ArrayList<String> listdata = MainActivity.converter(test);
ArrayList<String> elementlist = new ArrayList<>();
(some more code (irrelevant in this matter) which makes the array nice and neat)
//System.out.println(alldata);
return alldata;
}
public static ArrayList<String> converter(JSONArray test){ //creates an array with all the data splited
(Some code that converts JSON to ArrayList (also no problems here))
}
}
class Networkaccess{
public static JSONArray getJSONarr(URL ktraxURL) throws Exception{
HttpURLConnection con = (HttpURLConnection) ktraxURL.openConnection();
//Checking for reponse code of GET Method
con.setRequestMethod("GET");
!!!!!! int responseCode = con.getResponseCode(); //THE DEBUGGER JUMPS FROM HERE TO THE CATCH IN MAIN
System.out.println("Response Code : " +responseCode);
//Reading Data and
BufferedReader readin = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = readin.readLine()) != null) {
response.append(inputLine);
}
readin.close();
//System.out.println(response.toString());
String jsonresp = new String(response.toString());
//System.out.println(jsonresp);
JSONObject myResponse = new JSONObject(jsonresp);
JSONArray test = myResponse.getJSONArray("targets");
//System.out.println(test);
return test;
}
}
我创建了新的网络类作为错误,它在textview字段中显示为:android.os.NetworkOnMainThreadException。但是,这似乎没有完成任务,并且仍然显示相同的错误。我不知道如何从这里继续。调试时,调试器始终运行,直到我标记为!!!的行为止。在代码中。然后,它跳转到主要活动中的catch异常。
期待您的回答!
网络内容趋于积压,因为响应可能需要一段时间才能完成。这就是说,您需要将代码移至另一个线程,以使程序在等待响应时不会冻结。