No se pudo encontrar la clase referenciada desde el método android java.lang.NoClassDefFoundError

Estoy llamando para una clase separada que he escrito en el mismo paquete que mi clase MainActivity se guarda. Pero cuando ejecuto la aplicación me da java.lang.NoClassDefFoundError . No puedo entender por qué otra clase definida en el mismo paquete no puede ser identificada. He intentado muchos métodos sugieren para java.lang.NoClassDefFoundError pero ninguno de ellos resolvió el error.

 08-26 10:43:27.776: E/dalvikvm(1311): Could not find class 'com.example.hcpandroid.SSLAuthenticate$1', referenced from method com.example.hcpandroid SSLAuthenticate.authenticate 08-26 10:43:27.786: E/AndroidRuntime(1311): FATAL EXCEPTION: main 08-26 10:43:27.786: E/AndroidRuntime(1311): java.lang.NoClassDefFoundError: com.example.hcpandroid.SSLAuthenticate$1 08-26 10:43:27.786: E/AndroidRuntime(1311): at com.example.hcpandroid.SSLAuthenticate.authenticate(SSLAuthenticate.java:86) 08-26 10:43:27.786: E/AndroidRuntime(1311): at com.example.hcpandroid.LogIn.LogIn(LogIn.java:48) 08-26 10:43:27.786: E/AndroidRuntime(1311): at com.example.hcpandroid.LogIn$1.onClick(LogIn.java:29) 08-26 10:43:27.786: E/AndroidRuntime(1311): at android.view.View.performClick(View.java:4128) 08-26 10:43:27.786: E/AndroidRuntime(1311): at android.view.View$PerformClick.run(View.java:17142) 08-26 10:43:27.786: E/AndroidRuntime(1311): at android.os.Handler.handleCallback(Handler.java:615) 08-26 10:43:27.786: E/AndroidRuntime(1311): at android.os.Handler.dispatchMessage(Handler.java:92) 08-26 10:43:27.786: E/AndroidRuntime(1311): at android.os.Looper.loop(Looper.java:213) 08-26 10:43:27.786: E/AndroidRuntime(1311): at android.app.ActivityThread.main(ActivityThread.java:4787) 08-26 10:43:27.786: E/AndroidRuntime(1311): at java.lang.reflect.Method.invokeNative(Native Method) 08-26 10:43:27.786: E/AndroidRuntime(1311): at java.lang.reflect.Method.invoke(Method.java:511) 08-26 10:43:27.786: E/AndroidRuntime(1311): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809) 08-26 10:43:27.786: E/AndroidRuntime(1311): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576) 08-26 10:43:27.786: E/AndroidRuntime(1311): at dalvik.system.NativeStart.main(Native Method) 

Clase de actividad principal:

 package com.example.hcpandroid; import com.example.hcpandroid.R.id; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.hcpandroid.SSLAuthenticate; public class LogIn extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_in); Button btnLogIn = (Button) findViewById(id.btnLogIn); btnLogIn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LogIn(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.log_in, menu); return true; } public void LogIn(){ EditText txtUname = (EditText) findViewById(id.txtUsername); EditText txtPword = (EditText) findViewById(id.txtPassword); SSLAuthenticate ssl = new SSLAuthenticate(txtUname.getText().toString(), txtPword.getText().toString()); int authCode = ssl.authenticate(); Toast toast= Toast.makeText(getApplicationContext(), authCode, Toast.LENGTH_LONG); toast.show(); } } 

Clase SSLAuthentication:

 package com.example.hcpandroid; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.IOException; import java.math.BigInteger; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import net.sf.json.JSON; import net.sf.json.JSONSerializer; import net.sf.json.xml.XMLSerializer; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.simple.JSONValue; import sun.misc.BASE64Encoder; /** * @author sajithru */ public class SSLAuthenticate { private String username; private String password; private DefaultHttpClient httpClient; private String cookie; public SSLAuthenticate(String username, String password) { this.username = username; this.password = password; } public SSLAuthenticate() { } public DefaultHttpClient getHttpClient() { return httpClient; } public String getCookie() { return cookie; } public String getUsername() { return username; } public int authenticate() { HttpResponse responce = null; try { //Authenticate SSL Certification TrustStrategy easyStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { // eh, why not? return true; } }; SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = new SSLSocketFactory((KeyStore) easyStrategy); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", ssf, 443); schemeRegistry.register(httpsScheme); TrustManager trustMgr = new TrustManager() { }; sslcontext.init(null, new TrustManager[]{trustMgr}, null); HttpParams params = new BasicHttpParams(); ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, schemeRegistry); httpClient = new DefaultHttpClient(connMgr, params); //Encode username into BASE64 encode format BASE64Encoder base64Encoder = new BASE64Encoder(); String uname64 = base64Encoder.encode(username.getBytes()); //Encode password into MD5 Hash encode format MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes(), 0, password.length()); String md5Password = new BigInteger(1, messageDigest.digest()).toString(16); //Set HTTPS request header- Authentication cookie = "hcp-ns-auth=" + uname64 + ":" + md5Password; System.out.println("Username: " + username + " Password: " + password); System.out.println(cookie); responce = adminAuth(cookie, httpClient); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyManagementException ex) { Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyStoreException ex) { Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex); } catch (UnrecoverableKeyException ex) { Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex); } int responceCode = responce.getStatusLine().getStatusCode(); return responceCode; } private HttpResponse adminAuth(String cookie, HttpClient hClient) { HttpResponse response = null; try { //Creating HTTP Post object String url = "https://millennium-test.hcp.millenniumit.com/query"; //String url = "https://hitachi.hcp1.hdspoc.com/query"; HttpPost httpPost = new HttpPost(url); httpPost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); //Setting HTTP Post headers for Authentication, Request type, Respond type and Encode type httpPost.addHeader("Cookie", cookie); httpPost.addHeader("Content-Type", "application/xml"); httpPost.addHeader("Accept", "application/json"); //httpPost.addHeader("Content-Encoding", "gzip"); //httpPost.addHeader("Accept-Encoding", "gzip"); Map<String, String> obj = new LinkedHashMap<String, String>(); obj.put("query", "+(namespace:\"data-set1.Millennium-Test\")"); obj.put("contentProperties", "false"); obj.put("objectProperties", "shred,retention"); obj.put("sort", "changeTimeMilliseconds+asc"); String jsonText = "{\"object\" :" + JSONValue.toJSONString(obj) + "}"; System.out.println(jsonText); XMLSerializer serializer = new XMLSerializer(); JSON json = JSONSerializer.toJSON(jsonText); serializer.setRootName("queryRequest"); serializer.setTypeHintsEnabled(false); String xml = serializer.write(json); xml = xml.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim(); System.out.println(xml); StringEntity stringEntity = new StringEntity(xml, HTTP.UTF_8); httpPost.setEntity(stringEntity); response = hClient.execute(httpPost); System.out.println(response.toString()); String sJson = EntityUtils.toString(response.getEntity()); System.out.println(sJson); HCP_Logger myLogger = new HCP_Logger(); myLogger.writeToLog(username, xml, response.toString()); } catch (IOException ex) { Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex); } return response; } private HttpResponse tenantAuth(String cookie, HttpClient hClient) { HttpResponse response = null; try { //Creating HTTP Post object String url = "sample url"; //String url = "sample url"; HttpPost httpPost = new HttpPost(url); httpPost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); //Setting HTTP Post headers for Authentication, Request type, Respond type and Encode type httpPost.addHeader("Cookie", cookie); httpPost.addHeader("Content-Type", "application/xml"); httpPost.addHeader("Accept", "application/json"); //httpPost.addHeader("Content-Encoding", "gzip"); //httpPost.addHeader("Accept-Encoding", "gzip"); Map obj = new LinkedHashMap(); obj.put("query", "+(namespace:\"sample")"); obj.put("contentProperties", "false"); obj.put("objectProperties", "shred,retention"); obj.put("sort", "changeTimeMilliseconds+asc"); String jsonText = "{\"object\" :" + JSONValue.toJSONString(obj) + "}"; //System.out.println(jsonText); XMLSerializer serializer = new XMLSerializer(); JSON json = JSONSerializer.toJSON(jsonText); serializer.setRootName("queryRequest"); serializer.setTypeHintsEnabled(false); String xml = serializer.write(json); xml = xml.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim(); //System.out.println(xml); //String xmll = "<queryRequest><object><query>namespace:\"data-set1.Millennium-Test\"</query><objectProperties>shred,retention</objectProperties><sort>changeTimeMilliseconds+asc</sort></object></queryRequest>"; //System.out.println(xmll); StringEntity stringEntity = new StringEntity(xml, HTTP.UTF_8); httpPost.setEntity(stringEntity); response = hClient.execute(httpPost); //System.out.println(response.toString()); // String sJson = EntityUtils.toString(response.getEntity()); //System.out.println(sJson); // HCP_Logger myLogger = new HCP_Logger(); // myLogger.writeToLog(username, xml, response.toString()); } catch (IOException ex) { Logger.getLogger(SSLAuthenticate.class.getName()).log(Level.SEVERE, null, ex); } return response; } } 

ACTUALIZAR:

Creo que encontré lo que está causando el error. Son las bibliotecas que utilizo dentro de la clase las excepciones. Estoy usando httpclient-4.2.5.jar, jackson-core-2.2.0.jar, json-lib-2.4-jdk15.jar, json-simple-1.1.1.jar y rt.jar dentro de mi clase. ¿Hay algún método que pueda utilizar estas bibliotecas sin causar la excepción?

3 Solutions collect form web for “No se pudo encontrar la clase referenciada desde el método android java.lang.NoClassDefFoundError”

Haga clic derecho en su

  project -> Build Path -> Configure Build Path -> Order and Export Tab. 

Asegúrese de que "Android Private Libraries" esté marcado para Exportar.

Si ha agregado bibliotecas de la libs / carpeta, quítelas, ya que se agregan automáticamente en la sección "Bibliotecas privadas de Android".

Haga clic con el botón secundario del mouse en el proyecto -> Propiedades-> Java Build Path -> Ordene y exporte la pestaña y seleccione sus bibliotecas privadas.

En la clase MainActivity: import com.example.hcpandroid.SSLAuthenticate; A continuación, después de que si ha importado el archivo jar de biblioteca externa importarlos a la carpeta LIB.

Haga clic derecho en su proyecto -> Propiedades -> Java Build Path -> Pedido y exportación -> Seleccionar todo -> Presione OK -> ir a limpiar su proyecto.

Espero que esto solucione su problema.

  • Eclipse: java.lang.NoClassDefFoundError para clases JDK en un proyecto de Android
  • NoClassDefFoundError al intentar ejecutar pruebas unitarias en Android Studio
  • Java.lang.NoClassDefFoundError en la versión de Android inferior a Lollipop
  • Java.lang.NoClassDefFoundError: android / graphics / drawable / Icono
  • NoClassDefFoundError - Rechazo de re-init en la clase con fallo anterior
  • NoClassDefFoundError en la biblioteca de Caligrafía
  • Extraño error NoClassDefFoundError al iniciar una versión firmada APK con proguard habilitado
  • Plataforma de Google+ para Android - NoClassDefFoundError: com.google.android.gms.samples.plus.SignInActivity
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.