我只是一个初学者,从网上学习Json解析和流, 好吧,我没有在这个应用程序中得到错误,但它没有显示任何东西。 我不知道问题是什么,并且无法在日志中看到任何问题。 这是代码:
InputStream is;
String line;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
try {
URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&minlatitude=4&maxlatitude=5");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
if(connection.getInputStream()==null)
{
textView.setText("input stream empty");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
while((line=reader.readLine())!=null){
builder.append(line);
}
if(builder.toString().equals(""))
{
textView.setText("no work builder empty");
}
line=builder.toString();
JSONObject object = new JSONObject(line);
JSONArray fea = object.getJSONArray("features");
JSONObject QUAKE = fea.getJSONObject(0);
JSONObject pro = QUAKE.getJSONObject("properties");
int mag = pro.getInt("mag");
textView.setText(mag+"");
} catch (Exception e) {
e.printStackTrace();
}
}
谢谢!
答案 0 :(得分:1)
在主线程上进行任何网络操作都是Android中的犯罪行为。您将受到network_operation_on_main_thread异常的惩罚。您需要从AsyncTask获取帮助。
请尝试以下代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
String data = "input stream empty";
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&minlatitude=4&maxlatitude=5");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
while((line=reader.readLine())!=null){
builder.append(line);
}
if(builder.toString().equals(""))
{
data = "no work builder empty";
}
line=builder.toString();
JSONObject object = new JSONObject(line);
JSONArray fea = object.getJSONArray("features");
JSONObject QUAKE = fea.getJSONObject(0);
JSONObject pro = QUAKE.getJSONObject("properties");
int mag = pro.getInt("mag");
data = mag+"";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
textView.setText(data);
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
答案 1 :(得分:1)
当应用程序尝试在其主线程上执行网络操作时,抛出异常。因此,当您在主线程上进行网络调用时,网络调用将不会发生,并且它将直接抛出 NetworkOnMainThreadException 而不是进行网络调用。在 AsyncTask
中运行您的代码