본문 바로가기
📱| Android/🔥 | Firebase

[Android, Kotlin] firebase sns 앱 만들기 3(게시물 생성)

by immgga 2022. 7. 4.

이번에는 게시글을 생성하는 기능을 만들어 보자

 

1. 갤러리로 사진 불러오기

var PICK_IMAGE_FROM_ALBUM = 0
var photoUri: Uri? = null

val photoPickerIntent = Intent(Intent.ACTION_PICK)
photoPickerIntent.type = "image/*"
startActivityForResult(photoPickerIntent, PICK_IMAGE_FROM_ALBUM)

. . .

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == PICK_IMAGE_FROM_ALBUM) {
        photoUri = data?.data
        Log.d("SUCCESS", "onActivityResult photo uri: $photoUri")
        binding.uploadImg.setImageURI(photoUri)
    } else {
        Log.d("FAIL", "onActivityResult: 문제가 발생함")
        finish()
    }
}
  • PICK_IMAGE_FROM_ALBUM: 갤러리로 이동할때 전달되서, onActivityResult에서 requestCode가 같은지 확인하는 변수
  • onActivityResult에서 PICK_IMAGE_FROM_ALBUM와 requestCode가 같으면 photoUri에 사진 uri를 저장하고, imageView에 보여준다

 

2. 파일 업로드

private val postDto = PostDto()

. . .

// file 형식 만들기
val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val imageFileName = "IMAGE_${timestamp}_.png"
val storageRef = storage?.reference?.child("images")?.child(auth?.uid!!)?.child(imageFileName)

// 업로드, 데이터베이스 추가
storage?.reference?.child("profileImage")?.child(auth?.uid!! + ".png")?.downloadUrl
    ?.addOnSuccessListener { imageUri ->
        postDto.profileImg = imageUri.toString()
    }

storageRef?.putFile(photoUri!!)?.addOnSuccessListener {
    storageRef.downloadUrl.addOnSuccessListener { uri ->
        postDto.imageUrl = uri.toString()
        getData()
    }
}
  • 파일 형식: 현재 날짜
  • putFile로 이미지를 넣으면 firebase storage에 파일 데이터가 저장됨

 

3. 포스팅 기능 구현

private fun getData() {
    // data 담기
    postDto.explain = binding.commentPost.text.toString()
    postDto.uid = auth?.currentUser?.uid
    postDto.userId = auth?.currentUser?.email
    postDto.tag1 = binding.hashiText1.text.toString()
    postDto.tag2 = binding.hashiText2.text.toString()
    postDto.tag3 = binding.hashiText3.text.toString()

    val time = System.currentTimeMillis()
    val date = Date(time)
    val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:MM")
    postDto.timestamp = dateFormat.format(date)

    fireStore.collection("posts").document().set(postDto).addOnCompleteListener {
        if (it.isSuccessful) {
            Toast.makeText(this, "업로드가 완료되었습니다.", Toast.LENGTH_SHORT).show()
            finish()
            startActivity(Intent(this, MainPageActivity::class.java))
        }
    }
}
  • postDto: 포스팅 정보를 저장할 변수
  • postDto에 데이터를 담은 후 firebase firestore에 저장한다
  • 성공하면 액티비티 종료후 MainPageActivity로 이동

 

4. 결과 화면

 

728x90

댓글