Android 帮助在没有互联网连接时停止活动崩溃 (FC)

发布于 2024-12-01 09:07:42 字数 7436 浏览 0 评论 0原文

我已经按照教程远程下载图像,当存在互联网连接时它工作正常,但是当您在没有互联网连接的情况下启动活动时,活动崩溃“强制关闭”,

不幸的是,我是一个 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;


    }


}

}

I have followed a tutorial to download images remotely, it works fine when an internet connection is present, but when you launch the activity with no internet connection present the activity crashes "force Closes"

I'am unfortunately an android novice so i'm not sure what to do to stop it crashing. Is their a way to just toast a message stating "Sorry Internet is required" with a blank screen, nothing fancy, just to stop it crashing.

Hope someone can show me how to do this,
Thankyou
Lucy

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;


    }


}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倾其所爱 2024-12-08 09:07:42

您可以检查连接可用性:

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();
    }

注意:向清单文件添加权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

you can check connection availability:

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();
    }

Note: Add permission to your manifest file:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
给我一枪 2024-12-08 09:07:42

我可以确认 Vineet 的回答很好,因为我也遇到了同样的问题。

我的代码不起作用如下:

public boolean isOnline() {

final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);        
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();      
boolean connected = networkInfo.isConnected();

    if (connected)
        return true;
    else
        return false;

}

我上面的示例的问题是 networkInfo.isConnected() 似乎没有值。我将一个布尔值设置为 null,我认为这是不允许的(是的,我的 Java 很粗略,因为我是新手),因此应用程序会抛出异常并崩溃。

现在我使用 Vineet 的解决方案解决了这个问题。

public boolean isOnline() {

final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);        
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();      

if(networkInfo == null)
    return false;
else
    return networkInfo.isConnected();

现在

,它可以正常工作并且应用程序不再崩溃。希望这个解决方案可以帮助某人。我怀疑 JAVA 大师将能够更好地解释不允许将 boolean 设置为 Null 的问题。

I can confirm Vineet's answer is good as I had the same issue.

My code that was not working is as follows:

public boolean isOnline() {

final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);        
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();      
boolean connected = networkInfo.isConnected();

    if (connected)
        return true;
    else
        return false;

}

And the issue with my above example is that networkInfo.isConnected() does not appear to have a value. I was setting a boolean value to null, which (and yes my Java is sketchy since I am a newbie) I believe is not allowed, hence the app would throw up an exception and crash.

Here is now I solved it using Vineet’s solution.

public boolean isOnline() {

final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);        
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();      

if(networkInfo == null)
    return false;
else
    return networkInfo.isConnected();

}

Now, it works correctly and the app no longer crashes. Hope this solution helps someone. And I suspect a JAVA guru will be able to better explain the issue with setting boolean to Null not being allowed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文