如何在Android活动之间传递会话对象

时间:2015-06-03 22:40:30

标签: android dropbox dropbox-api

我正在开发一个项目,该项目使用Dropbox Android apis来实现上传和下载功能。 第一步我使用了UploadButton触发器fileselectorActivity这个函数我使用Intent方法实现了跳转到下一个活动,但是intent方法无法将dropbox会话带到其他活动(可能关于dropbox会话类型不是String)。 afer执行了文件选择器Activity,它将选择一个特定的文件路径上传到dropbox,

我想知道如何在选择目标文件后将dropbox会话传递给fileselectorActivity将发送到uploadActivity。 使用Intent方法和bundle但没有用。 这是我的代码。

MainActivity代码

public class MainActivity extends Activity implements OnClickListener {
    private DropboxAPI<AndroidAuthSession> dropbox;
    private final static String FILE_DIR = "/";
    private final static String DROPBOX_NAME = "dropbox_prefs";
    private final static String ACCESS_KEY = "***************";
    private final static String ACCESS_SECRET = "************";
    private String path = "/";
    private boolean isLoggedIn;
    private Button logIn;
    private Button uploadFile;
    private Button encryption;
    private Button decryption;
    private Button listFiles;

    private ArrayAdapter<String> listAdapter;
    private ListView itemlist;
    ArrayList<String> items = new ArrayList<String>();


    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        logIn = (Button) findViewById(R.id.dropbox_login);
        logIn.setOnClickListener(this);
        uploadFile = (Button) findViewById(R.id.UploadButton);
        uploadFile.setOnClickListener(this);
        decryption=(Button) findViewById(R.id.decryptionButton);
        decryption.setOnClickListener(this);
        encryption=(Button) findViewById(R.id.encryptionButton);
        encryption.setOnClickListener(this);
        listFiles = (Button) findViewById(R.id.list_files);
        listFiles.setOnClickListener(this);
        // get itemlist
        itemlist = (ListView) findViewById(R.id.itemList);

        // encryption();
        loggedIn(false);
        AndroidAuthSession session;
        AppKeyPair pair = new AppKeyPair(ACCESS_KEY, ACCESS_SECRET);

        SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
        String key = prefs.getString(ACCESS_KEY, null);
        String secret = prefs.getString(ACCESS_SECRET, null);

        if (key != null && secret != null) {
            AccessTokenPair token = new AccessTokenPair(key, secret);
            session = new AndroidAuthSession(pair, AccessType.DROPBOX, token);
        } else {
            session = new AndroidAuthSession(pair, AccessType.DROPBOX);
        }
        dropbox = new DropboxAPI<AndroidAuthSession>(session);

    }

    @Override
    protected void onResume() {
        super.onResume();

        AndroidAuthSession session = dropbox.getSession();
        if (session.authenticationSuccessful()) {
            try {
                session.finishAuthentication();
                TokenPair tokens = session.getAccessTokenPair();
                SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
                Editor editor = prefs.edit();
                editor.putString(ACCESS_KEY, tokens.key);
                editor.putString(ACCESS_SECRET, tokens.secret);
                editor.commit();
                loggedIn(true);
            } catch (IllegalStateException e) {
                Toast.makeText(this, "Error during Dropbox authentication",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void loggedIn(boolean isLogged) {
        isLoggedIn = isLogged;
        uploadFile.setEnabled(isLogged);
        listFiles.setEnabled(isLogged);
        decryption.setEnabled(isLogged);
        encryption.setEnabled(isLogged);
        logIn.setText(isLogged ? "Log out" : "Log in");
    }

    private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            items.clear();
            ArrayList<String> result = msg.getData().getStringArrayList("data");
            for (String fileName : result) {
                items.add(fileName);
            }
            handleitems();
        }

    };

    public void handleitems() {
        listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, items);
        itemlist.setAdapter(listAdapter);
        itemlist.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                String item = ((TextView) view).getText().toString();
                Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
                DownloadFileFromDropbox download2=new DownloadFileFromDropbox(parent.getContext(), dropbox, path,item);
                download2.execute();
            }

        });
    }



    @SuppressWarnings("deprecation")
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.dropbox_login:
            if (isLoggedIn) {
                dropbox.getSession().unlink();
                loggedIn(false);
            } else {
                dropbox.getSession().startAuthentication(MainActivity.this);
            }
            break;
        case R.id.list_files:
            ListDropboxFiles list = new ListDropboxFiles(dropbox, FILE_DIR,handler);
            list.execute();
            break;
        case R.id.UploadButton:
            Intent intent = new Intent(MainActivity.this, FileChooser.class);
            startActivity(intent);


        //  UploadFileToDropbox uploader=new UploadFileToDropbox(this, dropbox, path);
        //  uploader.execute();
            break;
        default:
            break;
        }
    }


}

Fileselector代码。

package filechooser;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.exception.DropboxUnlinkedException;
import com.example.ik2000dropbox.MainActivity;
import com.example.ik2000dropbox.R;
import com.example.ik2000dropbox.UploadFileToDropbox;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class FileChooser extends ListActivity {

    private File currentDir;
    FileArrayAdapter adapter;



    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentDir = new File("/sdcard/download");
        fill(currentDir);
    }

    private void fill(File f) {
        File[] dirs = f.listFiles();
        this.setTitle("Current Dir: " + f.getName());
        List<Option> dir = new ArrayList<Option>();
        List<Option> fls = new ArrayList<Option>();
        try {
            for (File ff : dirs) {
                if (ff.isDirectory())
                    dir.add(new Option(ff.getName(), "Folder", ff
                            .getAbsolutePath()));
                else {
                    fls.add(new Option(ff.getName(), "File Size: "
                            + ff.length(), ff.getAbsolutePath()));
                }
            }
        } catch (Exception e) {

        }
        Collections.sort(dir);
        Collections.sort(fls);
        dir.addAll(fls);
        if (!f.getName().equalsIgnoreCase("sdcard"))
            dir.add(0, new Option("..", "Parent Directory", f.getParent()));
        adapter = new FileArrayAdapter(FileChooser.this, R.layout.file_view,dir);
        this.setListAdapter(adapter);
    }

    protected void onListItemClick(ListView l, View v, int position, long id) {

        super.onListItemClick(l, v, position, id);
        Option o = adapter.getItem(position);
        if (o.getData().equalsIgnoreCase("folder")
                || o.getData().equalsIgnoreCase("parent directory")) {
            currentDir = new File(o.getPath());
            fill(currentDir);
        } else {

            onFileClick(o);
        }
    }

    private void onFileClick(Option o) {

        Toast.makeText(this, "File Clicked: " + o.getName(), Toast.LENGTH_SHORT).show();

    }

}

我的上传活动

public class UploadFileToDropbox  extends AsyncTask<Void, Void, Boolean> {

    private DropboxAPI<?> dropbox;
    private String path;
    private Context context;

    public UploadFileToDropbox(Context context, DropboxAPI<?> dropbox,
            String path) {
        this.context = context.getApplicationContext();
        this.dropbox = dropbox;
        this.path = path;
    }



    @Override
    protected Boolean doInBackground(Void... params) {

        try {
        File file = new File("/sdcard/download/lecture.pdf.p7m");
        FileInputStream inputStream =new FileInputStream(file);
        dropbox.putFile(path + "lecture.pdf.p7m",inputStream,
                file.length(), null, null);
        return true;    

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e) {
                e.printStackTrace();
        } catch (DropboxException e) {
                e.printStackTrace();

        }

        return false;
    }





    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            Toast.makeText(context, "File Uploaded Sucesfully!",
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, "Failed to upload file", Toast.LENGTH_LONG).show();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

创建应用程序对象

public function moveTaskIdToListId($oldid,$newid){

$this->db->beginTransaction();
$tmpid=$this->db->query('SELECT max(`id`) FROM `table`');
++$tmpid;
$this->db->query('UPDATE `table` SET `id` = '.$this->db->quote($tmpid).' WHERE `id` = '.$this->db->quote($newid));
$this->db->query('UPDATE `table` SET `id` = '.$this->db->quote($newid).' WHERE `id` = '.$this->db->quote($oldid));
$this->db->query('UPDATE `table` SET `id` = '.$this->db->quote($oldid).' WHERE `id` = '.$this->db->quote($tmpid));
$this->db->commit();
//todo: error handling and handle case when newid does not exist yet..(if that ever happens)
}

将其添加到清单

 public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks{

            private final static String ACCESS_KEY = "***************";
            private final static String ACCESS_SECRET = "************";

            private  static MyApplication singleton;
            private DropboxAPI<AndroidAuthSession> dropbox;

            private final static String DROPBOX_NAME = "dropbox_prefs";

            public DropboxAPI<AndroidAuthSession> getDropbox() {
                return dropbox;
            }

            public void setDropbox(DropboxAPI<AndroidAuthSession> dropbox) {
                this.dropbox = dropbox;
            }



            @Override
            public void onCreate() {
                super.onCreate();
                singleton = this;
                SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
                String key = prefs.getString(ACCESS_KEY, null);
                String secret = prefs.getString(ACCESS_SECRET, null);

                if (key != null && secret != null) {
                    AccessTokenPair token = new AccessTokenPair(key, secret);
                    session = new AndroidAuthSession(pair, AccessType.DROPBOX, token);
                } else {
                    session = new AndroidAuthSession(pair, AccessType.DROPBOX);
                }
                dropbox = new DropboxAPI<AndroidAuthSession>(session);
            }}

在活动中使用

  <application
            android:name=".MyApplication"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >

答案 1 :(得分:0)

Create Application Object

 public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks{

            private final static String ACCESS_KEY = "***************";
            private final static String ACCESS_SECRET = "************";

            private  static MyApplication singleton;
            private DropboxAPI<AndroidAuthSession> dropbox;

            private final static String DROPBOX_NAME = "dropbox_prefs";

            public DropboxAPI<AndroidAuthSession> getDropbox() {
                return dropbox;
            }

            public void setDropbox(DropboxAPI<AndroidAuthSession> dropbox) {
                this.dropbox = dropbox;
            }



            @Override
            public void onCreate() {
                super.onCreate();
                singleton = this;
                SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
                String key = prefs.getString(ACCESS_KEY, null);
                String secret = prefs.getString(ACCESS_SECRET, null);

                if (key != null && secret != null) {
                    AccessTokenPair token = new AccessTokenPair(key, secret);
                    session = new AndroidAuthSession(pair, AccessType.DROPBOX, token);
                } else {
                    session = new AndroidAuthSession(pair, AccessType.DROPBOX);
                }
                dropbox = new DropboxAPI<AndroidAuthSession>(session);
            }}
Add it to manifest

  <application
            android:name=".MyApplication"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
Use in activity

   MyApplication.getInstance().getDropbox()