1. 使用对象属性前需要判断对象是否为null
- 反面样例:
name = user.name;
nameLength = user.name.length();
- 正确做法:
if(user != null)
{
name = user.name;
if(user.name != null)
{
nameLength = user.name.length();
}
}
2. 访问数组及列表时,需要判断下标是否超出范围
- 反面样例:
String element = arr[index];
- 正确做法:
int index = 0;
if (arr != null && index >= 0 && index < arr.length) {
String element = arr[index];
}
3. 类型强制转化时,需要对类型进行检查
- 反面样例:
Student stu = (Student) people;
- 正确做法:
if(people instanceof Student)
{
Student stu = (Student) people;
}
4. 异步任务回调更新ui或调用activity方法时需要判断activity状态
- 反面样例:
mActivity.xx();
- 正确做法:
if (!(mActivity.isFinishing() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())) {
mActivity.xx();
}
5. 显示dialog前需要对所属activity状态做判断
- 反面样例:
dialog.show();
- 正确做法:
Dialog dialog = new Dialog(this);
if (!(mActivity.isFinishing() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())
&& dialog != null
&& dialog.isShowing()) {
dialog.show();
}
- 最佳实践:
所有dialog都继承基础dialog类,在基础dialog类中,覆写show方法,对activity状态进行判断.
6. 避免不必要的activity依赖
对于Toast和SharedPreference,都不需要依赖activity.
- 反面样例:
Toast.makeText(getActivity(), "出错啦", Toast.LENGTH_SHORT).show();
- 正确做法:
Toast.makeText(applicationContext, "出错啦", Toast.LENGTH_SHORT).show();
- 最佳实践:
将Toast/SharedPreference封装成工具类,app初始化时,将applicationContext设置进去,后面调用者就都不用管context的问题了.