2013-08-26 40 views
4

我打電話給一個單獨的類我已經寫在同一個包中,因爲我的MainActivity類已保存。但是當我運行該應用程序時,它給了我java.lang.NoClassDefFoundError。我不明白爲什麼在同一個包中定義的另一個類不能被識別。我已經嘗試了許多方法建議java.lang.NoClassDefFoundError,但沒有任何人解決了這個錯誤。無法找到從方法android java.lang.NoClassDefFoundError引用的類

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) 

主要活動類:

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類:

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

UPDATE:

我想我找到什麼引起的錯誤。這是我在課堂上使用的圖書館使這些例外。我在我的類中使用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。有什麼方法可以使用這些庫而不會導致異常?

+1

發佈您的代碼和日誌 – Ravi

+1

如果你添加任何jar文件,那麼要確保檢查同一個庫中的複選框,以便和導出選項卡 –

+0

清理並生成項目 –

回答

7

右擊你的

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

確保「Android的私人圖書館」被選中用於出口。

如果您已添加libs /文件夾中的任何庫,請將它們刪除,因爲它們會自動添加到「Android專用庫」部分中。

+0

我也這樣做過。事情是給我一個錯誤的類不是來自一個庫。我已經在同一個包裏面定義了它。 – Sajirupee

2

右鍵單擊project - > Properties-> Java Build Path - > Order and Export Tab並選擇你的私有庫。

+1

清理您的項目,然後嘗試。 –

+1

也做到了。仍然無法理解爲什麼它不能確定一個類在相同的包 – Sajirupee

+0

你的真棒。感謝很多 –

0

在MainActivity類中:import com.example.hcpandroid.SSLAuthenticate; 然後,如果你已經導入了外部庫jar文件,將它們導入到LIB文件夾。

右鍵單擊您的項目 - >屬性 - > Java Build Path - >訂單和導出 - >全選 - >按OK - >清理您的項目。

希望這可以解決您的問題。

相關問題