I am trying to attach files to the letter. Now it turns out to choose a file from the explorer and send it to the array. Next, I display the attached files in the list. What is the problem - I can attach two identical files, and sometimes more 5. I can not understand what the problem is. In the end, I did a check, but it does not work as it should. Here are my steps to attach a file:
Select file via adapter:
fileManager.itemView.setOnClickListener(view -> { if (file.isDirectory()) { ((WriteResponseMess) ctx).recreateRecyclerView(file.getPath()); } else { if (getFolderSize(file) > 20) { ((WriteResponseMess) ctx).convertFileToString(file.getPath()); } else { Log.i("m", ">20"); } } });In the adapter, I check if the selected item in the list is a file or folder, and if this is a file, then we proceed to step 2.
Encode the file:
public void convertFileToString(String pathOnSdCard) { dialog.dismiss(); File file = new File(pathOnSdCard); if (ms.getArray() != null) { if (ms.getArray().size() > 0) { for (int i = 0; i < ms.getArray().size(); i++) { JsonObject object = ms.getArray().get(i).getAsJsonObject(); String nFile = object.get("filename").getAsString(); Log.i("m", nFile + "\n" + object.get("filename")); if (!file.getName().equals(nFile)) { try { byte[] data = FileUtils.readFileToByteArray(file); uploadFiles(ms.getArray(), new File(pathOnSdCard).getName(), Base64.encodeToString(data, Base64.NO_WRAP)); } catch (IOException e) { e.printStackTrace(); } } else { Toast.makeText(this, "You have already attached this file", Toast.LENGTH_SHORT).show(); } } } else { try { byte[] data = FileUtils.readFileToByteArray(file);//Convert any file, image or video into byte array uploadFiles(ms.getArray(), new File(pathOnSdCard).getName(), Base64.encodeToString(data, Base64.NO_WRAP)); } catch (IOException e) { e.printStackTrace(); } } } }
In this function, I check if there are already elements in the array, if there is, then I check if there is such a file already in the array, and it is this test that for some reason does not work for me correctly. It turns out if I choose the same file a second time, then I get a toast that the file has already been selected once, and anyway the file is attached. I feel that the problem is somewhere in the cycle but could not find where exactly. I hope for your help :)