728x90
반응형
작업이나 공부를 하면서 막힌 부분을 해결했던 것, 알고 싶었던 것이나 알리고 싶은 것을 올리는 블로그입니다
최대한 검증은 하겠지만 100% 정확한 글이 아니므로 단순 참고만 해주시길 바랍니다 :)
사실 공부한거 블로그 주인장이 안까먹을려고 올리는거임
파이어베이스
파이어베이스 데이터베이스에는 사진을 올릴 수 없으니 파이어베이스 스토리지에 업로드를 한 후 데이터베이스에는 파일의 다운로드 uri를 저장하여 사용한다
사진 선택하기
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:padding="10dp">
<ImageView
android:id="@+id/image_view"
android:layout_width="300dp"
android:layout_height="300dp"
android:src="@drawable/common_google_signin_btn_icon_dark"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<Button
android:id="@+id/button_select"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="사진 선택"
app:layout_constraintTop_toBottomOf="@+id/image_view"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:backgroundTint="#838383"
android:layout_marginTop="20dp"/>
<Button
android:id="@+id/button_upload"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="사진 업로드"
app:layout_constraintTop_toBottomOf="@+id/button_select"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:backgroundTint="#838383"
android:layout_marginTop="20dp"/>
<Button
android:id="@+id/button_show"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="사진 보기"
app:layout_constraintTop_toBottomOf="@+id/button_upload"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:backgroundTint="#838383"
android:layout_marginTop="20dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
public class MainActivity extends AppCompatActivity {
private Uri uri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = findViewById(R.id.image_view);
Button buttonSelect = findViewById(R.id.button_select);
buttonSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT );
intent.setType("image/*");
launcher.launch(intent);
}
});
}
private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == RESULT_OK && result.getData() != null) {
uri = result.getData().getData();
Log.d("test", uri.toString());
}
}
});
}
사진 선택은 StartActivityForResult가 지원이 중단되어서 ActivityResultLauncher를 사용하면 된다고 하네요
사진 Storage에 업로드
private void upload() {
StorageReference storageReference = FirebaseStorage.getInstance().getReference("Study");
storageReference.child("images").child("image").putFile(uri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
Toast.makeText(MainActivity.this, "업로드에 성공했습니다", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "업로드에 실패했습니다", Toast.LENGTH_SHORT).show();
}
}
});
}
저장은 Study/images/image로 저장이 됩니다.
getDownloadUri()로 사진 다운로드 uri 받고 이미지 설정
private void show() {
StorageReference storageReference = FirebaseStorage.getInstance().getReference("Study");
storageReference.child("images").child("image").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Glide.with(MainActivity.this).load(uri).into(imageView);
}
});
}
전체 코드
public class MainActivity extends AppCompatActivity {
private Uri uri;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.image_view);
Button buttonSelect = findViewById(R.id.button_select);
buttonSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
select();
}
});
Button button_upload = findViewById(R.id.button_upload);
button_upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
upload();
}
});
Button button_show = findViewById(R.id.button_show);
button_show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
show();
}
});
}
private void select() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT );
intent.setType("image/*");
launcher.launch(intent);
}
private void upload() {
StorageReference storageReference = FirebaseStorage.getInstance().getReference("Study");
storageReference.child("images").child("image").putFile(uri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
Toast.makeText(MainActivity.this, "업로드에 성공했습니다", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "업로드에 실패했습니다", Toast.LENGTH_SHORT).show();
}
}
});
}
private void show() {
StorageReference storageReference = FirebaseStorage.getInstance().getReference("Study");
storageReference.child("images").child("image").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Glide.with(MainActivity.this).load(uri).into(imageView);
}
});
}
private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == RESULT_OK && result.getData() != null) {
uri = result.getData().getData();
Log.d("test", uri.toString());
}
}
});
}
참고 링크
https://firebase.google.com/docs/storage/android/create-reference?hl=ko
728x90
반응형