簡體   English   中英

帶有導入庫的Android Studio java.lang.NoSuchMethodError

[英]Android Studio java.lang.NoSuchMethodError with an imported library

我按照以下步驟導入了commons-codec-1.10.jar:

  1. 在de app目錄下創建了一個libs目錄
  2. 手動復制libs目錄中的.jar
  3. 右鍵單擊android-studio中的.jar,然后單擊Add as library

在我的build.grade中添加了這一行

compile fileTree(dir: 'libs', include: ['*.jar'])

在我的課上我導入了這樣的庫:

import org.apache.commons.codec.binary.Base64;

然后我嘗試在Base64中訪問encodeBase64String靜態方法,如下所示:

public static class DoThisThing {
    public String DoThisOtherThing() {
        String hashed = "hello";
        String hash = Base64.encodeBase64String(hashed.getBytes());
        return hash;
    }
}

public class ActivityThing extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity_thing);
        String hash = DoThisThing.DoThisOtherThing();
        System.out.println(hash);
    }
}

沒有錯,即使我編譯,除非我運行應用程序,它會拋出以下錯誤,應用程序關閉:

11-03 09:41:27.719 2390-2476/com.myproject E/AndroidRuntime:  Caused by: java.lang.NoSuchMethodError: No static method encodeBase64String([B)Ljava/lang/String; in class Lorg/apache/commons/codec/binary/Base64; or its super classes (declaration of 'org.apache.commons.codec.binary.Base64' appears in /system/framework/org.apache.http.legacy.boot.jar)

順便說一下,我的DoThisThing類不在活動內部,只是為了縮短它。 我檢查了庫,確實是encodeBase64String是靜態的。 所以我不確切知道該怎么做,我是java和android環境中的新手。 所以任何幫助將不勝感激

更換

org.apache.commons.codec.binary.Base64 

對於

android.util.Base64

並像這樣更新你的方法。

public static class DoThisThing {
 public String DoThisOtherThing() {
    String hashed = "hello";
    byte[] data = hashed.getBytes("UTF-8");
    String hash = Base64.encodeToString(data, Base64.DEFAULT);
    return hash;
 }
}

Android框架包括類路徑上的commons-codec庫的古代版本(1.3)。 在運行時,它將使用其類而不是與您的應用程序打包的類。 Base64#encodeBase64String方法在1.4中引入,因此您將收到java.lang.NoSuchMethodError異常。

一種可能的解決方案是通過使用jarjar重新打包來更改庫的命名空間。

請參閱我的博客文章 ,更詳細地解釋了該問題,並展示了如何重新打包庫。

好吧,告訴大家,我無法解決這個問題。 我使用原生的android庫進行編碼和解碼,它位於android.util.Base64中

            String hash = Base64.encodeToString(hasheado.doFinal(json.getBytes()), Base64.DEFAULT);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM