找不到从方法android java.lang.NoClassDefFoundError引用的类 [英] could not find class referenced from method android java.lang.NoClassDefFoundError

查看:1703
本文介绍了找不到从方法android java.lang.NoClassDefFoundError引用的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用一个单独的类,我已在同一个包中编写,因为我的 MainActivity 类已保存。但是当我运行应用程序时,它给了我 java.lang.NoClassDefFoundError 。我无法理解为什么无法识别在同一个包中定义的另一个类。我已经尝试了很多方法建议 java.lang.NoClassDefFoundError 但是没有任何方法解决了错误。

I'm calling for a separate class I have written in same package as my MainActivity class is saved. but when I run the application it gives me java.lang.NoClassDefFoundError. I can't understand why another class defined in same package cannot be identified. I have tried many methods suggest for java.lang.NoClassDefFoundError but not any of them resolved the 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)

Main活动类:

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();
    }

}

SSLAuthentication class:

SSLAuthentication class:

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;
    }
}

更新:

我想我发现了导致错误的原因。我在课堂上使用的库就是例外。我在我的班级里面使用了httpclient-4.2.5.jar,jackson-core-2.2.0.jar,json-lib-2.4-jdk15.jar,json-simple-1.1.1.jar和rt.jar。有没有任何方法可以使用这些库而不会导致异常?

I think I found what's causing the error. It's the libraries I used inside the class make that exceptions. I'm using httpclient-4.2.5.jar, jackson-core-2.2.0.jar, json-lib-2.4-jdk15.jar, json-simple-1.1.1.jar and rt.jar inside my class. Is there any method I can use these libraries without causing the exception?

推荐答案

右键单击

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

确保选中Android Private Libraries进行导出。

Make sure that "Android Private Libraries" is checked for Export.

如果你已经从libs /文件夹中添加了任何库,请删除它们,因为它们会自动添加到Android私有库部分。

If you've added any libraries from the libs/ folder, remove them as they are automatically added in the "Android Private Libraries" section.

这篇关于找不到从方法android java.lang.NoClassDefFoundError引用的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆