0
我在StackOverflow中检查了解答案,但是我没有找到太多内容。所以,我正在做这个练习,就像Hello World与JSON一起工作,我得到了来自openweather API的JSON响应。 我在EditText中输入城市名称,然后按按钮搜索并在日志中显示JSON字符串。跳过了104帧!该应用程序可能在其主线程上做了太多工作
public class MainActivity extends AppCompatActivity {
EditText city;
public void getData(View view){
String result;
String cityName = city.getText().toString();
getWeather weather = new getWeather();
try {
result = weather.execute(cityName).get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public class getWeather extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection connection = null;
String result = "";
try {
String finalString = urls[0];
finalString = finalString.replace(" ", "%20");
String fullString = "http://api.openweathermap.org/data/2.5/forecast?q=" + finalString + "&appid=a18dc34257af3b9ce5b2347bb187f0fd";
url = new URL(fullString);
connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
city = (EditText) findViewById(R.id.editText);
}
}
我该怎么做才能得到这个消息?
添加到此 - 永远不会调用.get()。 AsyncTask的要点是并行运行。如果你觉得需要调用get(),那么首先使用AsyncTask没有意义。在UI线程中这样做绝对不是,你会让整个应用程序无响应,并且可能会被看门狗定时器杀死。 .get合适的次数非常有限。 –
好了,但如果我删除获得()我得到一个错误“Incompatile类型”。所以我应该使用什么获得()而不是,或是否有更好的方式来获得JSON数据? –
我应该使用onPostExecute()吗? –