我正在尝试从服务器获取数据,当我禁用互联网时,它会出错。我的活动代码是
的活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hos);
new ProgressTask(Hospital.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getApplicationContext(),
"INTERNET CONNECTION NOT PRESENT", 5).show();
startActivity(new Intent(Hospital.this, MainActivity.class));
}
}
// private List<Message> messages;
public ProgressTask(ListActivity activity) {
context = activity;
}
private Context context;
protected void onPreExecute() {
}
@Override
protected void onPostExecute(final Boolean success) {
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.row_listitem, new String[] { name, contact },
new int[] { R.id.vehicleType, R.id.vehicleColor });
setListAdapter(adapter);
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> map = (HashMap<String, String>) lv
.getItemAtPosition(position);
String name = map.get("name");
Intent intent = new Intent(Hospital.this,
DataViewActivity.class);
intent.putExtra("itemName", name);
startActivity(intent);
}
});
}
protected Boolean doInBackground(final String... args) {
baseAdapter jParser = new baseAdapter();
// get JSON data from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vtype = c.getString(name);
String vcolor = c.getString(contact);
String vfuel = c.getString(Category);
// String vtread = c.getString(TREAD);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(name, vtype);
map.put(contact, vcolor);
map.put(Category, vfuel);
// map.put(TREAD, vtread);
jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
baseAdapter:
public class baseAdapter {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";
public baseAdapter() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
jarray = new JSONArray(builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
logcat的:
08-16 12:36:00.271: E/JSON Parser(17005): Error parsing data org.json.JSONException: End of input at character 0 of
08-16 12:36:00.271: W/dalvikvm(17005): threadid=11: thread exiting with uncaught exception (group=0x40a7f228)
08-16 12:36:00.281: E/AndroidRuntime(17005): FATAL EXCEPTION: AsyncTask #1
08-16 12:36:00.281: E/AndroidRuntime(17005): java.lang.RuntimeException: An error occured while executing doInBackground()
08-16 12:36:00.281: E/AndroidRuntime(17005): at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-16 12:36:00.281: E/AndroidRuntime(17005): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.lang.Thread.run(Thread.java:864)
08-16 12:36:00.281: E/AndroidRuntime(17005): Caused by: java.lang.NullPointerException
08-16 12:36:00.281: E/AndroidRuntime(17005): at com.example.careandcure.Hospital$ProgressTask.doInBackground(Hospital.java:124)
08-16 12:36:00.281: E/AndroidRuntime(17005): at com.example.careandcure.Hospital$ProgressTask.doInBackground(Hospital.java:1)
08-16 12:36:00.281: E/AndroidRuntime(17005): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-16 12:36:00.281: E/AndroidRuntime(17005):
我的问题是,当我连接互联网时它工作正常,但当我断开它崩溃的应用程序,并显示吐司而不是互联网连接
答案 0 :(得分:1)
您的代码是在假设尝试获取json工作且有效的情况下编写的。如果您没有互联网连接,它将超时。在那种情况下,json将为null。您需要检查该案例并进行处理。
答案 1 :(得分:1)
如果您在行返回null之后没有互联网连接:
jParser.getJSONFromUrl(url);
所以json
在您的代码中为空,您无法运行以下代码:
for (int i = 0; i < json.length(); i++)
要解决此问题,您可以检查非空的json
if (json != null)
{
// your code
}