Android Studio retrofit2.Utils中的java.lang.NoClassDefFoundError

我正在使用Retrofit处理来自Mobile的Serverside数据。 实施改造后,我得到下面的例外。

我究竟做错了什么?

com.name.App_idea W / System.err:java.lang.NoClassDefFoundError:retrofit2.Utils at retrofit2.Retrofit $ Builder.baseUrl(Retrofit.java:434)at com.name.App_idea.utils.Idea.onCreate(Idea。在android.app.ActivityThread.access $ 1500(ActivityThread.java:151)android.app.ActivityThread.handleBindApplication(ActivityThread.java:4541)android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1007) android.app.ActivityThread $ android.os.Handler.dispatchMessage(Handler.java:110)android.os.Looper.loop(Looper.java:193)android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1381)在com.android.internal的java.lang.reflect.Method.invoke(Method.java:515)处的java.lang.reflect.Method.invokeNative(Native Method)处使用app.ActivityThread.main(ActivityThread.java:5292)。 os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:824)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)at dalvik.system.NativeStart.main(Native Method)

改造初始

mRetrofit = new Retrofit.Builder() .baseUrl(AppConstance.APP_URL) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .client(getOkHttpClient()) .build(); 

Gradle文件

 apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion '23.0.3' defaultConfig { applicationId "com.name.App_idea" minSdkVersion 14 targetSdkVersion 23 versionCode 1 versionName "9" multiDexEnabled true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.3.0' compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-scalars:2.0.0' compile 'com.google.code.gson:gson:2.2.4' compile 'com.squareup.retrofit2:converter-gson:2.0.0' compile 'com.jakewharton:butterknife:7.0.1' compile 'com.android.support:design:23.3.0' compile 'com.android.support:cardview-v7:23.3.0' compile 'com.google.android.gms:play-services:8.4.0' compile 'com.squareup.okhttp3:okhttp:3.2.0' compile 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0' compile 'com.android.support:support-v4:23.3.0' } 

应用程序类

 import android.app.Application; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Environment; import android.support.multidex.MultiDex; import android.util.Log; import java.io.File; import java.security.cert.CertificateException; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.scalars.ScalarsConverterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class Idea extends Application { public static Retrofit mRetrofit; public static IdeaService Iservice; public static LoginResponceModel loinResponce; public static SettingsModel settingModel; public static LocationModel location = new LocationModel(); private static SQLiteDatabase dbase; private static String FILE_PATH; public static SQLiteDatabase getDataBase() { return dbase; } public static String getFilePath() { return FILE_PATH; } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, "App", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(AppConstance.DbConstans.tblLogin); Log.i("DB", "Created"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { onCreate(db); } } public static void deleteAllTables() { getDataBase().execSQL("DELETE FROM login"); } @Override public void onCreate() { super.onCreate(); try { mRetrofit = new Retrofit.Builder() .baseUrl(AppConstance.APP_URL) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .client(getOkHttpClient()) .build(); Iservice = mRetrofit.create(IdeaService.class); MultiDex.install(this); DatabaseHelper dbHelper = new DatabaseHelper(this); dbase = dbHelper.getWritableDatabase(); AppDataService appDataService = new AppDataService(); loinResponce = appDataService.getLoginDetails(); settingModel = appDataService.getSettings(); FILE_PATH = getAppFilePath(); startService(new Intent(Idea.this, LocationTracker.class)); } catch (Exception e) { e.printStackTrace(); } } public String combineFilePath(String path1, String path2) { File file1 = new File(path1); File file2 = new File(file1, path2); return file2.getPath(); } public String getAppFilePath() { String dsPath; if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) dsPath = combineFilePath(Environment .getExternalStorageDirectory().getAbsolutePath(), "android/data/Idea/"); else dsPath = this.getDir( this.getPackageName(), 0).getAbsolutePath(); new File(dsPath).mkdirs(); return dsPath; } private OkHttpClient getOkHttpClient() { try { // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } }; // Install the all-trusting trust manager final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.sslSocketFactory(sslSocketFactory); builder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); OkHttpClient okHttpClient = builder.build(); return okHttpClient; } catch (Exception e) { throw new RuntimeException(e); } } } 

Solutions Collecting From Web of "Android Studio retrofit2.Utils中的java.lang.NoClassDefFoundError"

这个错误是由于MultiDexApplication引起的 。我遇到过这样的问题,一些其他库不是一样的库,而是一些其他的库。它会改造库的错误,因为它的启动应用程序的启动dex(你的改造库代码是转换为dex)文件是不是设置(安装)。

要解决您需要处理多个Dex文件。 借助应用程序build.gradle &Application类

下面是build.gradle文件中所需的build.gradle

 dexOptions { incremental true // here heap size give 4g i got this thing from https://groups.google.com/forum/#!topic/adt-dev/P_TLBTyFWVY javaMaxHeapSize "4g" } dependencies { compile 'com.android.support:multidex:1.0.1' // your dependencies which you are using. } 

整个build.gradle

 android { signingConfigs { /* releasebuild { keyAlias 'hellotest' keyPassword 'hellotest' storeFile file('path to keystore') storePassword 'hellotest' } */ } compileSdkVersion 'Google Inc.:Google APIs:22' buildToolsVersion '23.0.0' /* if you got error regarding duplicate file of META-INF/LICENSE.txt from jar file packagingOptions { exclude 'META-INF/LICENSE.txt' } */ dexOptions { jumboMode = true incremental true // here heap size give 4g i got this thing from https://groups.google.com/forum/#!topic/adt-dev/P_TLBTyFWVY javaMaxHeapSize "4g" } defaultConfig { multiDexEnabled true applicationId "com.myapp.packagenme" minSdkVersion 17 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.releasebuild } debug { signingConfig signingConfigs.releasebuild } } } dependencies { compile 'com.android.support:multidex:1.0.1' // your dependencies which you are using. } 

如果您的应用程序使用扩展了Applicationclass,则可以覆盖attachBaseContext()方法并调用MultiDex.install(this)以启用multidex。 使用应该扩展的应用程序类来安装Multipledex文件上下文[MultiDexApplication][2]

 public class MyAppClass extends MultiDexApplication{ @Override protected void attachBaseContext(Context newBase) { MultiDex.install(newBase); super.attachBaseContext(newBase); } } 

build议

select性地将API编译到您的可执行文件中

不要使用整个Google Play服务,只使用必需的库。从6.5版本开始,您可以select性地将Google Play服务API编译到您的应用程序中。 例如,要仅包含Google Fit和Android Wear API,请在build.gradle文件中replace以下行:

 compile 'com.google.android.gms:play-services:8.4.0' 

用这些线:

 compile 'com.google.android.gms:play-services-fitness:8.4.0' compile 'com.google.android.gms:play-services-wearable:8.4.0' 

与我的回答https://stackoverflow.com/a/34948154/1140237的参考

我正在面对棒棒糖设备下面的这个错误。

我正在使用multiDexEnabled true。

将此代码添加到扩展Application类的类后,我的问题得到解决。

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

参考: https : //stackoverflow.com/a/39968486/4777524

你添加了以下的proguard规则吗?

 -dontwarn retrofit2.** -keep class retrofit2.** { *; } -keepattributes Signature -keepattributes Exceptions 

文档: http : //square.github.io/retrofit/

这是Gradle的bulidconfiguration问题我也有同样的问题有些时候

在Gradle中使用

 compile 'com.google.android.gms:play-services:8.4.0' 

使用Google Play服务库可以改变你的项目中使用的库

 com.google.android.gms:play-services-gcm:8.4.0 com.google.android.gms:play-services-maps:8.4.0 com.google.android.gms:play-services-auth:8.4.0 

请参阅此URl https://developers.google.com/android/guides/setup#add_google_play_services_to_您的项目

你应该像这样做Utils类:

 public class AppUtil{ public static Retrofit getRetrofitInstance(){ HttpLoggingInterceptor logging=new HttpLoggingInterceptor(); if(isEnableLogging) logging.setLevel(HttpLoggingInterceptor.Level.BODY); else logging.setLevel(HttpLoggingInterceptor.Level.NONE); Gson gson = new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .create(); OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(logging); return new Retrofit.Builder() .baseUrl(Constants.URL_BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .client(httpClient.build()) .build(); } } 

为http方法创build一个这样的接口:

 public interface EndPointInterface{ @FormUrlEncoded @POST(Constants.URL_LOGON) Call<Doctor> login(@Field(Constants.EMAIL) String email, @Field(Constants.PASSWORD) String password); } 

在您打电话给web服务的活动中,请按照以下步骤操作:

  @OnClick(R.id.btn_login) public void onLoginButtonClick() { String emailString = edtEmail.getText().toString().trim(); String passwordString = edtPassword.getText().toString().trim(); if (emailString.length() == 0) { emailWrapper.setError("Please enter E-Mail ID"); } else if (!AppUtil.isEmailValid(emailString)) { emailWrapper.setError("Please enter valid E-Mail ID"); } else if (passwordString.length() == 0) { passwordWrapper.setError("Please enter password"); } else if (AppUtil.isNetworkConnectionAvailable(this, true)) { login(emailString,passwordString); } } private void login(String email, String pwd) { final MaterialDialog dialog = AppUtil.showIndeterminateProgressDialog(this,getString(R.string.please_wait)); EndPointInterface apiService = AppUtil.getRetrofitInstance().create(EndPointInterface.class); Call<Doctor> call = apiService.login(email, pwd); call.enqueue(new Callback<Doctor>() { @Override public void onResponse(Call<Doctor> call, Response<Doctor> response) { dialog.dismiss(); if (response.code() == 200) { Doctor doctor = response.body(); if (doctor == null) { AppUtil.showSimpleDialog(LoginActivity.this, getString(R.string.userid_pwd_mismatched), getString(R.string.login_credential_mismatch)); } else { SharedPreferences.Editor editor = mAppPreferences.edit(); editor.putString(Constants.SETTINGS_OBJ_DOCTOR, new Gson().toJson(doctor)); editor.putBoolean(Constants.SETTINGS_IS_LOGGED_IN, true); editor.commit(); startActivity(new Intent(LoginActivity.this, PatientSummaryInfoActivity.class)); finish(); } } else { dialog.dismiss(); AppUtil.showSimpleDialog(LoginActivity.this, getString(R.string.server_error), getString(R.string.could_not_connect_to_server)); } } @Override public void onFailure(Call<Doctor> call, Throwable t) { dialog.dismiss(); AppUtil.showSimpleDialog(LoginActivity.this,getString(R.string.server_error), t.getMessage()); } }); } 
 mRetrofit = new Retrofit.Builder() .baseUrl(AppConstance.APP_URL) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .client(getOkHttpClient()) .build(); 

重新打包

 OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); mRetrofit = new Retrofit.Builder() .baseUrl(AppConstance.APP_URL) .addConverterFactory(GsonConverterFactory.create()) .client(httpClient) .build(); 

随着这些许多图书馆的马鞍,它一定已经超过臭名昭着的64K方法的限制,你需要启用您的应用程序multidex。 这是你如何做到的。 https://developer.android.com/tools/building/multidex.html

尝试使用相同的lib版本的基础改造库和转换器。

 compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-scalars:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2' 

我碰到类似的问题,这可能是一个依赖性问题

 compile 'com.squareup.retrofit2:retrofit:2.0.2' 

已经包括okhttp在这里看到https://github.com/square/retrofit/blob/d04f3a50e41ca01d22f370ac4f332f6ddf4ba9fe/pom.xml ,因此从依赖列表中删除okhttp,然后同步并再试一次。

我遇到了这个错误。 经过多次search,发现我忘了添加Internet Permission来显示。

添加这个权限后,我的错误,解决了。