1

DropBox API + Android

Хотел спросить кто нибудь пользовался DropBox API. На сайте есть инструкция и пример пример не запускается, а по инструкции не совсем ясно как произвести аутентификацию!. Может кто подскажет или объяснит.

public class MainActivity extends Activity {

final String FILENAME = "file.txt";

private LinearLayout mDisplay;

private static final String TAG = "log";

private static final String APP_KEY="xxx";
private static final String APP_SECRET="yyy";

private static final AccessType ACCESS_TYPE = AccessType.APP_FOLDER;

final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";

DropboxAPI<AndroidAuthSession>mApi;

private boolean mLoggedIn;

private Button btnAuto;
private Button btnSave;
private Button btnDownload;

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "Метод onCreate");

    AndroidAuthSession session = buildSession();
    mApi = new DropboxAPI<AndroidAuthSession>(session);
    mApi.getSession().startAuthentication(MainActivity.this);

    setContentView(R.layout.activity_main);
    checkAppKeySetup();

    btnAuto = (Button) findViewById(R.id.btnAuto);

    btnAuto.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // This logs you out if you're logged in, or vice versa
            if (mLoggedIn) {
                Log.d(TAG, "if(mLoggedIn");
                logOut();
            } else {
                // Start the remote authentication
                mApi.getSession().startAuthentication(MainActivity.this);
                Log.d(TAG, "else mLoggedIn");
            }
        }
    });

btnSave = (Button) findViewById(R.id.btnSave);

btnSave.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        AccessTokenPair aTP = new AccessTokenPair(APP_KEY, APP_SECRET);

        writeFile();
        readFile();
        FileInputStream inputStream = null;
        try {
            File file = new File("/data/data/com.example.db_test2/files/file.txt");
            Log.d(TAG, "File file...");
            if(!file.exists()){
                file.createNewFile();
            }

            inputStream = new FileInputStream(file);
            Log.d(TAG, "file.lenght "+file.length());
            Entry newEntry = mApi.putFile("/Task for you/file.txt", inputStream,
                    file.length(), null, null);
            Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
        } catch (DropboxUnlinkedException e) {
            Log.d(TAG,inputStream.toString());

            // User has unlinked, ask them to link again here.
            Log.e("DbExampleLog", "User has unlinked.");
        } catch (DropboxException e) {
            Log.e("DbExampleLog", "Something went wrong while uploading.");
        } catch (FileNotFoundException e) {
            Log.e("DbExampleLog", "File not found.");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {}
            }
        }
        }

});

btnDownload = (Button) findViewById(R.id.btnDownload);

btnDownload.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        readFile();

        FileOutputStream outputStream = null;
        try {
            File file = new File(FILENAME);

            Log.d(TAG, file.toString());
            outputStream = new FileOutputStream(file);
            Log.d(TAG, outputStream.toString());
            DropboxFileInfo info = mApi.getFile(FILENAME, null, outputStream, null);
            Log.i("DbExampleLog", "The file's rev is: " );

            // /path/to/new/file.txt now has stuff in it.
        } catch (DropboxException e) {
            Log.e("DbExampleLog", "Something went wrong while downloading.");
        } catch (FileNotFoundException e) {
            Log.e("DbExampleLog", "File not found.");
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {}
            }
        }

    }
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

private AndroidAuthSession buildSession() {
    AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
    AndroidAuthSession session;

    String[] stored = getKeys();
    if (stored != null) {
        AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);
        session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken);

    } else {
        session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);

    }

    return session;
}

private String[] getKeys() {
    SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
    String key = prefs.getString(ACCESS_KEY_NAME, null);
    String secret = prefs.getString(ACCESS_SECRET_NAME, null);
    if (key != null && secret != null) {
        String[] ret = new String[2];
        ret[0] = key;
        ret[1] = secret;
        return ret;
    } else {
        return null;
    }
}
private void checkAppKeySetup() {
    // Check to make sure that we have a valid app key
    if (APP_KEY.startsWith("CHANGE") ||
            APP_SECRET.startsWith("CHANGE")) {
        showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it.");
        finish();
        return;
    }}

    private void showToast(String msg) {
        Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
        error.show();
    }

    private void logOut() {
        // Remove credentials from the session
        mApi.getSession().unlink();

        // Clear our stored keys
        clearKeys();
        // Change UI state to display logged out version
        setLoggedIn(false);
    }
    private void clearKeys() {
        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
        Editor edit = prefs.edit();
        edit.clear();
        edit.commit();
    }

    private void setLoggedIn(boolean loggedIn) {
        mLoggedIn = loggedIn;
        if (loggedIn) {
            btnAuto.setText("Unlink from Dropbox");
            mDisplay.setVisibility(View.VISIBLE);
        } else {
            btnAuto.setText("Link with Dropbox");
            mDisplay.setVisibility(View.GONE);
        }
    }

    void writeFile() {
        try {
          // отрываем поток для записи
          BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
              openFileOutput(FILENAME, MODE_WORLD_READABLE)));
          // пишем данные
          bw.write("Содержимое файла");
          bw.write("Check it");
          // закрываем поток
          bw.close();
          Log.d(TAG, "Файл записан");
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

    void readFile() {
        try {
          // открываем поток для чтения
          BufferedReader br = new BufferedReader(new InputStreamReader(
              openFileInput(FILENAME)));
          String str = "";
          // читаем содержимое
          while ((str = br.readLine()) != null) {
            Log.d(TAG, str);
          }
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

}

1 ответ 1

2

Решение есть! Я забыл добавить onResume(){} И реализовать получения токена, ужас как я сразу не понял этого..

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.