0

in fact I am in the process of preparing an android application that makes the upload of an image on a server thanks to a REST API.

I tested lapi with POSTMAN and I have no errors.

but have an error in this part: I that the crash app before intent this is my source codes:

 public class FileShooser extends AppCompatActivity {

private static final int INTENT_REQUEST_CODE = 100;
private String name ;

private CompositeSubscription mSubscriptions;
ProgressDialog progressdialog ;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    mSubscriptions = new CompositeSubscription();

    // get name from last activity
    name= getIntent().getStringExtra("Name");
    // start file shooser intent
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");

    try {

        startActivityForResult(intent, INTENT_REQUEST_CODE );

    } catch (ActivityNotFoundException e) {
        e.printStackTrace();
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode==INTENT_REQUEST_CODE)
    {
            if(resultCode==RESULT_OK){

                uploadImage( data.getData());
            }
    }

}
public byte[] getBytes(InputStream is) throws IOException {
    ByteArrayOutputStream byteBuff = new ByteArrayOutputStream();

    int buffSize = 1024;
    byte[] buff = new byte[buffSize];

    int len = 0;
    while ((len = is.read(buff)) != -1) {
        byteBuff.write(buff, 0, len);
    }

    return byteBuff.toByteArray();
}
private void uploadImage(Uri fileUri) {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);

    // use the FileUtils to get the actual file by uri
    File file = new File(fileUri.getPath());

    showSnackBarMessage("name:"+file.getName());

    // create RequestBody instance from file
    RequestBody requestFile =
            RequestBody.create(
                    MediaType.parse(getContentResolver().getType(fileUri)),
                    file
            );
    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("image", file.getName(), requestFile);

    // progress dialog
    progressdialog = new ProgressDialog(getApplicationContext());
    progressdialog.setMessage("Please wait ...");
    progressdialog.show();

      retrofitInterface.upload(name,body).observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(this::handleResponse,this::handleError);

}

private void handleError(Throwable error) {
    progressdialog.dismiss();
    if (error instanceof HttpException) {

        Gson gson = new GsonBuilder().create();

        try {

            String errorBody = ((HttpException) error).response().errorBody().string();
            Response response = gson.fromJson(errorBody,Response.class);
            showSnackBarMessage(response.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {

        showSnackBarMessage("Network Error !");
    }
}

private void handleResponse(Response response) {
    progressdialog.dismiss();
    showSnackBarMessage(response.getMessage());

}

private void showSnackBarMessage(String message) {
    Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}
 }

thank you very much for your answers

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
hatem dagbouj
  • 139
  • 1
  • 2
  • 12
  • whats the crash / stacktrace? – Cody Caughlan Oct 07 '18 at 09:41
  • If you're using Marshmallow (API 23) or higher versioned devices to test this code, I'd assume that the error is occurring due to SecutiryException for storage access. Please request for Runtime Permission (for storage) in your code. If that's not the case, please [edit] and post the error log here. – Shashanth Oct 07 '18 at 17:13
  • @CodyCaughlan is stacktrace :( any help . – hatem dagbouj Oct 08 '18 at 00:51
  • @Shashanth i use android 6.0 ( Marshmallow with api 23 ) , and i have this permission in my manifests file : – hatem dagbouj Oct 08 '18 at 00:53
  • please any help @Shashanth – hatem dagbouj Oct 08 '18 at 00:57
  • Yeah that's what I said in my previous comment. You need to ask [Runtime Permission](https://developer.android.com/training/permissions/requesting#java) if you're targeting API 23 or above. Asking those permissions in Manifest file isn't sufficient. You need to ask it before showing file chooser intent. Refer this SO [thread](https://stackoverflow.com/q/33162152/5180017) for your requirement. – Shashanth Oct 08 '18 at 05:05

0 Answers0