iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 25
1
Mobile Development

Android 開發經驗三十天系列 第 25

[Android 開發經驗三十天]D25一小畫家串接自己寫的上傳API+打開圖片+選擇圖片

  • 分享至 

  • xImage
  •  

努力的人不一定能成功,但是成功的人,一定都曾努力。努力寫完今天這篇吧!


tags: 鐵人賽 Templates

今天我們來介紹
打開圖片庫
選擇圖片
串接上傳API
MVVM + kotlin +LiveData

0.retofit,Api設定
ApiService
用defferd是因為corutine

interface ApiService {


    @GET("searchAllFile")
    fun getFilenameAndUrl(): Deferred<List<UrLAndFilenameResponse>>

}

RetrofitManager
192.168.1.227 ->可以改成自己api的ip

class RetrofitManager private constructor(){
    private val retrofit : Retrofit
    private val httpClient:OkHttpClient= OkHttpClient()

    //初始化
    init {
        retrofit=Retrofit.Builder()
            .baseUrl("http://\uFEFF192.168.1.227:8080/")
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .client(httpClient)
            .build()
    }

    companion object{
        private val manager=RetrofitManager()
        val client :Retrofit
            get()= manager.retrofit
    }
}

1.ViewModel
這裡用打完API就改變liveData
打得是上傳圖片API

class PickerPhotoViewModel (): ViewModel(){
    var showProgress: MutableLiveData<PickerPhotoResponse> = MutableLiveData()

    fun getListData(fileOrgName :String,path:String,userName:String="uu"){
        CoroutineScope(Dispatchers.IO).launch {
            //waint
           try {
               val client = OkHttpClient().newBuilder()
                   .build()
               val mediaType = MediaType.parse("text/plain")
               val body = MultipartBody.Builder().setType(MultipartBody.FORM)
                   .addFormDataPart(
                       "file", fileOrgName,
                       RequestBody.create(
                           MediaType.parse("application/octet-stream"),
                           File(path)
                       )
                   )
                   .addFormDataPart("userName", userName)
                   .build()
               val request = Request.Builder()
                   .url("http://192.168.1.227:8080/uploadFile")
                   .method("POST", body)
                   .build()
               val response = client.newCall(request).execute()

               Log.d("aaa",response.toString())
               if (response.isSuccessful){
                   var p=PickerPhotoResponse("ok",false)

                   showProgress.postValue(p)
               }
               else{
                   var p=PickerPhotoResponse(response.message(),false)
                   showProgress.postValue(p)
               }
           }catch (e : ConnectException){
               var p=PickerPhotoResponse("internnet connection",false)
               showProgress.postValue(p)
           }

        }
    }
}

2.打開圖片
開啟Pictures畫面Type設定為image
用action設定是ACTION_GET_CONTENT
可以用startActivityForResult返回本畫面,設定返回碼

 btn.setOnClickListener {
            val intent = Intent()
            intent.type = "image/*"
            intent.action = Intent.ACTION_GET_CONTENT
            startActivityForResult(intent, 2)
        }

3.onActivityResult&&打API

@RequiresApi(Build.VERSION_CODES.KITKAT)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        ....

            }
        }

判斷resultcode是什麼在做下一步,如果reqestCode是你設定的就是代表他真的返回到Activity
並拿出path

   when (requestCode) {
        
            2-> if (resultCode === Activity.RESULT_OK) {//resultcode是setResult裡面設定的code值
                var path= FileUtils.getPath(this,data?.data)
                var ff= File(path);
                Log.d("aaaa",path.toString())
                Log.d("aaaawqweqq",path.lastIndexOf("/").toString()+path.lastIndexOf(".").toString())
                Log.d("aaaa",path.substring(path.lastIndexOf("/")+1,path.lastIndexOf(".")))
                var fileOrgName=path.substring(path.lastIndexOf("/")+1)

打上傳API
viewModel.getListData(fileOrgName,path)
show出progresDialog

  showProgressDialog("loading",this)

創observer監聽,如果回傳值是對的就顯示並關掉progressDialog

   val nameObserver = Observer<PickerPhotoResponse> {
                        list ->
                            if (!list.progressShow){
                                dismissProgressDialog()
                                if (list.message=="ok"){
                                    var bitmap = BitmapFactory.decodeFile( ff.path )
                                    var img=findViewById<ImageView>(R.id.ff)
                                    img.setImageBitmap(bitmap)
                                }else{
                                    Toast.makeText(this,list.message,Toast.LENGTH_LONG)
                                }

                            }
                }

viewmodel綁定監聽器
` viewModel.showProgress.observe(this, nameObserver)```


上一篇
[Android 開發經驗三十天+Spring Boot]D24一Spring Boot Download file(下載檔案)
下一篇
[Android 開發經驗三十天]#D26一Glide教學+小畫家繼續
系列文
Android 開發經驗三十天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言