Android Загрузить изображение с камеры и галереи с помощью Retrofit - PullRequest
0 голосов
/ 26 августа 2018

Я использую Retrofit для загрузки изображений на сервер, но я не могу завершить, и я даже не могу найти в чем ошибка в коде.

Мне не нужно показывать результат изображения пользователюперед загрузкой, но нужно получить файл для загрузки только тогда, когда пользователь нажимает кнопку регистрации.

Используется для захвата изображений:

fun dispatchTakePicture(){
    var takePictureIntent:Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    //Ensure for atleast one camera activity
    if(takePictureIntent.resolveActivity(packageManager) != null){
        var photoFile: File? = null
        try {
            photoFile = createImageFile()
            toast("dispatchTakePicture"+photoFile.toString())
        }catch (e:IOException){
            Log.d(LOG_TAG,e.printStackTrace().toString())
        }

        if(photoFile !=null) {
            var photoUri:Uri = FileProvider.getUriForFile(this,"com.example.android.fileprovider",photoFile)
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoUri)
            startActivityForResult(takePictureIntent,REQUEST_IMAGE_CAPTURE)
        }
    }
}

Этот код предназначен для получения изображения из галереи:

 private fun getImageFromGallery(){
    val intent:Intent = Intent()
    intent.setType("image/*")
    intent.setAction(Intent.ACTION_GET_CONTENT)
    startActivityForResult(intent,REQUEST_GALLERY_IMAGE)
}

Вот где я обрабатываю результат:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

    var bitmap:Bitmap

    Log.i("OnActivityResult","Before checking data Null")

    if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK && data!=null && data.data!=null){
        Log.i("OnActivityResult","After checking data Null")

        bitmap = data?.extras?.get("data") as Bitmap
        toast("OnActivityResult"+bitmap.toString())
        Log.i("OnActivityResult","END of function checking data Null")
    }
    else if(requestCode == REQUEST_GALLERY_IMAGE && resultCode == Activity.RESULT_OK && data != null)
    {
        Log.e("onActivityResult()->","Gallery Result")
        var targetUri:Uri = data!!.data
        try {
            bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(targetUri))
            toast("OnActivityResult"+bitmap.toString())
            Log.e("onActivityResult()->",bitmap.toString())
            global_photoFile = File(targetUri.toString())
            Log.e("onActivityResult()->",global_photoFile.toString())
            Log.e("onActivityResult()->",currentPhotoPath.toString())
        }catch (e:FileNotFoundException){
            e.printStackTrace()
        }
    }



}

Модифицированный CallBack:

        val call:Call<ResponseBody> = userClient.performRegistration(username,email,password, location,requestFile)

        call.enqueue(object :Callback<ResponseBody>{
            override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
                Log.d(LOG_TAG+"-> onFailure",t?.printStackTrace().toString())
            }

            override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
                try {
                    if (response?.code() == 201) {
                        Log.d("onResponse->","User Created")
                        toast(response.code().toString())
                        //showLogin()
                    }
                    else{
                        toast("Some other Response")
                        toast(response?.code().toString())
                    }
                }catch (e:Exception){
                    Log.d(LOG_TAG,e.printStackTrace().toString())
                }
            }

        })

Метод запроса на модификацию:

@Multipart
@POST("profile/")
Call<ResponseBody> performRegistration(@Part("username") RequestBody username,
                                       @Part("email")    RequestBody email,
                                       @Part("password") RequestBody password,
                                       @Part("location") RequestBody location,
                                       @Part MultipartBody.Part profile_pic);

Это мой метод регистрации:

fun performSignup(){

    val name_et:String = et_full_name.text.toString()
    val email_et:String = et_email_address.text.toString()
    val password_et:String = password.text.toString()
    val location_et:String = location.text.toString()


    var username:RequestBody = RequestBody.create(MultipartBody.FORM,name_et)
    var email:RequestBody = RequestBody.create(MultipartBody.FORM,email_et)
    var password:RequestBody = RequestBody.create(MultipartBody.FORM,password_et)
    var location:RequestBody = RequestBody.create(MultipartBody.FORM,location_et)

    val mainfile:File = File(currentPhotoPath)
    var filePart:RequestBody = RequestBody.create(
            MediaType.parse(contentResolver.getType(Uri.parse(currentPhotoPath.toString()))),
            mainfile)

    var requestFile:MultipartBody.Part = MultipartBody.Part.createFormData("profile_pic",mainfile.name,filePart)//....}

Это строка ошибки:

  MediaType.parse(contentResolver.getType(
  Uri.parse(currentPhotoPath.toString()))),
            mainfile)

    var requestFile:MultipartBody.Part = MultipartBody.Part.createFormData("profile_pic",mainfile.name,filePart)

LogCat:

  --------- beginning of crash
    2018-08-26 15:50:32.458 31602-31602/com.example.viredapp 
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.viredapp, PID: 31602
java.lang.NullPointerException: Attempt to invoke interface method 'int 
java.lang.CharSequence.length()' on a null object reference
    at java.util.regex.Matcher.reset(Matcher.java:1059)
    at java.util.regex.Matcher.<init>(Matcher.java:187)
    at java.util.regex.Pattern.matcher(Pattern.java:1010)
    at okhttp3.MediaType.get(MediaType.java:53)
    at okhttp3.MediaType.parse(MediaType.java:106)
    at com.example.viredapp.ui.SignUpActivity.performSignup(SignUpActivity.kt:87)
    at com.example.viredapp.ui.SignUpActivity$onCreate$3.onClick(SignUpActivity.kt:67)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
...