仅在Android中崩溃,java.lang.NoClassDefFoundError:解析失败:Lcom / squareup / okhttp / MediaType;

时间:2017-06-08 11:22:31

标签: android retrofit2

更新:它仅在Android Lollipop上崩溃。

我收到此错误

06-08 16:30:56.788 29535-29535/com.d.p E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.d.p, PID: 29535
  java.lang.NoClassDefFoundError: Failed resolution of: Lcom/squareup/okhttp/MediaType;
      at com.d.p.ui.base.DWBApplication.<clinit>(DWBApplication.java:164)
      at java.lang.reflect.Constructor.newInstance(Native Method)
      at java.lang.Class.newInstance(Class.java:1606)
      at android.app.Instrumentation.newApplication(Instrumentation.java:1000)
      at android.app.Instrumentation.newApplication(Instrumentation.java:985)
      at android.app.LoadedApk.makeApplication(LoadedApk.java:567)
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4837)
      at android.app.ActivityThread.access$1500(ActivityThread.java:178)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531)
      at android.os.Handler.dispatchMessage(Handler.java:111)
      at android.os.Looper.loop(Looper.java:194)
      at android.app.ActivityThread.main(ActivityThread.java:5643)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
   Caused by: java.lang.ClassNotFoundException: Didn't find class "com.squareup.okhttp.MediaType" on path: DexPathList[[zip file "/data/app/com.d.p-1/base.apk", zip file "/data/app/com.d.p-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.d.p-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
      at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
      at com.d.p.ui.base.DWBApplication.<clinit>(DWBApplication.java:164) 
      at java.lang.reflect.Constructor.newInstance(Native Method) 
      at java.lang.Class.newInstance(Class.java:1606) 
      at android.app.Instrumentation.newApplication(Instrumentation.java:1000) 
      at android.app.Instrumentation.newApplication(Instrumentation.java:985) 
      at android.app.LoadedApk.makeApplication(LoadedApk.java:567) 
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4837) 
      at android.app.ActivityThread.access$1500(ActivityThread.java:178) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531) 
      at android.os.Handler.dispatchMessage(Handler.java:111) 
      at android.os.Looper.loop(Looper.java:194) 
      at android.app.ActivityThread.main(ActivityThread.java:5643) 
      at java.lang.reflect.Method.invoke(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:372) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
    Suppressed: java.lang.ClassNotFoundException: com.squareup.okhttp.MediaType
      at java.lang.Class.classForName(Native Method)
      at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
      at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
            ... 17 more
   Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

我的傻瓜:

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true;
}
//    compile 'com.google.android.gms:play-services-location:8.4.0'
compile('com.github.worker8:tourguide:1.0.17-SNAPSHOT@aar') {
    transitive = true
}
compile 'junit:junit:4.12'
compile 'junit:junit:4.12'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.google.android.gms:play-services-location:9.4.0'
compile 'com.android.support:design:25.3.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'

compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'


compile 'com.wefika:flowlayout:0.4.1'
compile 'com.jeremyfeinstein.slidingmenu:library:1.3@aar'
compile 'com.googlecode.libphonenumber:libphonenumber:7.0.4'
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.commit451:PhotoView:1.2.5'
compile 'com.outlander.showcaseview:showcaseview:1.2.0'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:support-v13:25.3.1'
compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
compile 'com.google.firebase:firebase-crash:9.0.0'
compile 'com.github.PhilJay:MPAndroidChart:v3.0.0-beta1'
compile 'com.google.android.gms:play-services-analytics:9.4.0'
compile 'com.layer.sdk:layer-sdk:0.21.3'
compile 'org.slf4j:slf4j-nop:1.5.8'
compile 'com.google.android.gms:play-services-maps:9.4.0'
compile 'com.layer.atlas:layer-atlas:0.2.10'
compile 'io.jsonwebtoken:jjwt:0.6.0'
compile 'com.google.firebase:firebase-messaging:9.2.0'
compile 'com.google.android.gms:play-services:9.4.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.android.gms:play-services-ads:9.4.0'
compile 'com.google.android.gms:play-services-auth:9.4.0'
compile 'com.google.android.gms:play-services-gcm:9.4.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
}
android {
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
}
}


apply plugin: 'com.google.gms.google-services'

我的申请文件:

public class DWBApplication extends Application {

//Network interface for executing web services over internet
Retrofit networkInterfaceBuilder;
private DawaiBoxService dawaiboxServiceInterface;

//Holds the current application context
private static Context appContext;

private static HomeActivity homeActivity; //Holds the reference to homeActivity as it holds fragments.
// Some time 'onAttach' callback method may call slowly. So then homeActivity reference is used from here

private static DWBApplication mInstance;

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

@Override
public void onCreate() {
    super.onCreate();
    ViewTarget.setTagId(R.id.glide_tag);
    mInstance = this;

//        firebase initialization
    FirebaseAnalytics.getInstance(this).setAnalyticsCollectionEnabled(true);

//        google analytics initialization
    AnalyticsTrackers.initialize(this);
    AnalyticsTrackers.getInstance().get(AnalyticsTrackers.Target.APP);

    if(BuildConfig.FABRIC_ENABLED){
        Fabric.with(this, new Crashlytics());
    }

    appContext = getApplicationContext();

    //Create builder for interacting to server
    networkInterfaceBuilder = new Retrofit.Builder()
            .baseUrl(BuildConfig.SERVER_URL)
            .addConverterFactory(new GsonStringConverterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    //Create service interface to execute dawaibox services
    dawaiboxServiceInterface = networkInterfaceBuilder.create(DawaiBoxService.class);

    try {
        //initialize Typefaces
        TypefaceUtils.initTypefaces(getApplicationContext());
    } catch (Exception ex) {
        DWB_Logs.e("typefaces", ex);
    }
}

public DawaiBoxService getDawaiboxServiceInterface() {
    return dawaiboxServiceInterface;
}

public static Context getAppContext() {
    return appContext;
}

/*------------------------------Current user reference methods ends---------------------*/

/*------------------------------Add prefix +91 to mobile no. Methods starts---------------------*/
/*
* Desc: appends the '+91' prefix to entered text in edit text.
* */
public static MobileNoTextWatcher getAppendPrefixTextWatcher() {
    return new MobileNoTextWatcher();
}

public static String getMobileNoFromEdTxt(EditText mMobileNoEd) {
    if (mMobileNoEd.getText() != null) {
        String mobileNo = mMobileNoEd.getText().toString();
        if (mobileNo.length() > Constants.MOBILE_PREFIX.length()) {
            return mobileNo.substring(Constants.MOBILE_PREFIX.length(), mobileNo.length());
        }
    }
    return "";
}
/*------------------------------Add prefix +91 to mobile no. Methods ends---------------------*/

/*------------------------------Base homeActivity holder methods starts---------------------*/

/*Set the reference to current base homeActivity which displays the fragments*/
public static void setHomeActivity(HomeActivity homeActivity) {
    DWBApplication.homeActivity = homeActivity;
}

/*Returns the reference of current base homeActivity which displays the fragments*/
public static HomeActivity getHomeActivity() {
    return homeActivity;
}

/*------------------------------Base homeActivity holder methods ends---------------------*/

/*
* Methods which will hides the keyboard*/
public static void hideSoftKeyboard(Activity activity) {
    try {
        activity.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
        );
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

/*
* Solves problem: adding extra quotes to multipart string form values
*/
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

public class GsonStringConverterFactory extends Converter.Factory {
    @Override
    public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
        if (String.class.equals(type))// || (type instanceof Class && ((Class<?>) type).isEnum()))
        {
            return new Converter<String, RequestBody>() {
                @Override
                public RequestBody convert(String value) throws IOException {
                    return RequestBody.create(MEDIA_TYPE, value);
                }
            };
        }
        return null;
    }
}

public static synchronized DWBApplication getInstance() {
    return mInstance;
}

public synchronized Tracker getGoogleAnalyticsTracker() {
    AnalyticsTrackers analyticsTrackers = AnalyticsTrackers.getInstance();
    return analyticsTrackers.get(AnalyticsTrackers.Target.APP);
}

/***
 * Tracking screen view
 *
 * @param screenName screen name to be displayed on GA dashboard
 */
public void trackScreenView(String screenName) {
    Tracker t = getGoogleAnalyticsTracker();

    // Set screen name.
    t.setScreenName(screenName);

    // Send a screen view.
    t.send(new HitBuilders.ScreenViewBuilder().build());
    //t.set("&uid", DWB_SharedPreferences.getLayertID(this));
    GoogleAnalytics.getInstance(this).dispatchLocalHits();
}

/***
 * Tracking exception
 *
 * @param e exception to be tracked
 */
public void trackException(Exception e) {
    if (e != null) {
        Tracker t = getGoogleAnalyticsTracker();

        t.send(new HitBuilders.ExceptionBuilder()
                .setDescription(
                        new StandardExceptionParser(this, null)
                                .getDescription(Thread.currentThread().getName(), e))
                .setFatal(false)
                .build()
        );
    }
}

/***
 * Tracking event
 *
 * @param category event category
 * @param action   action of the event
 * @param label    label
 */
public void trackEvent(String category, String action, String label) {
    Tracker t = getGoogleAnalyticsTracker();
    t.set("&uid", Config.USER1);
    // Build and send an Event.
    t.send(new HitBuilders.EventBuilder().setCategory(category).setAction(action).setLabel(label).build());
}
}

我在application.java

中的private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");行崩溃了

1 个答案:

答案 0 :(得分:0)

只是一个猜测,但错误存在于Retrofit的传递依赖中,称为Okhttp。

Retrofit不再处于测试阶段。您可以浏览并升级您的库。

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit:converter-gson:2.3.0'

就个人而言,我会像这样重写,以便始终保持版本一致

ext {
    retrofitVer = '2.3.0'
} 

dependencies {
   ... 
    compile "com.squareup.retrofit2:retrofit:${retrofitVer}"
    compile "com.squareup.retrofit:converter-gson:${retrofitVer}"
} 

同样应该应用于支持库,Google Play和Firebase