【发布时间】:2021-02-13 01:15:51
【问题描述】:
我正在创建一个从外部 url 获取 json 数据的类,如果有连接,它就可以正常工作。如果没有,也会显示错误。 问题是如果在类获取数据时连接丢失,应用程序就会崩溃。
这是我的代码:
//I always check connection before calling the class
class GetPost extends AsyncTask<String, String, String>
{
Context c;
String res;
public GetPost(Context c){
this.c=c;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
Earn.statu.setText("Loading post...");
}
@Override
protected String doInBackground(String[] p1)
{
try{
URL u = new URL(p1[0]);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
res = br.readLine();
}
catch (MalformedURLException e){}
catch (IOException e){}
return res;
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try{
JSONObject jo = new JSONObject(res);
Earn.getVideoData(c,
jo.getString("pid"),
jo.getInt("duration"),
jo.getInt("id")
);
}catch(JSONException a){}
}
那么各位有什么办法可以防止应用崩溃吗?
【问题讨论】: