Android开发错误集锦

5,457 阅读7分钟

2019年12月23日15:57:41

简书转掘金了,简书广告太多,受不了了 原链

2017年5月5日19:27:55

ButterKnife8.0之后依赖注入之后报空指针错误

解决方式:因为8.0之后运行时代码插件更新,所以需要配置

classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

不过最简单的办法是除了依赖Butterknife之外,依赖

annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

2017年5月5日20:00:11

Glide加载图片报错You must not call setTag() on a view Glide is targeting

解决方式:出现这种错误往往是因为使用了ListView或者RecyclerView,其Item的布局进行了简写,解决方法只需要将Item增加父布局即可

2017年11月10日10:08:18

Glide加载大图出现拉伸问题. 首先将自己的imageview的scaleType属性设置为centerCrop,然后使用glide的时候如下设置

Glide.with(context).load(url).asBitmap().centerCrop().placeholder(R.drawable.defaultpic).into(imageview);

2018年1月9日16:06:56

Glide V4依赖出错

提示Support资源找不到,只需要升级一下Support版本就可以,最好为26以上

implementation 'com.android.support:appcompat-v7:27+'
implementation 'com.android.support:design:27.+'

2018年7月19日14:32:37

Configuration 'compile' is obsolete and has been replaced with 'implementation'. It will be removed at the end of 2018

提示将compile替换为implementation,并且compile将于2018年底进行删除

2018年7月19日14:38:08

The SourceSet 'instrumentTest' is not recognized by the Android Gradle Plugin.

instrumentTest在更新之后已经过时,用androidTest替换即可

2018年7月19日14:48:39

DSL element 'DexOptions.incremental' is obsolete and will be removed at the end of 2018

将incremental = true删除即可.

2018年8月9日13:52:22

Toolbar内部左侧始终有一段空白,无法填充

在toolbar布局中加入如下代码即可解决

app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"

2018年8月18日10:34:24

自定义对话框顶部始终有一个白边,底部线性布局嵌套TextView始终无圆角

白边问题ImageView添加属性
android:adjustViewBounds="true"

无圆角问题原因:把圆角shape文件设置给了线性布局,修改设置给textview后正常

2018年8月18日11:20:27

OPPO手机拍照成功之后点击确定没反应,经过核查发现是保存图片的路径问题导致的,将路径改为如下后正常

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()

2018年8月23日11:53:43

Android嵌套H5,通过javascript调用H5无法显示内容,将H5的UL改为div包裹UL恢复正常

2018年10月11日16:20:29

打包混淆之后EventBus报错,在混淆文件中加入如下代码正常

-keepattributes *Annotation*
-keepclassmembers class ** {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }

# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);
}

2018年10月19日09:14:51

尝试使用Dagger2时报错

Could not find method apt() for arguments [com.google.dagger:dagger-compiler:2.6] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

将依赖中的apt...改为annotationProcessor...

参考资料 : With android gradle plugin 2.2.0 release, the android-apt plugin is no longer needed for annotation processing. The apt function was included in the latest android gradle plugin which called annotationProcessor.

compile 'com.google.dagger:dagger:2.6'
annotationProcessor "com.google.dagger:dagger-compiler:2.6"

2018年10月31日11:15:38

Android ContextThemeWrapper cannot be cast to android.app.Activity

加入以下代码:

private static Activity checkActivity(Context context) {
    if (context == null){
       return null;
    } else if (context instanceof Activity){
        return (Activity)context ;
    } else if (context instanceof ContextWrapper){
        return checkActivity(((ContextWrapper)context).getBaseContext());
    }
    return null;
}

调用时:

TextView tvView = new TextView(checkActivity(getContext()));

2018年11月6日09:14:13

去除腾讯X5浏览器的滑动块(原生去除滑动块方法对X5无效)

if (infoWebView.getX5WebViewExtension() != null) {
            infoWebView.getX5WebViewExtension().setHorizontalScrollBarEnabled(false);//水平不显示滚动按钮
            infoWebView.getX5WebViewExtension().setVerticalScrollBarEnabled(false); //垂直不显示滚动按钮
        }

2018年11月17日14:04:17

判断当前处于活动的Activity是否包含指定Activity

/**
     * 判断MainActivity是否活动
     *
     * @param activityName 要判断Activity,最好传全包名
     * @return boolean
     */
    private boolean isMainActivityAlive(Context context, String activityName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            // 注意这里的 topActivity 包含 packageName和className,可以打印出来看看
            if (info.topActivity.toString().contains(activityName) || info.baseActivity.toString().contains(activityName)) {
                LogUtils.e(TAG, info.topActivity.getPackageName() + " info.baseActivity.getPackageName()=" + info.baseActivity.getPackageName());
                return true;
            }
        }
        return false;
    }

2018年11月23日14:30:35

AS项目编译报错

Configuration on demand is not supported by the current version of the Android Gradle plugin since you are using Gradle version 4.6 or above. Suggestion: disable configuration on demand by setting org.gradle.configureondemand=false in your gradle.properties file or use a Gradle version less than 4.6.

在gradle-wrapper.properties 文件,修改distributionUrl 参数,低于4.6即可

2018年12月18日11:31:06 Android P强制接受HTTP: 新建文件 res -> xml ->network_security_config.xml,并填写如下内容:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

在AndroidManifest ->application节点加入:

android:networkSecurityConfig="@xml/network_security_config"

2018年12月18日11:33:57

Android P继续使用HTTPClient 给老项目升级到P,项目报错:

java.lang.RuntimeException: Stub!
&emsp;&emsp;at org.apache.http.message.BasicNameValuePair.<init>(BasicNameValuePair.java:6)

在Android P之后,org.apache.http.legacy 库将从 bootclasspath 中删除,所以无法继续使用.官方文档:

Apache HTTP 客户端弃用影响采用非标准 ClassLoader 的应用

小声BB(还能怎么办,强制接受吧......) 继续使用方法:在AndroidManifest ->application节点内加入:

<uses-library
            android:name="org.apache.http.legacy"
            android:required="false"/>

2019年1月10日11:11:58

报错 : Manifest merger failed with multiple errors, see logs

解决方法:切换到Terminal,运行如下命令后即可看到详细错误

gradlew processDebugManifest --stacktrace

2019年2月25日09:13:49

ERROR: Failed to resolve: support-media-compat

原因:莫名其妙的报错,莫名其妙的被墙,莫名其妙的糟心 解决方法: 项目build文件中注释:

 mavenCentral()
 google()
 jcenter()

换为

 maven { url 'https://maven.aliyun.com/repository/google' }
 maven { url 'https://maven.aliyun.com/repository/jcenter' }
 maven { url 'http://maven.aliyun.com/nexus/content/groups/public' } 

最后应为如下:

buildscript {
    repositories {
//        jcenter()
//        mavenCentral()
//        google()
        maven { url 'https://maven.aliyun.com/repository/google' }
        maven { url 'https://maven.aliyun.com/repository/jcenter' }
        maven { url 'http://maven.aliyun.com/nexus/content/groups/public' }
    }
    dependencies {
      ...
    }
}

allprojects {
    repositories {
//        mavenCentral()
//        jcenter()
//        google()
        maven { url 'https://maven.aliyun.com/repository/google' }
        maven { url 'https://maven.aliyun.com/repository/jcenter' }
        maven { url 'http://maven.aliyun.com/nexus/content/groups/public' }
        ...
    }
}

2019年4月15日15:26:46

EditText的clearFocus()方法无效 通过查看源码发现,clearFocus并不是真的清除焦点,而是在整个布局中遍历获取focusInTouchMode为true的View,如果EditText为第一个,就又重新设置了焦点,陷入了死循环,所以才会看上去无效,解决方法只需要将EditText之前的view设置如下属性

android:focusableInTouchMode="true"

2019年7月26日15:26:45

AndroidManifast警告GoogleAppIndexingWarning App is not indexable by Google Search

解决方法: 按照提示在AndroidManifest.xml文件中的至少一个页面中增加如下intent-filter:

<action android:name="android.intent.action.VIEW" />

或直接进行Alt+Enter忽略

2019年10月22日14:55:29

从后台切换程序后,页面重新加载报错

java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.support.v7.widget.Toolbar$SavedState instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/toolbar. Make sure other views do not use the same id

报错是说页面重新加载时,toolbar的id是重复的,百思不得其解,百度发现一些相同的问题,无解,后偶然间发现,布局中include的toolbar的id和toolbar.xml中的toolbar的id都是toolbar,将内部的toolbar的id进行修改后,解决问题.

 <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            binding:toolbarViewModel="@{mainViewModel.toolbarViewModel}" />
  <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="0dp"
            android:layout_height="49dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="?attr/actionBarTheme"
            app:contentInsetLeft="0dp"
            app:contentInsetStart="0dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

上边的id重复了,导致的问题

2019年12月31日09:52:51

老项目升级报错

NoClassDefFoundError: Failed resolution of: Lorg/apache/http/params/BasicHttpParams

清单文件application标签中加入

 <application
       ...>

        <uses-library android:name="org.apache.http.legacy" android:required="false" />
</application>

build文件android下加入

android {
   ...
        useLibrary 'org.apache.http.legacy'
    }