Uploading image by using Retrofit - java

I've been trying to upload an image from my application through API. But I keep getting this as response:
{"error":"<p>You did not select a file to upload.<\/p>"}
This is my code:
APIService.java
#Multipart
#POST("/media/upload.html")
Call<UploadImg> uploadimage (#Part MultipartBody.Part file);
UploadImageActivity.java
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri uri = data.getData();
Picasso.with(this).load(uri).fit().into(btn_img_picker);
String imagePath;
if (data.toString().contains("content:")) {
imagePath = getRealPathFromURI(uri);
} else if (data.toString().contains("file:")) {
imagePath = uri.getPath();
} else {
imagePath = null;
}
File file = new File(imagePath);
System.out.println(imagePath);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("userfile", file.getName(), requestFile);
System.out.println(file.getName());
Call<UploadImg> call = mAPIService.uploadimage(body);
call.enqueue(new Callback<UploadImg>() {
#Override
public void onResponse(Call<UploadImg> call, Response<UploadImg> response) {
System.out.println(response.raw());
}
#Override
public void onFailure(Call<UploadImg> call, Throwable t) {
System.out.println(t);
}
});
}
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = getContentResolver().query(contentUri, proj, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
I have tested sending image in Postman's form-data. I can send a picture from my desktop and received intended response. But I can't do the same with my code in android.
Am I sending the incorrect path format of the image? Currently, variable imagePath has an output like this:
/storage/emulated/0/Download/download.jpg
If this is the incorrect path to send, please tell the correct one. Thanks in advance.

try this
#Multipart #POST("user/updateprofile") Observable<ResponseBody>
updateProfile(#Part("user_id") RequestBody id, #Part("full_name")
RequestBody fullName, #Part MultipartBody.Part image, #Part("other")
RequestBody other);
pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg"); RequestBody
requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
add another part within the multipart request
RequestBody fullName = RequestBody.create( MediaType.parse("multipart/form-data"), "Your Name");
service.updateProfile(id, fullName, body, other)

You can use below code for uploading image
First you write code for calling request
//profile pic is image path
RequestBody imagePath = Utility.imageToBody(profilePic);
TestApiInterface service = WebServiceCaller.getClient();
Call<SuccessResponse> call = service.mediaUpload(imagePath);
call.enqueue(new Callback<SuccessResponse>() {
#Override
public void onResponse(Call<SuccessResponse> call,
Response<SuccessResponse> response) {
SuccessResponse result;
if (response.isSuccessful()) {
result = response.body();
}
}
#Override
public void onFailure(Call<SuccessResponse> call, Throwable t) {
}
});
Then you write code for API
#Multipart
#POST("user/mediaupload")
Call<SuccessResponse> mediaUpload(#Part("media_file\"; filename=\"test_media.png\" ") RequestBody media_file);
Then code for Imagetobody covert is below
public static RequestBody imageToBody(String text) {
RequestBody requestBody;
if (text != null && text.length() > 0) {
MediaType MEDIA_TYPE = MediaType.parse("image/*");
File file = new File(text);
requestBody = RequestBody.create(MEDIA_TYPE, file);
} else {
requestBody = null;
}
return requestBody;
}

Try this I had another way to implement
Inside your interface
#Multipart
#POST("edit_profile")
Call<TokenResponse> getTokenAccess(#PartMap Map<String, RequestBody> map);
Call in your Activity
private void getData() {
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("your_base_url_here")
.addConverterFactory(GsonConverterFactory.create())
.build();
Click service=retrofit.create(Click.class);
File file = new File("/storage/sdcard0/Pictures/OGQ/Puskinn Sharma_Jump roof skyscraper_YkRiRWpYcw.jpg");
//make sure your image path is valid
String convert_File_2String= String.valueOf(file);
String fileNAme=convert_File_2String.substring(convert_File_2String.lastIndexOf("/")+1);
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "Sunil");
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "56");
RequestBody lastname= RequestBody.create(MediaType.parse("text/plain"), "Kumar");
Map<String, RequestBody> map = new HashMap<>();
map.put("profile_pic\"; filename=\""+fileNAme+"\" ", fbody);
map.put("firstname", name);
map.put("user_id", id);
map.put("lastname",lastname);
Call<TokenResponse> tokenResponseCall=service.getTokenAccess(map);
tokenResponseCall.enqueue(new Callback<TokenResponse>() {
#Override
public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
TokenResponse tokenResponse=response.body();
Log.e("93","MA>>"+tokenResponse.getJwt());
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<TokenResponse> call, Throwable throwable) {
Log.e("172","><<>>"+throwable);
Log.e("TAG", "onFailure: 173"+call.toString() );
}
});
}

Related

How to upload a file from Android to Java Web Service?

I'm trying to send a file from android to my webserver through a Rest API, but I don't know how to handle the MultipartBody.Part object in java.
API Request:
#Multipart
#POST("utilizadores/upload")
Call<ResponseBody> uploadPhoto(
#Part MultipartBody.Part fotografia);
Android Code:
File file = new File(getPath(data));
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part parts = MultipartBody.Part.createFormData("images", file.getName(), requestBody);
Call<ResponseBody> call = RetrofitClient
.getInstance()
.getApi()
.uploadPhoto(parts);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(getContext(), response.message(), Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
Java Code:
What should I pass as parameter in the next function 'uploadFile()'?
The value of fotografia is '(NULL)'.
#POST
#Path("/upload")
#Produces(MediaType.APPLICATION_JSON)
public Response uploadFile(#QueryParam("fotografia") String fotografia) {
BD bd = new BD();
int id = 54;
try {
String path = "/fotografias/" + id + ".jpg";
//guardarFicheiro(fotografia, path);
ConnectionBD connection = bd.abrirLigacao();
PreparedStatement ps = connection.getConn()
.prepareStatement("UPDATE utilizador SET fotografia=? WHERE id=?");
ps.setString(1, fotografia);
ps.setInt(2, id);
int x = ps.executeUpdate();
if (x > 0) {
bd.fecharConexao(connection);
return Response.ok().build();
}
bd.fecharConexao(connection);
} catch (SQLException ex) {
System.out.println(ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}

unable to post array into server using retrofit

i am trying to post multiple images with array but i am not able to send it into server because its shows some error
when i am trying to send images converted into bitmap it goes into onFailure method and shows error like below
error returns bitmap
D/Onfail: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCACKAIoDASIA
AhEBAxEB/8QAHgABAAIDAQADAQAAAAAAAAAAAAUIBgcJAwECBAr/xABSEAABAgIFAhEGCAsJAAAA
AAAEAAUDBgECBxQVESEIExgkJTE1QVFVV2FxlJXR1BYjNER1oRIXM0VUgZGWNzhDWGRlsbbF1fAm
NlNWpbXB4fH/xAAYAQEBAQEBAAAAAAAAAAAAAAAAAgQDBf/EACIRAQAABAYDAQAAAAAAAAAAAAAB
AxPhAkFhcpHBESGhcf/aAAwDAQACEQMRAD8A/toREWh44iIgIiICIiAiIgIiICIiAiIgIiICIiAi
IgIiwmd5/lGztqqPc4vENqDrxLqL5oqOcYR9FEFC2QN78ufaQZsirJqtrDePXX7uOng01W1hvHrr
93HTwaOdPX5dZtFWTVbWG8euv3cdPBpqtrDePXX7uOng0Kevy6zaKsmq2sN49dfu46eDWxbP7ZbO
bSiDA5Sfr4eHC02K3mClAHXf6UIIbnO3tvL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vepZEETgjHxQ19QF70wRj4oa+oC96lkQROC
MfFDX1AXvTBGPihr6gL3qWRBE4Ix8UNfUBe9MEY+KGvqAvepZEETgjH
this is my post method
private void PostInfo() {
bitmap = ((BitmapDrawable) defoult.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
ArrayList<String> filePaths = new ArrayList<>();
filePaths.add(imageString);
Log.d("strinimagess",imageString);
//filePaths.add("file:///storage/emulated/0/DCIM/Camera/IMG_20191207_131304.jpg");
// filePaths.add("file:///storage/emulated/0/DCIM/Camera/IMG_20191207_131300.jpgg");
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("skill_years", nameField.getText().toString());
builder.addFormDataPart("skill_where", nameField1.getText().toString());
builder.addFormDataPart("about_work", nameField2.getText().toString());
builder.addFormDataPart("skill_id", skill_id);
builder.addFormDataPart("user_id", user_id);
for (int i = 0; i < filePaths.size(); i++) {
File file = new File(filePaths.get(i));
builder.addFormDataPart("skill_images", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
}
MultipartBody requestBody = builder.build();
jsonObject = new JsonObject();
jsonObject.addProperty("skill_years", nameField.getText().toString());
jsonObject.addProperty("skill_where", nameField1.getText().toString());
jsonObject.addProperty("about_work", nameField2.getText().toString());
jsonObject.addProperty("skill_id", skill_id);
jsonObject.addProperty("user_id", user_id);
jsonObject.addProperty("skill_images", String.valueOf(myImageList));
RetrofitInterface jsonpost = ServiceGenerator.createService(RetrofitInterface.class,"http://littletreasure.org.in/");
Call<InFo_Post> call = jsonpost.post(requestBody);
call.enqueue(new Callback<InFo_Post>() {
#Override
public void onResponse(Call<InFo_Post> call, retrofit2.Response<InFo_Post> response) {
if (response.isSuccessful()){
Log.d("response", String.valueOf(response.body().getMsg()));
Toast.makeText(Info.this, "success", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<InFo_Post> call, Throwable t) {
Log.d("Onfail",t.getMessage());
Toast.makeText(Info.this, "failed", Toast.LENGTH_SHORT).show();
}
});
this is my Info Post model class
public class InFo_Post {
private String status;
private String msg;
private DataModel data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public DataModel getData() {
return data;
}
public void setData(DataModel data) {
this.data = data;
}
private class DataModel {
private String skill_years;
private String skill_where;
private String about_work;
private String skill_images;
public String getSkill_years() {
return skill_years;
}
public void setSkill_years(String skill_years) {
this.skill_years = skill_years;
}
public String getSkill_where() {
return skill_where;
}
public void setSkill_where(String skill_where) {
this.skill_where = skill_where;
}
public String getAbout_work() {
return about_work;
}
public void setAbout_work(String about_work) {
this.about_work = about_work;
}
public String getSkill_images() {
return skill_images;
}
public void setSkill_images(String skill_images) {
this.skill_images = skill_images;
}
}
}
i wrote a method that takes array of paths for images and return array of StringBase64
private ArrayList<String> imagesBase64(ArrayList<String> filePathes){
ArrayList<String> imagesBase64=new ArrayList<>();
for (int i = 0; i <filePathes.size() ; i++) {
Bitmap bm = BitmapFactory.decodeFile(filePathes.get(i));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
String imgString = Base64.encodeToString(b, Base64.NO_WRAP);
imagesBase64.add(imgString);
}
return imagesBase64;
}
but you must be sure your back-end receive array of Strings base64 to successfully upload it
Do you have just the bitmap or maybe you have also a file with that image ?
You can try create MultypartBody from data
private void sendFileToServer(String fileName) {
File file = new File(fileName);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
...
...
}
Also , don t forget in your WebService class to add annotation #Multipart at your post method
Make sure your API can handle a multiple files. Set your interface class with list of multipart files.
#Multipart
#POST("upload")
Call<ResponseBody> uploadMultipleFilesDynamic(
#Part("description") RequestBody description,
#Part List<MultipartBody.Part> files);
The second part of the implementation is using the new endpoint declaration and passing some files. Convert your files to multipart
#NonNull
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
}
#NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
File file = FileUtils.getFile(this, fileUri);
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
MultipartBody.Part is used to send also the actual file name.
List<MultipartBody.Part> parts = new ArrayList<>();
if (photoUri != null) {
parts.add(prepareFilePart("photo", photoUri));
}
RequestBody description = createPartFromString("hello, this is description speaking");
// create upload service client
FileUploadService service = ServiceGenerator.createService(FileUploadService.class);
// finally, execute the request
Call<ResponseBody> call = service.uploadMultipleFilesDynamic(description, parts);
call.enqueue(...);
You can refer this official link : https://futurestud.io/tutorials/retrofit-2-how-to-upload-a-dynamic-amount-of-files-to-server

Need to get a string from response returned by api using retrofit2

I am trying to get string value returned by API on success. I am getting success but I do not getting the required value in the response, but when I navigate to response-> body-> responseBody then it shows me that value but I am unable to get that value (please check screen shot for detail).
private void uploadImage(String imagePath) {
try{
showProgressDialogue();
File file = new File(imagePath);
RequestBody photoContent = RequestBody.create(MediaType.parse("multipart/form data"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("file",file.getName(),photoContent);
//RequestBody description = RequestBody.create(MediaType.parse("description"),"abc");
UploadService uploadService = APIClient.getClient().create(UploadService.class);
Call call1 = uploadService.UploadOMRExamPaper(photo);
call1.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, Response<Response> response) {
progressBar.dismiss();
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
progressBar.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}catch (Exception e){
progressBar.dismiss();
Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
}
}
Change your code:
From:
File file = new File(imagePath);
RequestBody photoContent = RequestBody.create(MediaType.parse("multipart/form data"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("file",file.getName(),photoContent);
To:
File file = new File(imagePath);
RequestBody photoContent = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("upload", file.getName(), photoContent );
Note:"upload" is just example here,you should write there from your api paramater.

Why the String inside Controller not printing anything?

I am trying to send Image and Id using retrofit for that i am sending Multipart file and String.
This is my Upload Method on Android side ->
private void UploadFiles() {
File uploadFile = fileArrayList.get(0);
if (uploadFile != null) {
Log.d(TAG, "UploadFiles: File Name is -> " + uploadFile.getName());
// Parsing any Media type file
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part cropImage = MultipartBody.Part.createFormData("cropImage", uploadFile.getName(), requestFile);
RequestBody cropId = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile.getParentFile().getName());
Api.uploadCropImage(cropImage,cropId, new Callback<BasicResponse>() {
#Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
if (response.body() != null) {
Log.d(TAG, "onResponse: Success" + response.body().getResponse());
}
else{
Log.d(TAG, "onResponse: null Response");
}
}
#Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
Log.d(TAG, "onResponse: Failure");
}
});
}
}
My Upload CropImage Method ->
public static void uploadCropImage(MultipartBody.Part multipartBody,RequestBody cropId,
Callback<BasicResponse> callback) {
UploadCropImageApi uploadCropImageApi = retrofit.create(UploadCropImageApi.class);
Call<BasicResponse> call = uploadCropImageApi.uploadCropImage(multipartBody,cropId);
call.enqueue(callback);
}
My Interface ->
public interface UploadCropImageApi {
#Multipart
#POST(UPLOAD_FILE_TO_AWS_URL)
Call<BasicResponse> uploadCropImage(#Part MultipartBody.Part cropImage, #Part("cropId") RequestBody cropId);
}
This is my Spring Controller, What's wrong with it? It's not printing cropId.
#RequestMapping(value = "/UploadCropImage", method = RequestMethod.POST, consumes = {"multipart/form-data"})
#ResponseBody
public String UploadImage(#RequestBody MultipartFile cropImage,#RequestBody String cropId ,HttpServletRequest request) {
System.out.println("String is -> " + cropId);
return null;
}
You cannot use two #RequestBody as it can bind to a single object only (the body can be consumed only once)
You need to use #RequestParam String cropId instead of RequestBody.
See here for clarification
UPDATE :Here is your controller method look like
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public #ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler(#RequestParam("name") String name, #RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location=" + serverFile.getAbsolutePath());
return null;
} catch (Exception e) {
return null;
}
}
}

retrofit2 for multipart file upload working in one class but not multiple class

I am using retrofit2 for multi part file upload. But when I use the below code in two forms, I get an error. I am using the code to upload profile creation and update after login. If I use this only in update profile or register page it's working fine.
My code [Client + Interface + Main class]:
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public interface FileUploadService {
#Multipart
#POST("ProfileFileUpload")
Call<ResponseBody> uploadFile(
#Part("authToken") RequestBody authToken,
#Part MultipartBody.Part docFile,
#Part("FileName") RequestBody FileName,
#Part("TypeName") RequestBody TypeName);
}
private void executeMultipartPost(String picturePath){
try {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofitProfile = new Retrofit.Builder()
.baseUrl("url")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
mFileUploadService = retrofitProfile.create(FileUploadService.class);
File file = new File(Environment.getExternalStorageDirectory(),picturePath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("docFile", file.getName(), requestFile);
RequestBody autoToken = RequestBody.create(MediaType.parse("text/plain"), "xxxxxxxxxx");
RequestBody FileName = RequestBody.create(MediaType.parse("text/plain"), file.getName());
RequestBody FileType = RequestBody.create(MediaType.parse("text/plain"), "image");
Call<ResponseBody> req = mFileUploadService.uploadFile(autoToken, body,FileName,FileType);
req.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
if (response.isSuccessful()) {
String Response="";
// dont work
String objRes = response.body().string();
JSONObject jsonObject = new JSONObject(objRes);
profileImage = jsonObject.optString("response").toString();
Response = jsonObject.optString("status").toString();
dialog.dialogBoxWithAlert(ActivityCreateAccount.this,"Alert", Response);
} else {
// works on failure
dialog.dialogBoxWithAlert(ActivityCreateAccount.this,"Error", "There is a error");
}
} catch (Exception e) {
e.printStackTrace();
}
progDailog.dismiss();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
progDailog.dismiss();
t.printStackTrace();
}
});
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
}
Crashlog
03-13 22:32:33.447 23389-23389/com.source.websys.rwm A/art: art/runtime/entrypoints/quick/quick_trampoline_entrypoints.cc:2077] Check failed: instr_code == Instruction::INVOKE_INTERFACE || instr_code == Instruction::INVOKE_INTERFACE_RANGE Unexpected call into interface trampoline: invoke-virtual {v1, v127, v2646493288, v85, v48}, thing#13744

Categories