Я следовал руководству по удаленной загрузке изображений, оно отлично работает при наличии подключения к Интернету, но когда вы запускаете действие без подключения к Интернету, происходит сбой действия «принудительное закрытие»
I'mamК сожалению, новичок Android, так что я не уверен, что делать, чтобы остановить его сбой.Это способ просто выпустить сообщение с надписью «Извините, что требуется Интернет» с пустым экраном, ничего особенного, просто чтобы остановить его падение.
Надеюсь, кто-то может показать мне, как это сделать, спасибо, Люси
private ImageAdapter imageAdapter;
private ArrayList<String> PhotoURLS = new ArrayList<String>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN ,
WindowManager.LayoutParams.FLAG_FULLSCREEN );
setContentView(R.layout.galleryview);
public static boolean isDataConnectionAvailable(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if(info == null)
return false;
return connectivityManager.getActiveNetworkInfo().isConnected();
}
imageAdapter = new ImageAdapter(this);
final ImageView imgView = (ImageView) findViewById(R.id.GalleryView);
Gallery g = (Gallery) findViewById(R.id.Gallery);
g.setAdapter(imageAdapter);
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
imgView.setImageDrawable(LoadImageFromURL(PhotoURLS
.get(position)));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
}
});
// replace this code to set your image urls in list
PhotoURLS.add("http://domain.com/image-286.jpg");
PhotoURLS.add("http://domain.com/image-285.jpg");
PhotoURLS.add("http://domain.com/image-284.jpg");
PhotoURLS.add("http://domain.com/image-283.jpg");
PhotoURLS.add("http://domain.com/image-282.jpg");
PhotoURLS.add("http://domain.com/image-281.jpg");
new AddImageTask().execute();
}
class AddImageTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... unused) {
for (String url : PhotoURLS) {
String filename = url.substring(url.lastIndexOf("/") + 1,
url.length());
filename = "th_" + filename;
String thumburl = url.substring(0, url.lastIndexOf("/") + 1);
imageAdapter.addItem(LoadThumbnailFromURL(thumburl + filename));
publishProgress();
//SystemClock.sleep(200);
}
return (null);
}
@Override
protected void onProgressUpdate(Void... unused) {
imageAdapter.notifyDataSetChanged();
}
@Override
protected void onPostExecute(Void unused) {
}
}
private Drawable LoadThumbnailFromURL(String url) {
try {
URLConnection connection = new URL(url).openConnection();
String contentType = connection.getHeaderField("Content-Type");
boolean isImage = contentType.startsWith("image/");
if(isImage){
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity);
InputStream is = bufferedHttpEntity.getContent();
Drawable d = Drawable.createFromStream(is, "src Name");
return d;
} else {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.no_image);
Drawable d = new BitmapDrawable(b);
return d;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG)
.show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
private Drawable LoadImageFromURL(String url) {
try {
URLConnection connection = new URL(url).openConnection();
String contentType = connection.getHeaderField("Content-Type");
boolean isImage = contentType.startsWith("image/");
if(isImage){
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
entity);
InputStream is = bufferedHttpEntity.getContent();
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 320;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
is = bufferedHttpEntity.getContent();
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap b = BitmapFactory.decodeStream(is, null, o2);
Drawable d = new BitmapDrawable(b);
return d;
} else {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.no_image);
Drawable d = new BitmapDrawable(b);
return d;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG)
.show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
ArrayList<Drawable> drawablesFromUrl = new ArrayList<Drawable>();
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.GalleryTheme);
mGalleryItemBackground = a.getResourceId(
R.styleable.GalleryTheme_android_galleryItemBackground, 0);
a.recycle();
}
public void addItem(Drawable item) {
drawablesFromUrl.add(item);
}
public int getCount() {
return drawablesFromUrl.size();
}
public Drawable getItem(int position) {
return drawablesFromUrl.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageDrawable(drawablesFromUrl.get(position));
i.setLayoutParams(new Gallery.LayoutParams(70, 110));
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
//i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
}