Document Share App Tutorial in Android
Output Screen
Login Screen
Student Home Page
Student Download Page
Teacher Home Page
Teacher Upload Document Page
Delete Document
LoginActivity.java
package com.example.documentshareapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.example.documentshareapp.model.Student;
import com.example.documentshareapp.model.Teacher;
import com.example.documentshareapp.utility.Util;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.auth.SignInMethodQueryResult;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.Iterator;
public class LoginActivity extends AppCompatActivity {
private RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
radioGroup = findViewById(R.id.rg);
com.google.android.gms.common.SignInButton signInButton =
findViewById(R.id.sign_button);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = ((SingleTask) getApplication()).
getGoogleSignInClient().getSignInIntent();
startActivityForResult(signInIntent, 1001);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {
Task<GoogleSignInAccount> task = GoogleSignIn.
getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account.getIdToken());
} catch (ApiException e) {
Util.showError(LoginActivity.this, e.toString());
}
}
}
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
((SingleTask) getApplication()).getFirebaseAuth().
signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
newUser();
}
}
});
}
private void newUser() {
RadioButton radioButton = findViewById(radioGroup.getCheckedRadioButtonId());
String role = radioButton.getText().toString();
if (role.equalsIgnoreCase("student")) {
Student student = new Student();
student.setRole(role);
student.setUid(((SingleTask) getApplication()).getFirebaseAuth().getUid());
Log.e("error", student.getUid());
((SingleTask) getApplication()).getDatabaseReference().
child(student.getUid()).setValue(student).
addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent in = new Intent(LoginActivity.this,
StudentHomePage.class);
startActivity(in);
finish();
}
}
});
} else {
Teacher teacher = new Teacher();
teacher.setRole(role);
teacher.setUid(((SingleTask) getApplication()).getFirebaseAuth().getUid());
Log.e("error", teacher.getUid());
((SingleTask) getApplication()).getDatabaseReference().
child(teacher.getUid()).setValue(teacher).
addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent in = new Intent(LoginActivity.this,
TeacherHomePage.class);
startActivity(in);
finish();
}
}
});
}
}
}
SingleTask.java
package com.example.documentshareapp;
import android.app.Application;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
public class SingleTask extends Application {
private FirebaseAuth mAuth;
private GoogleSignInClient mGoogleSignInClient;
private FirebaseDatabase database;
private StorageReference mStorageRef;
@Override
public void onCreate() {
super.onCreate();
mAuth = FirebaseAuth.getInstance();
GoogleSignInOptions gso = new
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
database = FirebaseDatabase.getInstance();
mStorageRef = FirebaseStorage.getInstance().getReference();
}
public FirebaseAuth getFirebaseAuth() {
return mAuth;
}
public GoogleSignInClient getGoogleSignInClient() {
return mGoogleSignInClient;
}
public DatabaseReference getDatabaseReference() {
return database.getReference("user");
}
public DatabaseReference getDatabaseUploadReference() {
return database.getReference("download");
}
public StorageReference getStorageReference() {
return mStorageRef;
}
}
SplashActivity.java
package com.example.documentshareapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.documentshareapp.model.Student;
import com.example.documentshareapp.model.Teacher;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import java.util.Iterator;
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
}
@Override
protected void onStart() {
super.onStart();
final FirebaseUser user = ((SingleTask) getApplication()).
getFirebaseAuth().getCurrentUser();
if (user != null) {
((SingleTask) getApplication()).getDatabaseReference().
addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Toast.makeText(SplashActivity.this,
dataSnapshot.getValue() + "", Toast.LENGTH_SHORT).show();
Iterator<DataSnapshot> dd = dataSnapshot.getChildren().iterator();
while (dd.hasNext()) {
//Log.e("error", dd.next() + "");
DataSnapshot ds = dd.next();
if (ds.getKey().equals(user.getUid())) {
Log.e("error", "success" + "");
Log.e("error", user.getUid() + "\t" + ds.getKey());
Log.e("error", ds.getValue().toString());
String role = ds.child("role").getValue(String.class);
Log.e("error", role);
if (role.equalsIgnoreCase("Student")) {
Student student = dataSnapshot.getValue(Student.class);
Log.e("error", "student");
Intent in = new Intent(
SplashActivity.this, StudentHomePage.class);
startActivity(in);
finish();
} else {
Teacher teacher = dataSnapshot.getValue(Teacher.class);
Log.e("error", "teacher");
Intent in = new Intent(
SplashActivity.this, TeacherHomePage.class);
startActivity(in);
finish();
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
public void goToLoginPage(View view) {
startActivity(new Intent(this, LoginActivity.class));
finish();
}
}UploadFragment.java
package com.example.documentshareapp.teacher.upload;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.text.TextUtilsCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.documentshareapp.R;
import com.example.documentshareapp.SingleTask;
import com.example.documentshareapp.adapter.UploadAdapter;
import com.example.documentshareapp.model.Upload;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class UploadFragment extends Fragment {
private ProgressBar progressBar;
private RecyclerView recyclerView;
private List<Upload> listupUploads;
private UploadAdapter uploadAdapter;
private LinearLayout noitemfound;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_upload, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = view.findViewById(R.id.myrecyclerview);
noitemfound = view.findViewById(R.id.noitemfound);
listupUploads = new ArrayList<>();
FloatingActionButton fab = view.findViewById(R.id.myfab);
progressBar = view.findViewById(R.id.progress);
uploadAdapter = new UploadAdapter(listupUploads);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(uploadAdapter);
getAllUploadedDataFromFirebase();
//new MyTask().execute();
//click on fab show an custom alert
//where we can upload document
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
uploadAlertDialog();
}
});
//we need to show all document in recycler view
//and here also teacher can remove upload documents
uploadAdapter.setDeleteListener(new UploadAdapter.DeleteListener() {
@Override
public void deleteItem(View view, int position) {
Toast.makeText(getActivity(), "Delete", Toast.LENGTH_SHORT).show();
Upload upload = listupUploads.get(position);
deleteFromFirebase(upload);
}
});
}
private void deleteFromFirebase(final Upload upload1) {
progressBar.setVisibility(View.VISIBLE);
((SingleTask) getActivity().getApplication()).
getDatabaseUploadReference().
addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//Log.e("error deep", dataSnapshot.getValue().toString());
Iterator<DataSnapshot> ds = dataSnapshot.getChildren().iterator();
while (ds.hasNext()) {
DataSnapshot dd = ds.next();
Upload upload2 = dd.getValue(Upload.class);
if (upload1.getName().equals(upload2.getName())) {
Log.e("error", "delete from here" +
upload1.getName() + "\t" + upload1.getPosteddate());
Log.e("error", dd.getKey());
dd.getRef().removeValue();
Log.e("error", "remove");
//file remove from storage
deleteFromStorage(upload1);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
progressBar.setVisibility(View.GONE);
}
});
}
private void deleteFromStorage(Upload upload) {
((SingleTask) getActivity().getApplication()).
getStorageReference().child("documents/" + upload.getName()).
delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getActivity(),"Successfully Deleted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Deleted Failed",Toast.LENGTH_SHORT).show();
}
uploadAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
});
}
private void getAllUploadedDataFromFirebase() {
progressBar.setVisibility(View.VISIBLE);
((SingleTask) getActivity().getApplication()).
getDatabaseUploadReference().
addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> it = dataSnapshot.getChildren().iterator();
long count = dataSnapshot.getChildrenCount();
if (count > 0) {
noitemfound.setVisibility(View.GONE);
while (it.hasNext()) {
listupUploads.add(it.next().getValue(Upload.class));
Log.e("error", listupUploads.get(0).getName() + "");
}
uploadAdapter.notifyDataSetChanged();
} else {
noitemfound.setVisibility(View.VISIBLE);
}
progressBar.setVisibility(View.GONE);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e("error", databaseError.toString());
}
});
}
private TextView tfile;
private void uploadAlertDialog() {
AlertDialog.Builder a = new AlertDialog.Builder(getActivity());
final AlertDialog aa = a.create();
View view = getActivity().getLayoutInflater().
inflate(R.layout.upload_alert, null, false);
aa.setView(view);
aa.show();
tfile = view.findViewById(R.id.filename);
ImageView addfile = view.findViewById(R.id.browse);
final Button uploadbutton = view.findViewById(R.id.uploadbutton);
uploadbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TextUtils.isEmpty(tfile.getText().toString())
|| !tfile.getText().toString().
equalsIgnoreCase("browse file")) {
aa.dismiss();
uploadDocument(localuri);
} else {
Toast.makeText(getActivity(),
"Please select a document", Toast.LENGTH_SHORT).show();
}
}
});
addfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent,
"Select Document (pdf/docx/doc)"), 1001);
}
});
}
private Uri localuri;
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {
if (resultCode == Activity.RESULT_OK) {
localuri = data.getData();
Log.e("error", localuri + "");
tfile.setText(localuri.toString());
}
}
}
private String filename = "";
private void uploadDocument(Uri uri) {
progressBar.setVisibility(View.VISIBLE);
if (uri.toString().contains(".pdf")) {
filename = System.currentTimeMillis() + ".pdf";
} else if (uri.toString().contains(".docx")) {
filename = System.currentTimeMillis() + ".docx";
} else if (uri.toString().contains(".doc")) {
filename = System.currentTimeMillis() + ".doc";
} else {
Toast.makeText(getActivity(), "Please select only Pdf/Doc/Docx file",
Toast.LENGTH_SHORT).show();
return;
}
((SingleTask) getActivity().getApplication()).
getStorageReference().child("documents/" + filename).
putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if (taskSnapshot.getTask().isSuccessful()) {
try {
//we need to store file name only
//in upload model class
Upload upload = new Upload();
upload.setName(filename);
upload.setPosteddate(new Date(System.currentTimeMillis()).toString());
((SingleTask) getActivity().getApplication()).
getDatabaseUploadReference().
push().
setValue(upload).
addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
Toast.makeText(getActivity(),
"Successfully Share",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),task.getException().toString(),
Toast.LENGTH_SHORT).show();
}
}
});
} catch (Exception e) {
Log.e("error", e.toString());
}
}
}
});
}
}DownloadFragment.java
package com.example.documentshareapp.student.dashboard;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.os.EnvironmentCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.documentshareapp.R;
import com.example.documentshareapp.SingleTask;
import com.example.documentshareapp.adapter.DownloadAdapter;
import com.example.documentshareapp.model.Upload;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FileDownloadTask;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static android.os.Environment.getExternalStorageDirectory;
public class DownloadFragment extends Fragment {
private RecyclerView recyclerView;
private List<Upload> uploadList;
private ProgressBar progressBar;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_download, container, false);
return root;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
progressBar = view.findViewById(R.id.myprogress);
uploadList = new ArrayList<>();
recyclerView = view.findViewById(R.id.listfile);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
final DownloadAdapter downloadAdapter = new DownloadAdapter(uploadList);
recyclerView.setAdapter(downloadAdapter);
downloadAdapter.setDownloadListener(new DownloadAdapter.DownloadListener() {
@Override
public void onDownload(View view, int position) {
Upload upload = uploadList.get(position);
//destination where your file is downloaded
try {
File root = Environment.getExternalStorageDirectory();
File folder = new File(root, "mydocuments");
folder.mkdir();
File destination = new File(folder, upload.getName());
destination.createNewFile();
//get actual file from storage
((SingleTask) getActivity().getApplication()).
getStorageReference().child("documents/" + upload.getName()).
getFile(destination).
addOnCompleteListener(new OnCompleteListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<FileDownloadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Toast.makeText(getActivity(),
"Successfully Download",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),
"Download Failed",
Toast.LENGTH_SHORT).show();
}
}
});
} catch (Exception e) {
Log.e("error", e.toString());
}
}
});
((SingleTask) getActivity().getApplication()).
getDatabaseUploadReference().
addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
progressBar.setVisibility(View.VISIBLE);
Iterator<DataSnapshot> dd = dataSnapshot.getChildren().iterator();
while (dd.hasNext()) {
uploadList.add(dd.next().getValue(Upload.class));
}
progressBar.setVisibility(View.GONE);
downloadAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
These are the main Module of this project
No comments:
Post a Comment