(转载)android开发常见编程错误总结
android开发常见编程错误总结
编辑推荐:稀土掘金,这是一个针对技术开发者的一个应用,你可以在掘金上获取最新最优质的技术干货,不仅仅是Android知识、前端、后端以至于产品和设计都有涉猎,想成为全栈工程师的朋友不要错过!
1.设置TextView的文本颜色
- TextView tv;
- ...
- tv.setTextColor(R.color.white);
其实这样设置的颜色是 R.color.white的资源ID值所代表的颜色值,而不是资源color下的white颜色值:正确的做法如下:
- tv.setTextColor(getResources().getColor(R.color.white));
这个出错的概率满高的,就是因为二者都是int类,导致编译器不报错。
2.读取Cursor中的值
- Uri uri;
- Cursor cursor = contentResolver.query(uri, null,null,null,null);
- if(cursor !=null){
- String name = cursor.getString(1);//
- curosr.close();
- cursor =null;
- }
上面语句中的,执行到cursor.getString(1)部分就会报异常,异常是: Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 4
编译没有问题,只有在运行的时候才会发现。
正确的做法是:
- Uri uri;
- Cursor cursor = contentResolver.query(uri, null,null,null,null);
- if(cursor !=null){
- if(cursor.moveToFirst()){
- String name = cursor.getString(1);//
- }
- curosr.close();
- cursor =null;
- }
或者:
- Uri uri;
- Cursor cursor = contentResolver.query(uri, null,null,null,null);
- if(cursor !=null){
- while(cursor.moveToNext()){
- String name = cursor.getString(1);//
- }
- curosr.close();
- cursor =null;
- }
3.不要使用标有Deprecated的函数或者类,比如不要使用android.telephony.gsm.SmsMessage,而应该用android.telephony.SmsMessage,这样避免采用不同的3G协议时不会出现问题。
4.SQLite中的查询条件,比如一个叫name的字段,其字段类型为TEXT,如果我们要判断其name不等某个值(如zhangsan),写出如下的语句
- name <> 'zhangsan'
但是,这样写的语句,如果碰到name值为空的时候,就有问题,即name为空时 以上的布尔值为false,而不是true.
原因很可能,SQLite中的判断函数采用类似写法:
- boolean judge(String self, String conditions){
- if(null == self) return false;
- return self.equalsIgnoreCase(conditions);
- }
其中 self为数据库中name的值,而conditions为上面示例中的 zhangsan。
所以,以上查询条件的正确写法是:
- name <> 'zhangsan' or name is null
除非你也想过滤掉name 为空的记录。
5.如下所示,想要在按钮显示"删 除"(没错删除中间有个空格),以下的字符串资源是错误的:
- <string name="button_delete_text">删 除</string>
这样的出来,最终看不到中间的空格,应该是Android SDK编译的时候,会自动过滤掉String中的空格部分,所以应该采用以下的方式:
- <string name="button_delete_text">删\u0020除</string>
类似地,其他的特殊符号都可以用\u00XX来转义,如 ' ---- \u0027, < ----- \u003C, > ---- \u003E 。
注意这里的数字是16进制哦。
还有一种方法是:这个应该是XML经常使用的方法(new 2013.03.28)
'
<
>
别忘了数字后面的分号哦,而且其中的数字是十进制的
6. context的问题:
如果在一个非Activity的context里面调用startActivity,那么其intent必须设置:
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
否则,会报如下类似的错误:
- Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.
而我们还要提防系统控件中的隐性调用startActivity:
- TextView tv = new TextView(mContext);
- tv.setAutoLinkMask(Linkify.ALL);
- <br>tv.setText(content);
当content内容中有电话号码/邮件/URL时,并且mContext不是非Acitvity的context,而是app的context时(XXXActivity.this.getApplicationContext()),
就会出现如下的错误:
- android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity
- context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
- E/AndroidRuntime(10382): at android.app.ContextImpl.startActivity(ContextImpl.java:622)
- E/AndroidRuntime(10382): at android.content.ContextWrapper.startActivity(ContextWrapper.java:258)
- E/AndroidRuntime(10382): at android.text.style.URLSpan.onClick(URLSpan.java:62)
由于URLSpan.onClick中调用startActivity是由系统控制的,所以我们必须传入activity的contex,才不会出现如上的异常,导致程序退出。
7. 另外一个context的问题:如果你在一个单实例的对象中,有个注册监听器的行为的话,那么传给这个单实例
对象的context,就必须是ApplicationContext了,否则会出现:receiver leak的错误。
8. 控件有时不能充满整个屏幕:
- LinearLayout panel = new LinearLayout(this);
- LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.FILL_PARENT,
- LinearLayout.LayoutParams.FILL_PARENT);
- panel.setLayoutParams(llp);
- root.addView(panel);
而应该是:
- LinearLayout panel = new LinearLayout(this);
- LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.FILL_PARENT,
- LinearLayout.LayoutParams.FILL_PARENT);
- root.addView(panel. llp);
9.按照以下的方式启动service,但是service没有起来
- Intent service = new Intent(this, FuncService.class);
- startService(service);
很有可能是忘了在AndroidManifest.xml中注册FuncService
- <service android:name="com.android.example.FuncService"/>
10.TextView中为什么会在有些行尾出现"..."字符,当然不是所有手机都是有问题,本来笔者刚开始也以为可能是
手机的ROM问题,认真review了代码,发现如下的代码:
- mIntroView = (TextView) findViewById(R.id.description);
- mIntroView.setEllipsize(TruncateAt.END);
问题是上面的第2行,之前是因为要限定文本的行数,后来去掉限制,没有去掉以上的代码。
该行代码会导致很多的ROM上:只要一个文本行的文字在一个手机屏幕行显示不下的话,就自动在
行尾截断并在行尾添加"...",而之前没有问题是因为:全部显示的时候,我调用了如下方法:
- mIntro.setMaxLines(Integer.MAX_VALUE);
11.不要太相信工具,比如Eclipse里面的断点遇到多线程什么,经常不起作用/走不到,还有就是如果语句为空的也不会走,这时候别太早下结论断点地方出错了,
所以每个工程都应该有日志的开关,通过查看日志来确认,某个路径是否走到或者某个变量的值,。。。
12.Java中的月份是从0开始的,所以格式化月份的时候,记得在原有的值上加1处理,如
- Calendar calendar = Calendar.getInstance();
- if(!TextUtils.isEmpty(dateTimes)){
- long milliseconds = WLDateUtils.parseDayTime(dateTimes);
- calendar.setTimeInMillis(milliseconds);
- }
- final int old_year = calendar.get(Calendar.YEAR);
- final int old_month = calendar.get(Calendar.MONTH);
- final int old_day = calendar.get(Calendar.DAY_OF_MONTH);
- mDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener(){
- @Override
- public void onDateSet(DatePicker view, int year,
- int monthOfYear, int dayOfMonth) {
- if(year != old_year || monthOfYear != old_month || dayOfMonth != old_day){
- String dateTimes = String.format("%04d-%02d-%02d", year,
- monthOfYear + 1, dayOfMonth);//月份是从0开始的
- }
- }
- },
- old_year, old_month, old_day);
13.设置ListView的分割线,如果不是图片的话,应注意顺序:
- mListView = new ListView(this);
- mListView.setCacheColorHint(0);
- mListView.setBackgroundDrawable(null);
- mListView.setDivider(getResources().getDrawable(R.drawable.list_divider));
- mListView.setDividerHeight(2);
- 其中:
- <drawable name="list_divider">#00CCCC00</drawable>
即 setDividerHeight 函数应该在setDivider之后,否则这个分割线无效。
- The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged2014-10-23
- 异常:java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams2014-11-16
- RunnableException与CheckedException2016-07-07
- activity外部调用startActivity的new task异常解析2013-09-07
- Unsupported major.minor version 51.02014-10-27
- 嵌套两层滑动view下,IllegalArgumentException: pointerIndex out of range的解决方法2015-05-01
- 关于异常“The specified child already has a parent. You must call removeView"的解决以及产生的原因2014-09-23
- 小心android-support-v4.jar版本混乱造成的NoClassDefFoundError2014-11-03
- Only the original thread that created a view hierarchy can touch its views. 是怎么产生的2016-06-04
- Java 异常处理的最佳实践Best Practices for Exception Handling2013-07-24
(转载)android开发常见编程错误总结的更多相关文章
- android开发常见编程错误总结
1.设置TextView的文本颜色 1 2 3 TextView tv; ... tv.setTextColor(R.color.white); 其实这样设置的颜色是 R.color.white的资源 ...
- Android开发常见错误类型一览表
这是我的第一个博客,我会一直添加我在Android开发中遇到的错误,用来记录我开发中踩过的那些坑 ------------------------分割线------------------------ ...
- Android开发常见错误汇总
[错误信息] [2011-01-19 16:39:10 - ApiDemos] WARNING: Application does not specify an API level requireme ...
- Android开发 |常见的内存泄漏问题及解决办法
在Android开发中,内存泄漏是比较常见的问题,有过一些Android编程经历的童鞋应该都遇到过,但为什么会出现内存泄漏呢?内存泄漏又有什么影响呢? 在Android程序开发中,当一个对象已经不需要 ...
- Android开发——常见的内存泄漏以及解决方案(二)
)Android2.3以后,SoftReference不再可靠.垃圾回收期更容易回收它,不再是内存不足时才回收软引用.那么缓存机制便失去了意义.Google官方建议使用LruCache作为缓存的集合类 ...
- Android开发——常见的内存泄漏以及解决方案(一)
0. 前言 转载请注明出处:http://blog.csdn.net/seu_calvin/article/details/52333954 Android的内存泄漏是Android开发领域永恒的 ...
- Android开发常见的Activity中内存泄漏及解决办法
上一篇文章楼主提到由Context引发的内存泄漏,在这一篇文章里,我们来谈谈Android开发中常见的Activity内存泄漏及解决办法.本文将会以“为什么”“怎么解决”的方式来介绍这几种内存泄漏. ...
- [转载]Android开发必备的21个免费资源和工具
转载自: http://blog.csdn.net/shimiso/article/details/6788375 Android移动开发平台现在不是一个“火”字能形容的,今年Android平台在市场 ...
- Android开发常见错误及技巧
1.无法使用网络:Permission denied(maybe missing internet permission) 在AndroidMainifest.xml中增加允许使用网络选项(在< ...
随机推荐
- Tomcat内存分析相关方法(jmap和mat)
Linux环境命令行 首先,根据进程命令,获取运行的tomcat的进程ID ps aux | grep tomcat | grep java | grep bsc 在第二列可以看到进程ID 然后使用j ...
- Doxyfile中插入图片
下面讲一下如何在doxyfile中插入图片 在查看别人写的文档的过程中,看到可以在doxyfile中插入图片,对此十分的好奇,所以拿出来研究一下 那么这是如何实现的? 根据代码,可以看到如下的注释 @ ...
- pytorch基础(4)-----搭建模型网络的两种方法
方法一:采用torch.nn.Module模块 import torch import torch.nn.functional as F #法1 class Net(torch.nn.Module): ...
- SQL第二节课
SQL练习题 一. 设有一数据库,包括四个表:学生表(Student).课程表(Course).成绩表(Score)以及教师信息表(Teacher).四个表的结构分别如表1-1的 ...
- SpringBoot快速创建HelloWorld项目
废话不多提,拿起键盘,打开 IDEA 就是一通骚操作. 打开 IDEA 后,首页选择 Create New Project,再接着按下图所示,快速搭建SpringBoot项目. 接下来将 Group ...
- greenplum数据迁移
源集群: 登录集群su - gpadminpsql -d postgres查询数据库信息\l查询用户信息\du 备份需要迁移的库到指定目录pg_dump -C testdata > /home/ ...
- 面试官问你如何解决web高并发这样回答就好了
所谓高并发,就是同一时间有很多流量(通常指用户)访问程序的接口.页面及其他资源,解决高并发就是当流量峰值到来时保证程序的稳定性. 我们一般用QPS(每秒查询数,又叫每秒请求数)来衡量程序的综合性能,数 ...
- Shell入门基础
Shell的Helloworld #!/bin/bash echo "helloworld taosir" 执行方式 方式一:用 bash 或 sh 的相对或绝对路径(不用赋予脚本 ...
- 01010_Eclipse中项目的jar包导入与导出
1.jar包 jar包是一个可以包含许多.class文件的压缩文件.我们可以将一个jar包加入到项目的依赖中,从而该项目可以使用该jar下的所有类:也可以把项目中所有的类打包到指定的jar包,提供给其 ...
- hashlib模块 简单了解
import hashlib '''不可逆加密''' password = 'wwwwww7777'.encode('utf8') word = hashlib.md5(password) # md5 ...
收藏(1)
赞(1)
踩(0)