UploadPdfActivity.java
package com.sjcoding.admincollegeapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
public class UploadPdfActivity extends AppCompatActivity {
private CardView addPdf; // pdf 업로드 버튼
private EditText pdfTitle;
private Button uploadPdfButton; // pdf 업로드 버튼
private TextView pdfTextView;
private String pdfName, title;
private final int REQ = 1000; // 응답
private ProgressDialog pd; // 다이알로그
private DatabaseReference databaseReference;
private StorageReference storageReference;
private String downloadUrl = "";
private Uri pdfData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_pdf);
// 레퍼런스를 가져옴
databaseReference = FirebaseDatabase.getInstance().getReference();
storageReference = FirebaseStorage.getInstance().getReference();
pd = new ProgressDialog(this);
pdfTitle = findViewById(R.id.pdf_title);
pdfTextView = findViewById(R.id.tv_pdf);
addPdf = findViewById(R.id.add_pdf);
addPdf.setOnClickListener((view) -> {openGallery();});
// pdf 업로드 버튼 클릭클릭!
uploadPdfButton = findViewById(R.id.btn_upload_pdf);
uploadPdfButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
title = pdfTitle.getText().toString();
if(title.isEmpty()) {
pdfTitle.setError("제목은 필수사항입니다.");
pdfTitle.requestFocus();
} else if(pdfData == null) {
Toast.makeText(UploadPdfActivity.this, "Please upload pdf", Toast.LENGTH_SHORT).show();
} else {
uploadPdf();
}
}
});
}
private void uploadPdf() {
pd.setTitle("please wait...");
pd.setMessage("Uploading pdf");
pd.show();
StorageReference _storageReference = storageReference.child("pdf/" + pdfName + System.currentTimeMillis() + ".pdf");
_storageReference.putFile(pdfData)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isComplete()); // 비동기처리
Uri uri = uriTask.getResult();
uploadData(String.valueOf(uri));// String.valueOf()는 toString()의 기능과 같지만 npe가 발생하지 않는다 task는 toString()이 구현되지않아서 String.valueOf()를 써야한다
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(UploadPdfActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
// 파일 열기
private void openGallery() {
Intent intent = new Intent();
intent.setType("pdf/docs/ppt");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent.createChooser(intent, "Select Pdf File"), REQ);
}
// 결과값
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ && resultCode == Activity.RESULT_OK) {
pdfData = data.getData();
if(pdfData.toString().startsWith("content://")) { // 안드로이드 보안 정책 강화로인해 file://로 돌아오던 파일 real path가 content://이런식으로 돌아옴
Cursor cursor = null; // 데이터의 위치 정보
try {
cursor = UploadPdfActivity.this.getContentResolver().query(pdfData, null, null, null, null);
if(cursor != null && cursor.moveToFirst()) {
pdfName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); // pdf 이름
}
} catch (Exception e) {
e.printStackTrace();
}
} else if(pdfData.toString().startsWith("file://")) {
pdfName = new File(pdfData.toString()).getName();
}
pdfTextView.setText(pdfName);
}
}
private void uploadData(String downloadUrl) {
String uniqueKey = databaseReference.child("pdf").push().getKey();
HashMap data = new HashMap();
data.put("pdfTitle", title);
data.put("pdfUrl", downloadUrl);
databaseReference.child("pdf").child(uniqueKey).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
pd.dismiss();
Toast.makeText(UploadPdfActivity.this, "pdf uploaded successfully", Toast.LENGTH_SHORT).show();
pdfTitle.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(UploadPdfActivity.this, "Failed to uploaded pdf", Toast.LENGTH_SHORT).show();
}
});
}
}
activity_upload_pdf.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".UploadPdfActivity"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.card.MaterialCardView
android:layout_width="130dp"
android:layout_height="150dp"
android:layout_margin="10dp"
android:id="@+id/add_pdf"
app:cardElevation="5dp"
android:layout_gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:background='@drawable/circle_yellow'
android:src="@drawable/ic_pdf"
android:padding="15dp"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/lightGray"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Pdf"
android:textStyle="bold"
android:padding="5dp"
android:layout_marginTop="10dp"
android:textColor="@color/textColor"/>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_pdf"
android:text="No file Selected"
android:layout_gravity="center"
android:textSize="16sp"/>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="pdf title"
android:id="@+id/pdf_title"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload Pdf"
android:layout_marginTop="16dp"
android:textAllCaps="false"
android:id="@+id/btn_upload_pdf"/>
</LinearLayout>
</ScrollView>