Android开发常见Exception汇总


在我们进行开发中,难免会碰到各种Exception。再次记录和总结一下,希望对过路的你有所帮助。

Exception子子孙孙无穷尽也,我会不断新增内容补充完整,欢迎收藏,不断回顾

Java异常

1. ConcurrentModificationException异常

List<String> list = new ArrayList<>();
    list.add("di");
    String str = new String("da");
    list.add(str);
    list.add("paint");
    for(String temp : list){
    
    
        if(temp == "di" || temp == "da"){
    
    
            list.remove(temp);
        }
    }
System.out.print(list.toString());

会抛出ConcurrentModificationException异常,List不可在进行遍历时添加或移除其中的元素。

源码解析:ArrayList的父类AbstractList中有一个modCount成员变量来记录对List的修改次数,还有一个expectedModCount记录对ArrayList修改次数的期望值,modCount是它的初始值。

遍历开始时modCount与expectedModCount都为0,而当我们在遍历中对List进行了add或remove操作后modCount会增加1,expectedModCount不变。
而List在通过next()方法取下一次值时会先检查modCount与expectedModCount是否相等,不等则会抛出ConcurrentModificationException异常。

单线程中解决方案:使用Iterator遍历集合,调用Iterator的remove方法移除元素,其内部有expectedModCount = modCount的操作。

多线程中解决方案:多线程中使用上述方法也会抛出此异常,可在使用iterator迭代的时候使用synchronized或者Lock进行同步,或使用CopyOnWriteArrayList替换ArrayList。

总结
在for循环中进行集合元素的增删要特备注意,上面提供了两种不同线程情况的解决方案,我补充的一点是用for-- 的操作方案,也可以正常操作运行。

Android异常

1. SourceSet with name ‘main’ not found

在Android想进行代码运行测试,使用main方法进行一些方法调用测试,发现不能使用,报如下错误。
在这里插入图片描述
解决方案:
在项目.idea文件夹gradle.xml文件中添加一项配置参数。

   <option name="delegatedBuild" value="false" />

在这里插入图片描述

2. IllegalStateException: This Activity already has an action bar supplied by the window decor

Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
在这里插入图片描述
报错异常信息翻译就是Activity的Window 已经为你提供了一个ActionBar,如果你想用toolbar,那么你需要在theme中设置windowActionBar=false。

异常的原因

  1. 这是我的theme配置
    在这里插入图片描述
  2. 这是我的Activity的layout

    Toolbar和actionBar不能在同一Window中出现,只能二者择其一

解决方案
因为我需要使用Toobar,所以只能去掉ActionBar。
使用Theme.AppCompat.Light.NoActionBar
在这里插入图片描述

3. java.io.IOException: unexpected end of stream on Connection 196.*******

在Okhttp+retrofit中碰到此问题,造成该异常是因为client 与 server之间创建连接后未断开,下次请求就会出现这样的情况,要解决这种情况两种方案:

  1. 服务器配置client请求成功后,断开与与其的TCP连接
  2. 在Retroift中配置addHeader(“Connection”, “close”).build();
	OkhttpBuild .addNetworkInterceptor(getCacheIntercepter())
 
    private Interceptor getCacheIntercepter() {
    
    
        return chain -> {
    
    
//            Request request = chain.request();
			//上面的屏蔽化成下面一句
            Request request = chain.request().newBuilder().addHeader("Connection", "close").build();

如上两种方法是我截止发稿时间找到的方法,如有更好方案请联系我。

4.Android Studio debug模式下代码不显示变量值

在app的 build.gradle文件中别忘记了配置 debuggable=ture。不然你会发现打断点时看不到断点的变量值。
在这里插入图片描述

总结

在Android开发中我们总会遇到各种奇奇怪怪的Exception,Android开发经验就是建立在解决Bug,解决Exception之上的,当你能熟练定位各种Bug和Exception,并能知晓造成原因和有效解决之后,恭喜你,你向技术大神的神坛又迈进了一大步。

博客书写不易,如觉得文章还行,请您点个赞 ^ _ ^ !

猜你喜欢

转载自blog.csdn.net/luo_boke/article/details/106349481