Android Studio java.lang.NoSuchMethodError with an imported library

Edwin Vasquez picture Edwin Vasquez · Nov 3, 2015 · Viewed 10.3k times · Source

I imported the commons-codec-1.10.jar following the next steps:

  1. Under de app directory created a libs directory
  2. Copied manually the .jar inside the libs directory
  3. Right click the .jar inside android-studio and clicked Add as library

Added this line in my build.grade

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

In my class I imported the library like this:

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

Then I tried to access the encodeBase64String static method inside Base64 like this:

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

Nothing wrong there, even when I compile, except when I run the app, it throws the following error and the app shuts:

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)

My DoThisThing class is not inside the activity by the way, it's just to make it short. I checked the library an indeed the encodeBase64String is static. So I don't know exactly what to do, I'm new in the java and android environment . So any help would be much appreciated

Answer

Santiago Medina Chaverra picture Santiago Medina Chaverra · Nov 11, 2015

Replace

org.apache.commons.codec.binary.Base64 

for

android.util.Base64

And update your method like this.

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