【发布时间】:2015-05-02 18:56:23
【问题描述】:
我目前正在开发一个需要 HTTP 连接的 Android 应用程序。我正在使用物理设备来测试我的应用程序。如果我的设备上的无线连接未打开并且我启动了应用程序,它显然会崩溃并告诉我“不幸的是,我的应用程序已停止”。 .然后有这个堆栈跟踪告诉我与我的 URL 的连接被拒绝。到目前为止,一切都很好。现在,我需要的是,当我的设备上没有互联网连接时,我的应用程序不会崩溃,而是希望它显示一个对话框并保持应用程序运行。 我也在使用 Json。
这是我的代码的一部分:
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_restaurants, "GET", params);
System.out.println(json.toString());
if (json==null) {
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_SHORT).show();
}
else {
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
}
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
Jrestaurants = json.getJSONArray(TAG_RESTAURANTS);
// looping through All Products
for (int i = 0; i < Jrestaurants.length(); i++) {
JSONObject c = Jrestaurants.getJSONObject(i);
// Storing each json item in variable
String name = c.getString("name");
String description = c.getString("description");
String address = c.getString("address");
String rating = c.getString("rating");
String open = c.getString("open");
String close = c.getString("close");
double lat = c.getDouble("latitude");
double longit = c.getDouble("longitude");
Restaurant r = new Restaurant(name, description, address, rating, open, close, lat, longit);
// Restaurant r2 = new Restaurant("Nobori Japanese Restaurant","0364 144 626","Plopilor 57-62 Street","4.2","10:00 am","11:30 pm",46.762555,23.556854);
restaurants.add(r.getName());
// restaurants.add(r2.getName());
restaurantsMap.put(r.getName(), r);
//restaurantsMap.put(r2.getName(),r2);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
我尝试检查json 是否为空,但这不起作用。我不确定要检查什么以及在哪里检查。
【问题讨论】: