(转载)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中增加允许使用网络选项(在< ...
随机推荐
- 学习网址Collect
Laravel 学院 https://laravelacademy.org/wx小程序 https://developers.weixin.qq.com/miniprogram/dev/quic ...
- BZOJ 4195: [Noi2015]程序自动分析 并查集 + 离散化 + 水题
TM 读错题了...... 我还以为是要动态询问呢,结果是统一处理完了再询问...... 幼儿园题,不解释. Code: #include<bits/stdc++.h> #define m ...
- Skyline Web 端数据浏览性能优化
三维数据的效率一直是个瓶颈,特别是在Web端浏览一直是个问题,在IE内存限制1G的条件下,对于三维数据动不动几十G的数据量,这1G显得多么微不足道.虽然现在三维平台都是分级加载,或者在程序中采用数据分 ...
- 5、SpringBoot+MyBaits+Maven+Idea+pagehelper分页插件
1.为了我们平时方便开发,我们可以在同一个idea窗口创建多个项目模块,创建方式如下 2.项目中pom.xm文件的内容如下 <?xml version="1.0" encod ...
- 1.3 eclipse中配置Tomcat
下载并成功安装Eclipse和Tomcat(): 打开Eclipse,单击“window”菜单,选择下方的“Preferences”: 步骤阅读 3 找到Server下方的Runtime Envi ...
- 在Win32 Application 环境下实现MFC窗口的创建
// Win32下MFC.cpp : Defines the entry point for the application.// #include "stdafx.h" clas ...
- csu1395模拟
#include<stdio.h> #include<string.h> #define N 10 char s[N][N][N]={{"***",&qu ...
- POJ 1984
我做过的最棘手的一道题了,不是因为难,难就是不懂,而是因为明明思路对了,却调了很久程序没发现自己哪错了.....就连样例都不过 操,别人的代码::::::::::::::::::::::::::::. ...
- REST当道,NO MVC
前世今生 B/S开发经历了几个时代,如今已经是后MVC时期了. MVC体现了分层和解耦合的概念.从功能和理念上都做出过巨大贡献,使Java B/S开发在面对大型项目时从容不迫,说成是上个十年Java ...
- Oracle创建自增字段方法-ORACLE SEQUENCE的简介
曾经最头疼的就是对表插入数据的时候,有主键问题. 由于主键不可以反复,所以得用函数自己定义一个规则生成不反复的值赋值给主键. 如今发现oracle有sequence就不用那么麻烦了. 转自:http: ...
收藏(1)
赞(1)
踩(0)