Unable to Download a file(pdf) stores on Firebase

0

I am not able to download any file from firebase. The problem is that I have uploaded certain files on firebase which are segregated by categories. The categories are basically folders. Now I am facing problem downloading them as I am new to firebase.

I have used a card view with Recycler view to display all the files present on the firebase. The files are displayed in another activity which is called from a fragment. This fragment has spinners which are used to display certain category files. I have done display the files using values from the model that I made for firebase. Now the firebase shows the url as "com.google.android.gms.tasks.zzu@81ec86f". Now I don't know how should I download the file from this url. I am storing all the categories and url using a model class to firebase database.

This is my adapter code which displays card view

public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.ViewHolder> {

private Context context;
private ArrayList<Upload> noteslist;
private Downloader downloader;
public  static  final String TAG = "NotesAdapter";

public NotesAdapter(Context context, ArrayList<Upload> noteslist) {
    this.context = context;
    this.noteslist = noteslist;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_notes,parent,false);
    return new NotesAdapter.ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    final Upload notes = noteslist.get(position);
    holder.title.setText(notes.getName());
    holder.author.setText(notes.getAuthor());
    holder.noOfDown.setText("No. of Downloads = "+String.valueOf(notes.getDownload()));

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(context instanceof DownloadNotes) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(notes.getUrl()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);      <-------Error
            }
        }
    });
}

@Override
public int getItemCount() {
    return noteslist.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {

    TextView title,author,noOfDown;
    View view ;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        title = itemView.findViewById(R.id.title);
        author = itemView.findViewById(R.id.authorname);
        noOfDown = itemView.findViewById(R.id.download);
        this.view=itemView;
    }
}

Another problem I am facing here is that when I run this it shows up this error

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.collegeconnect, PID: 32314
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=com.google.android.gms.tasks.zzu@ab761b0 flg=0x10000000 }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2007)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
    at android.app.Activity.startActivityForResult(Activity.java:4586)
    at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:675)
    at android.app.Activity.startActivityForResult(Activity.java:4544)
    at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:662)
    at android.app.Activity.startActivity(Activity.java:4905)
    at android.app.Activity.startActivity(Activity.java:4873)
    at com.example.collegeconnect.NotesAdapter$1.onClick(NotesAdapter.java:72)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

this is my upload Activity

public class UploadNotes extends AppCompatActivity {

final static int PICK_PDF_CODE = 2342;

//these are the views
TextView textViewStatus;
EditText editTextFilename,author;
ProgressBar progressBar;
Button upload;
Spinner semester, branch, course, unit;

//the firebase objects for storage and database
StorageReference mStorageReference;
DatabaseReference mDatabaseReference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_notes);


    //getting firebase objects
    mStorageReference = FirebaseStorage.getInstance().getReference();
    mDatabaseReference = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS);

    //getting the views
    textViewStatus = findViewById(R.id.textViewStatus);
    semester = findViewById(R.id.spinnerSem);
    branch = findViewById(R.id.spinnerBranch);
    course = findViewById(R.id.spinnerCourse);
    unit = findViewById(R.id.spinnerUnit);
    editTextFilename = findViewById(R.id.FileName);
    progressBar =  findViewById(R.id.progressbar);
    upload = findViewById(R.id.viewnotes);
    author=findViewById(R.id.author);
    upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPDF();
            }
        });

}

//this function will get the pdf from the storage
private void getPDF() {
    if (ContextCompat.checkSelfPermission(UploadNotes.this,Manifest.permission.READ_EXTERNAL_STORAGE )
            == PackageManager.PERMISSION_DENIED) {

        // Requesting the permission
        ActivityCompat.requestPermissions(UploadNotes.this,
                new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                100);
    }
    else {

        //creating an intent for file chooser
        Intent intent = new Intent();
        intent.setType("application/pdf");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select PDF"), PICK_PDF_CODE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 100  && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        getPDF();

        } else {
            Toast.makeText(UploadNotes.this,
                    "Storage Permission Denied",
                    Toast.LENGTH_SHORT)
                    .show();
        }
    }
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //when the user choses the file
    if (requestCode == PICK_PDF_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
        //if a file is selected
        if (data.getData() != null) {
            editTextFilename.setText(data.getData().getPath());
            //uploading the file
            findViewById(R.id.button6).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    uploadFile(data.getData());
                }
            });

        }else{
            Toast.makeText(this, "No file chosen", Toast.LENGTH_SHORT).show();
        }
    }
}


//this method is uploading the file
private void uploadFile(Uri data) {
    progressBar.setVisibility(View.VISIBLE);
    StorageReference sRef = mStorageReference.child(Constants.STORAGE_PATH_UPLOADS + course.getSelectedItem().toString() + "/" + branch.getSelectedItem().toString()+ "/" + semester.getSelectedItem().toString() + "/" + unit.getSelectedItem().toString() + "/" + editTextFilename.getText().toString().toLowerCase());
    sRef.putFile(data)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @SuppressWarnings("VisibleForTests")
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    progressBar.setVisibility(View.GONE);
                    textViewStatus.setText("File Uploaded Successfully");

                    Upload upload = new Upload(editTextFilename.getText().toString(),
                                                    course.getSelectedItem().toString(),
                                                      semester.getSelectedItem().toString(),
                                                        branch.getSelectedItem().toString(),
                                                          unit.getSelectedItem().toString(),
                                                            author.getText().toString(),0, taskSnapshot.getStorage().getDownloadUrl().toString());
                    mDatabaseReference.child(mDatabaseReference.push().getKey()).setValue(upload);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                }
            })
            .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                @SuppressWarnings("VisibleForTests")
                @Override
                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                    double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                    textViewStatus.setText((int) progress + "% Uploading...");
                }
            });

}

This is my download activity where I have used the adapter

public class DownloadNotes extends AppCompatActivity {

public static final String EXTRA_COURSE = "course";
public static final String EXTRA_BRANCH = "branch";
public static final String EXTRA_SEMESTER = "semester";
public static final String EXTRA_UNIT = "unit";
public static ArrayList<Upload> uploadList;
static DatabaseReference mDatabaseReference;
static StorageReference storageReference;
RecyclerView recyclerView;
NotesAdapter notesAdapter;
String receivedCourse ;
String receivedBranch;
String receivedSemester;
String receivedUnit;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_download_notes);
//passing the values selected in spinner to access the certain files
    Intent intent = getIntent();
    receivedCourse = intent.getStringExtra(EXTRA_COURSE);
    receivedBranch = intent.getStringExtra(EXTRA_BRANCH);
    receivedSemester = intent.getStringExtra(EXTRA_SEMESTER);
    receivedUnit =  intent.getStringExtra(EXTRA_UNIT);

    Toast.makeText(this, receivedSemester, Toast.LENGTH_SHORT).show();

    uploadList = new ArrayList<>();
    mDatabaseReference = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS);
    mDatabaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                Upload upload = postSnapshot.getValue(Upload.class);
                if (upload.getBranch().equals(receivedBranch)) {
                    uploadList.add(upload);
                    Toast.makeText(DownloadNotes.this, upload.getName(), Toast.LENGTH_SHORT).show();
                }
            }

            recyclerView = findViewById(R.id.downloadRecycler);
            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new LinearLayoutManager(DownloadNotes.this));
            notesAdapter = new NotesAdapter(DownloadNotes.this, uploadList);
            recyclerView.setAdapter(notesAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

I don't know if I am doing this the wrong way or not as I am quite new at android development. I basically wish to download item on according to the card clicked from the recycler view. How should do that?

any help is welcomed

android
firebase
firebase-storage
asked on Stack Overflow Mar 21, 2020 by Saksham Pruthi

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0