I have my MainActivity and inside that I have a number of fragments. I also have another activity that works as my launcher and does everything to do with the Google Drive section of my app. On start up this activity launches, connects to Drive and then launches the MainActivity. I have a button in one of my fragments that, when pushed, needs to call a method in the DriveActivity. I can't create a new instance of DriveActivity because then googleApiClient will be null. Is this possible and how would I go about doing it? I've already tried using getActivity and casting but I'm assuming that isn't working because DriveActivity isn't the fragments parent.

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    //TODO for test only remove
        directory = new Directory(SDCARD + LOCAL_STORAGE);
        byte[] zippedFile = directory.getZippedFile(SDCARD + STORAGE_LOCATION + directory.getZipFileName());

     //Here I need to somehow call DriveActivity.uploadFileToDrive(zippedFile);
        //((DriveActivity)getActivity()).uploadFileToDrive(zippedFile);
    }
});
有帮助吗?

解决方案

Right, so I'm having a bit of difficulty with the heirarchy but I think what you want to do is define a method in the fragment that the activity will be required to override to use.

This will allow you to press the button, and then fire a method whos actual implementation is inside the parent.

    public interface Callbacks {
    /**
     * Callback for when an item has been selected.
     */
    public void onItemSelected(String id);
}

example implementation:

 private static Callbacks sDummyCallbacks = new Callbacks() {

    @Override
    public void onItemSelected(String id) {
        //Button fired logic
    }
};

so in the child you'd do just call:

this.onItemSelected("ID of Class");

EDITED

In retrospect what I believe you need is an activity whos sole purpose is to upload files, not fire off other activities.

Heres an example of a 'create file' activity:Google Demo for creating a file on drive

Heres an example of the 'base upload' activity' Base Service creator

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top