2017-06-19 104 views
0

我試圖從手機的圖庫上傳圖片到Firebase,但模擬器不斷關閉,並且沒有記錄任何錯誤。這裏是我的代碼上傳圖片到Firebase的問題

val PICK_IMAGE_CODE=123 
fun loadImage(){ 
    var intent = Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI) 
    startActivityForResult(intent,PICK_IMAGE_CODE) 
} 

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { 
    super.onActivityResult(requestCode, resultCode, data) 
    if(requestCode==PICK_IMAGE_CODE && data!=null && resultCode == RESULT_OK){ 

     val selectedImage=data.data 
     val filePathColum= arrayOf(MediaStore.Images.Media.DATA) 
     val cursor= contentResolver.query(selectedImage,filePathColum,null,null,null) 
     cursor.moveToFirst() 
     val coulomIndex=cursor.getColumnIndex(filePathColum[0]) 
     val picturePath=cursor.getString(coulomIndex) 
     cursor.close() 
     uploadImage(BitmapFactory.decodeFile(picturePath)) 
    } 


} 

var DownloadURL:String?="" 

fun uploadImage(bitmap:Bitmap){ 
    adapter!!.notifyDataSetChanged() 

    var currentUser = mAuth!!.currentUser 

    val storage= FirebaseStorage.getInstance() 
    val storgaRef=storage.reference 
    val df= SimpleDateFormat("ddMMyyHHmmss") 
    val dataobj= Date() 
    val imagePath= currentUser!!.uid+ "."+ df.format(dataobj)+ ".jpg" 
    val ImageRef=storgaRef.child("imagePost/"+imagePath) 
    val baos= ByteArrayOutputStream() 
    bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos) 
    val data= baos.toByteArray() 
    val uploadTask=ImageRef.putBytes(data) 
    uploadTask.addOnFailureListener{ 
     Toast.makeText(applicationContext,"fail to upload", Toast.LENGTH_LONG).show() 
    }.addOnSuccessListener { taskSnapshot -> 

     DownloadURL= taskSnapshot.downloadUrl!!.toString() 
     ListTweets.removeAt(0) 
     adapter!!.notifyDataSetChanged() 

    } 
} 

如果我註釋掉調用我做出uploadImage模擬器不會崩潰,所以我覺得有一些與我得到的picturePath的方式怎麼回事,但我不知道。誰能幫我嗎?

回答

0

我想通了,我沒有要求權限,所以我使用的picturePath始終爲空