Android-如果在获取JSON数据时没有网络连接,则会发生应用程序强制关闭
我在后台使用asynctask从web获取json数据。这很好,但是当没有网络连接时,应用程序强制关闭 代码如下:Android-如果在获取JSON数据时没有网络连接,则会发生应用程序强制关闭,android,json,Android,Json,我在后台使用asynctask从web获取json数据。这很好,但是当没有网络连接时,应用程序强制关闭 代码如下: public class MainActivity extends Activity { public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0; public static final int DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS = 1; private Pr
public class MainActivity extends Activity {
public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;
public static final int DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS = 1;
private ProgressDialog mProgressDialog;
ArrayList<HashMap<String, Object>> MyArrList;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Download JSON File
new DownloadJSONFileAsync().execute();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_JSON_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading.....");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
case DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading.....");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
// Show All Content
public void ShowAllContent()
{
// listView1
final ListView lstView1 = (ListView)findViewById(R.id.listView1);
lstView1.setAdapter(new ImageAdapter(MainActivity.this,MyArrList));
// OnClick
lstView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
String strImageName = MyArrList.get(position).get("ImageName").toString();
String strImagePathFull = MyArrList.get(position).get("ImagePathFull").toString();
new DownloadFullPhotoFileAsync().execute(strImageName,strImagePathFull); // Download file Full Photo
}
});
}
// Show Dialog Popup
public void showDialogPopup(String strImageName,Bitmap ImageFullPhoto)
{
final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_fullimage_dialog,
(ViewGroup) findViewById(R.id.layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.fullimage);
try
{
image.setImageBitmap(ImageFullPhoto);
} catch (Exception e) {
// When Error
image.setImageResource(android.R.drawable.ic_menu_report_image);
}
imageDialog.setIcon(android.R.drawable.btn_star_big_on);
imageDialog.setTitle("View : " + strImageName);
imageDialog.setView(layout);
imageDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
imageDialog.create();
imageDialog.show();
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
private ArrayList<HashMap<String, Object>> MyArr = new ArrayList<HashMap<String, Object>>();
public ImageAdapter(Context c, ArrayList<HashMap<String, Object>> myArrList)
{
// TODO Auto-generated method stub
context = c;
MyArr = myArrList;
}
public int getCount() {
// TODO Auto-generated method stub
return MyArr.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_column, null);
}
// ColImage
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
imageView.getLayoutParams().height = 80;
imageView.getLayoutParams().width = 80;
imageView.setPadding(5, 5, 5, 5);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
try
{
imageView.setImageBitmap((Bitmap)MyArr.get(position).get("ImageThumBitmap"));
} catch (Exception e) {
// When Error
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
// ColImgID
TextView txtImgID = (TextView) convertView.findViewById(R.id.ColImgID);
txtImgID.setPadding(10, 0, 0, 0);
txtImgID.setText("ID : " + MyArr.get(position).get("ImageID").toString());
// ColImgName
TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgName);
txtPicName.setPadding(50, 0, 0, 0);
txtPicName.setText("Name : " + MyArr.get(position).get("ImageName").toString());
return convertView;
}
}
// Download JSON in Background
public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
}
@Override
protected Void doInBackground(String... params) {
String url = "http://XXX.com.xxp";
JSONArray data;
try {
data = new JSONArray(getJSONUrl(url));
MyArrList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, Object>();
map.put("ImageID", (String)c.getString("ImageID"));
map.put("ImageName", (String)c.getString("ImageName"));
// Thumbnail Get ImageBitmap To Object
map.put("ImagePathThum", (String)c.getString("ImagePath_Thumbnail"));
map.put("ImageThumBitmap", (Bitmap)loadBitmap(c.getString("ImagePath_Thumbnail")));
// Full (for View Popup)
map.put("ImagePathFull", (String)c.getString("ImagePath_FullPhoto"));
MyArrList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
ShowAllContent(); // When Finish Show Content
dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
}
}
// Download Full Photo in Background
public class DownloadFullPhotoFileAsync extends AsyncTask<String, Void, Void> {
String strImageName = "";
String ImageFullPhoto = "";
Bitmap ImageFullBitmap = null;
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS);
}
@Override
protected Void doInBackground(String... params) {
strImageName = params[0];
ImageFullPhoto = params[1];
ImageFullBitmap = (Bitmap)loadBitmap(ImageFullPhoto);
return null;
}
protected void onPostExecute(Void unused) {
showDialogPopup(strImageName,ImageFullBitmap); // When Finish Show Popup
dismissDialog(DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS);
}
}
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = 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) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download file..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
/***** Get Image Resource from URL (Start) *****/
private static final String TAG = "Image";
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
/***** Get Image Resource from URL (End) *****/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
公共类MainActivity扩展活动{
公共静态最终整型对话框\u下载\u JSON\u进度=0;
公共静态最终整型对话框\下载\完整\照片\进度=1;
private ProgressDialog mProgressDialog;
ArrayList MyArrList;
@SuppressLint(“新API”)
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//权限限制模式
如果(android.os.Build.VERSION.SDK_INT>9){
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(策略);
}
//下载JSON文件
新下载的jsonfileasync().execute();
}
@凌驾
受保护的对话框onCreateDialog(int id){
开关(id){
案例对话框\u下载\u JSON\u进度:
mProgressDialog=新建进度对话框(此);
mProgressDialog.setMessage(“下载…”);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE\u微调器);
mProgressDialog.setCancelable(真);
mProgressDialog.show();
返回mProgressDialog;
案例对话框\下载\完整\照片\进度:
mProgressDialog=新建进度对话框(此);
mProgressDialog.setMessage(“下载…”);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE\u微调器);
mProgressDialog.setCancelable(真);
mProgressDialog.show();
返回mProgressDialog;
违约:
返回null;
}
}
//显示所有内容
public void ShowAllContent()
{
//列表视图1
最终ListView lstView1=(ListView)findViewById(R.id.listView1);
lstView1.setAdapter(新的ImageAdapter(MainActivity.this,MyArrList));
//OnClick
lstView1.setOnItemClickListener(新的OnItemClickListener(){
public void onItemClick(AdapterView父视图、视图v、,
内部位置,长id){
String strimagname=MyArrList.get(position.get(“ImageName”).toString();
字符串strImagePathFull=MyArrList.get(position.get(“ImagePathFull”).toString();
新建DownloadFullPhotoFileAsync().execute(strImageName,strImagePathFull);//下载文件完整照片
}
});
}
//显示对话框弹出窗口
public void showDialogPopup(字符串strimagname,位图ImageFullPhoto)
{
final AlertDialog.Builder imageDialog=新建AlertDialog.Builder(此);
最终布局充气机=(布局充气机)this.getSystemService(布局充气机服务);
视图布局=充气机。充气(R.layout.custom\u fullimage\u对话框,
(视图组)findViewById(R.id.layout_root));
ImageView image=(ImageView)layout.findviewbyd(R.id.fullimage);
尝试
{
image.setImageBitmap(ImageFullPhoto);
}捕获(例外e){
//出错时
setImageResource(android.R.drawable.ic\u菜单\u报告\u图像);
}
设置图标(android.R.drawable.btn_star_big_on);
setTitle(“视图:”+strimagname);
imageDialog.setView(布局);
imageDialog.setPositiveButton(android.R.string.ok,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
dialog.dismise();
}
});
imageDialog.create();
imageDialog.show();
}
公共类ImageAdapter扩展了BaseAdapter
{
私人语境;
private ArrayList MyArr=new ArrayList();
公共ImageAdapter(上下文c,ArrayList myArrList)
{
//TODO自动生成的方法存根
上下文=c;
MyArr=myArrList;
}
public int getCount(){
//TODO自动生成的方法存根
返回MyArr.size();
}
公共对象getItem(int位置){
//TODO自动生成的方法存根
返回位置;
}
公共长getItemId(int位置){
//TODO自动生成的方法存根
返回位置;
}
公共视图getView(int位置、视图转换视图、视图组父视图){
//TODO自动生成的方法存根
LayoutFlater充气器=(LayoutFlater)上下文
.getSystemService(上下文布局\充气机\服务);
if(convertView==null){
convertView=充气机。充气(R.layout.activity\u列,空);
}
//ColImage
ImageView ImageView=(ImageView)convertView.findViewById(R.id.ColImgPath);
imageView.getLayoutParams().height=80;
imageView.getLayoutParams().width=80;
设置填充(5,5,5,5);
imageView.setScaleType(imageView.ScaleType.CENTER\U裁剪);
尝试
{
setImageBitmap((位图)MyArr.get(位置).get(“ImageThumBitmap”);
}捕获(例外e){
//出错时
setImageResource(android.R.drawable.ic\u菜单\u报告\u图像);
}
//大肠杆菌
TextView txtImgID=(TextView)convertView.findViewById(R.id.ColImgID);
设置填充(10,0,0,0);
setText(“ID:+MyArr.get(position.get(“ImageID”).toString());
//ColImgName
TextView txtPicName=(TextView)convertView.findViewById(R.id.ColImgName);
private void getDataFromInternet() {
if(InternetConnection.isConnectedToInternet(CurrentActivity.this))
new MyAsyncTask().execute();
}
public static boolean isConnectedToInternet(Context context) {
Log.i(TAG, "Checking Internet Connection...");
boolean found = false;
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
found = true;
internetStatus = 0;
}
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo _3g = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected())
internetType = "WiFi";
if (_3g.isConnected())
internetType = "3G";
} catch (Exception e) {
Log.e("CheckConnectivity Exception", e.getMessage(), e);
}
if(found)
Log.i(TAG, "Internet Connection found.");
else
Log.i(TAG, "Internet Connection not found.");
return found;
}
if (!isOnline())
{
return ctx.getString(R.string.check_wifi);
}
else
{
// your service call goes here
}
public static boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}