最近在做一个项目,分享一下遇到的bug吧,算是比较常见:
1、handler——thread
问题:在thread中用handler发送消息,当程序退出时,thread不会立即终止。这时如果在thread中发送message,可能因为handler为null导致程序崩溃。
解决方案:将发送消息的代码放到try——catch当中,或者监察handler是否为空。
2、在thread中更新List的data数据
问题:我在thread中更新data数据,然后在handler中调用adapter.notifyDataSetChanged()方法,大部分时候不会有问题,但是偶尔会崩溃。
解决方案:在thread中更新一个临时的tempData数据,然后在handler中执行data = tempData,adapter.notifyDataSetChanged()。
3、OOM
在处理很多图片时,经常会遇到内存溢出的问题,可以在加载图片时判断一下图片的尺寸,过大的话就缩小后再加载,如下:
try {
URLConnection conn = new URL(url).openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
InputStream is = (InputStream) conn.getContent();
// bitmap = BitmapFactory
// .decodeStream(is);
// 对图像的大小进行处理
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
byte[] buffer = new byte[1024];
int length = -1;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((length = is.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, length);
}
byteArrayOutputStream.close();
byte[] newbuffer = byteArrayOutputStream.toByteArray();
length = newbuffer.length;
BitmapFactory.decodeByteArray(newbuffer, 0, length, options);
int scalew = (int) (options.outWidth / 200.0);
int scaleh = (int) (options.outHeight / 200.0);
options.inSampleSize = Math.max(scalew, scaleh) + 1;
// 获取图像
options.inJustDecodeBounds = false;
options.inInputShareable = true;
options.inPurgeable = true;
bitmap = BitmapFactory.decodeByteArray(newbuffer, 0, length, options);
is.close();
} catch (Exception e) {
Log.e("WebImage", "getBitmapFromUrl");
e.printStackTrace();
}
4、日期转换
这个不会引起崩溃,但却得不到正确结果。看问题吧:
拿到一个时间戳,想对齐进行自定义的格式化。分为——刚刚,X分钟前,X小时X分钟前,X天前,X个月前,然后就是X年X月X日了。。。
看其中一段代码吧:
else if(tempTime < 1000 * 60 * 60 * 24 * 30) {
//小于1个月
strTime = tempTime / (1000 * 60 * 60 * 24) + "天前";
}
这段代码看起来很合理,但却得不到正确结果!!原因就是1000 * 60 * 60 * 24 * 30得到的是个负值!!相信大家已经知道原因了,这个值超过了int所能表示的最大值。
正确代码为:
else if(tempTime < 1000l * 60 * 60 * 24 * 30) {//此处注意要将int转换为long
//小于1个月
strTime = tempTime / (1000l * 60 * 60 * 24) + "天前";
}
这么长时间第一次遇到这种值溢出的错误,当给自己一个提醒吧。5、java.lang.ClassCastException
出现这个错误一般都是我们重新调整了xml文件中控件的位置。
解决方法是清理一下工程。project->clean