How to Upload and Retrieve PDF Files in Firebase Storage in Android Studio ?

How to upload and retrieve Pdf Files in Firebase Storage in Android Studio ? 

Step 1 - Create a new Project and add permissions in Manifest File

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Step 2 - Design Your activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">

<ImageView
android:id="@+id/uploadpdf"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_margin="21dp"
android:src="@drawable/ic_baseline_picture_as_pdf_24" />

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:hint="PDF NAME"
android:inputType="textPersonName"
android:textSize="24sp"
android:textStyle="bold" />

<Button
android:id="@+id/uploadBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="UPLOAD PDF" />

<Button
android:id="@+id/pdflist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ALL PDF LIST" />

</LinearLayout>
Step 3 - Write code in your MainActivity.java
before onCretate method initialize these views

// INITIALIZE ALL VIEWS
ImageView selectPdf;
Button uploadBtn, pdfListsBtn;
EditText editText;
StorageReference storageReference;
DatabaseReference databaseReference;

in onCreate method write this code 

   //  GET ALL VIEW BY ID
selectPdf = findViewById(R.id.uploadpdf);
editText = findViewById(R.id.editText);
uploadBtn = findViewById(R.id.uploadBtn);
pdfListsBtn = findViewById(R.id.pdflist);


uploadBtn.setEnabled(false);

// AFTER CLICKING ON selectPdF BUTTON WE WILL REDIRECTED TO CHOOSE PDF
selectPdf.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("application/pdf");
startActivityForResult(galleryIntent, 1);
Toast.makeText(MainActivity.this, "Select Pdf ", Toast.LENGTH_SHORT).show();
}
});
// AFTER CLICKING ON pdfListsBtn BUTTON WE WILL REDIRECTED SHOW PDF FILES ACTIVITY
pdfListsBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ViewPdfActivity.class);
startActivity(intent);
}
});
}
// CREATE A PROGRESS DIALOG TO SHOW BEFORE UPLOADING
ProgressDialog dialog;


// OVERRIDE A METHOD onActivityResult METHOD WHICH REDIRECT PDF FILE SELECTED SUCCESSFULLY
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
dialog = new ProgressDialog(this);
if (editText.getText().toString().isEmpty()) {
editText.setError("Required");
} else {
uploadBtn.setEnabled(true);
}
// AFTER CLICKING ON upload BUTTON WE WILL REDIRECTED TO UPLOAD PDF FILES METHOD
uploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Here we are initialising the progress dialog box
dialog.setMessage("Uploading...");
dialog.show();
uploadPdfFiles(data.getData());
}
});
}
}

// THIS IS METHOD FOR UPLOADS PDF FILES
private void uploadPdfFiles(Uri data) {
// GET REFERENCES OF DATABASE AND STORAGE
storageReference = FirebaseStorage.getInstance().getReference("uploads/");
databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
// CODE FOR UPLOAD PDF
StorageReference reference = storageReference.child("pdf_" + System.currentTimeMillis() + ".pdf");
reference.putFile(data).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();
UploadPdfModel model = new UploadPdfModel(editText.getText().toString(), uri.toString());
databaseReference.child(databaseReference.push().getKey()).setValue(model);
dialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});

}

For retrieving data from firebase 

Step 1 - Create a new activity ViewPdfActivity and design xml file

<?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=".ViewPdfActivity">

<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Write code in your PdfViewActivity.java
before onCretate method initialize these views

ListView listView;
//database reference to get uploads data
DatabaseReference mDatabaseReference;
//list to store uploads data
List<UploadPdfModel> uploadList;


in onCreate method write this code 

  uploadList = new ArrayList<>();
listView = (ListView) findViewById(R.id.listview);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//getting the upload
UploadPdfModel upload = uploadList.get(i);

//Opening the upload file in
Intent intent = new Intent(Intent.ACTION_VIEW);
//default app using url
intent.setDataAndType(Uri.parse(upload.getFileUrl()), "application/pdf");
startActivity(intent);
}
});


//getting the database reference
mDatabaseReference = FirebaseDatabase.getInstance().getReference("uploads");

//retrieving upload data from firebase database
mDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
UploadPdfModel upload = postSnapshot.getValue(UploadPdfModel.class);
uploadList.add(upload);
}

String[] uploads = new String[uploadList.size()];

for (int i = 0; i < uploads.length; i++) {
uploads[i] = uploadList.get(i).getFilename();
}

//displaying it to list
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, uploads);
listView.setAdapter(adapter);
}

@Override
public void onCancelled(DatabaseError e) {
Toast.makeText(ViewPdfActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();

}
});
}



Post a Comment

Previous Post Next Post