我正在处理JSON数据获取和显示,但在此之前我将它存储在Sqlite中。
从该Sqlite表中获取后,当互联网可用时它可以正常工作但是当互联网连接不可用时应用程序会自动关闭。我使用哈希映射自定义适配器来显示listview中的数据。我已经从SqlHelper类
创建了一个fetchdata方法 protected Void doInBackground(Void... params)
{
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
int state = NetworkUtilClass.checkInternetConenction(getActivity());
if (state == 1) {
// jsonobject = new JSONObject(str1);
jsonobject = JSONFunction.getJSONfromURL("url");
JSONObject collection = null;
try {
collection = jsonobject.getJSONObject("collection");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray response = null;
try {
response = collection.getJSONArray("response");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < response.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonobject1 = null;
try {
jsonobject1 = (JSONObject) response.get(i);
noticeId = jsonobject1.getString("id").toString();
noticeTitle = jsonobject1.getString("title").toString();
noticeDescription = jsonobject1.getString("description").toString();
noticePublishedBy = jsonobject1.getString("publishedBy").toString();
noticeValidFrom = jsonobject1.getString("validFrom").toString();
noticeValidTo = jsonobject1.getString("validTo").toString();
Log.e(noticeId, "show");
Log.e(noticeTitle, "show");
Log.e(noticeDescription, "show");
//demo_database.insertData(noticeTitle,noticeDescription,noticePublishedBy,noticeValidFrom,noticeValidTo);
demo_database.insertNoticeData(noticeId,noticeTitle,noticeDescription, noticePublishedBy,
noticeValidFrom, noticeValidTo);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else{
onPostExecute(null);
}
return null;
}
@Override
protected void onPostExecute(Void args)
{
// Locate the listview in listview_main.xml
getData();
demo_database.close();
// Close the progressdialog
mProgressDialog.dismiss();
}
}
private void getData() {
// TODO Auto-generated method stub
try {
arraylist = demo_database.fetchNoticeData();
} catch (Exception e) {
e.printStackTrace();
}
listview = (ListView) getActivity().findViewById(R.id.listview);
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
Toast.makeText(getActivity(), "ListView clicked", Toast.LENGTH_SHORT).show();
}
});
// Pass the results into ListViewAdapter.java
adapter = new NoticeListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
答案 0 :(得分:0)
实际上,当你试图通过url访问json时,当互联网不可用时,所以带有名称响应的json数组没有得到任何项目因此它得到Null并且当你尝试执行For循环时你给出json数组的长度,由于空指针异常,它会崩溃。
你的应用程序正在崩溃for for Loop吗?