【问题标题】:Save image URL from Google Drive into SQLite database将 Google Drive 中的图片 URL 保存到 SQLite 数据库中
【发布时间】:2014-03-28 10:08:46
【问题描述】:

我的应用可以将图像保存到 Google 云端硬盘(例如 https://github.com/googledrive/android-quickstart)。如何获取上传图像的 URL 并将其保存在变量中,以便在 textview 中向用户显示,并将其保存到 SQLite 数据库中?

public class Phototodrive extends Activity implements ConnectionCallbacks,OnConnectionFailedListener{

private static final String TAG = "android-drive-quickstart";
private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;

private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;  

/**
 * Create a new file and save it to Drive. 
 */ 

private void saveFileToDrive() {  
    // Start by creating a new contents, and setting a callback.
    Log.i(TAG, "Creating new contents.");
    final Bitmap image = mBitmapToSave;    
    Drive.DriveApi.newContents(mGoogleApiClient).setResultCallback(new ResultCallback<ContentsResult>() { 


        public void onResult(ContentsResult result) {
            // If the operation was not successful, we cannot do anything
            // and must
            // fail.
            if (!result.getStatus().isSuccess()) {
                Log.i(TAG, "Failed to create new contents."); 
                return; 
            }
            // Otherwise, we can write our data to the new contents.
            Log.i(TAG, "New contents created.");
            // Get an output stream for the contents.
            OutputStream outputStream = result.getContents().getOutputStream();
            // Write the bitmap data from it.
            ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
            try {
                outputStream.write(bitmapStream.toByteArray());
            } catch (IOException e1) { 
                Log.i(TAG, "Unable to write file contents.");
            }
            // Create the initial metadata - MIME type and title.
            // Note that the user will be able to change the title later.
            MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                    .setMimeType("image/jpeg").setTitle("Doc_scan.jpg").build();
            // Create an intent for the file chooser, and start it.
            IntentSender intentSender = Drive.DriveApi
                    .newCreateFileActivityBuilder() 
                    .setInitialMetadata(metadataChangeSet)
                    .setInitialContents(result.getContents())
                    .build(mGoogleApiClient);
            try {
                startIntentSenderForResult(
                        intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
            } catch (SendIntentException e) {
                Log.i(TAG, "Failed to launch file chooser.");
            }
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    if (mGoogleApiClient == null) {
        // Create the API client and bind it to an instance variable.
        // We use this instance as the callback for connection and connection
        // failures.
        // Since no account name is passed, the user is prompted to choose.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
    // Connect the client. Once connected, the camera is launched.
    mGoogleApiClient.connect();
}

@Override
protected void onPause() { 
    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
    super.onPause();
}

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    switch (requestCode) {
        case REQUEST_CODE_CAPTURE_IMAGE:
            // Called after a photo has been taken.
            if (resultCode == Activity.RESULT_OK) {
                // Store the image data as a bitmap for writing later.
                mBitmapToSave = (Bitmap) data.getExtras().get("data");
            }
            break;
        case REQUEST_CODE_CREATOR:
            // Called after a file is saved to Drive.
            if (resultCode == RESULT_OK) {
                Log.i(TAG, "Image successfully saved.");
                mBitmapToSave = null;
                // Just start the camera again for another photo.
                startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                        REQUEST_CODE_CAPTURE_IMAGE); 
            }
            break;
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    // Called whenever the API client fails to connect.
    Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
    if (!result.hasResolution()) {
        // show the localized error dialog.
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
        return;
    }
    // The failure has a resolution. Resolve it.
    // Called typically when the app is not yet authorized, and an
    // authorization
    // dialog is displayed to the user.
    try {
        result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
    } catch (SendIntentException e) {
        Log.e(TAG, "Exception while starting resolution activity", e);
    }
}

@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "API client connected.");
    if (mBitmapToSave == null) {
        // This activity has no UI of its own. Just start the camera.
        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                REQUEST_CODE_CAPTURE_IMAGE);
        return;
    }
    saveFileToDrive();
}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "GoogleApiClient connection suspended");
}   


final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>(){
    @Override
    public void onResult(DriveFileResult result) {
        if (!result.getStatus().isSuccess()){
            //showMessage("Error");
            Toast.makeText(getApplicationContext(), "Error",
                       Toast.LENGTH_LONG).show();
            return;
        }
    //  showMessage("Created a file: " + result.getDriveFile().getDriveId());
        Toast.makeText(getApplicationContext(), "Created a file: " + result.getDriveFile().getDriveId(),
                   Toast.LENGTH_LONG).show();

}
};

}

【问题讨论】:

    标签: android image url google-drive-api google-drive-android-api


    【解决方案1】:

    您可以从 DriveId.getResourceId() 获得一个名为 Resource ID 的 ID,参见 SO 21800257,它允许您形成文件的 URL,类似于

    https://docs.google.com/file/d/0B1mQU..........ZRTc5SHRlNjg/

    您的问题的其余部分应该很容易回答。它是一个字符串,所以它可以被保存,显示,......这样。但请确保您正确地形成了 URL 字符串。上面的示例只是我的应用程序的一个特定示例。关键仍然是资源 ID。

    【讨论】:

    • 我应该在哪里插入这两行 DriveIdResult 结果 = Drive.DriveApi.fetchDriveId(GAC,DriveId.getResourceId()).await(); DriveId drvID = result.getDriveId(); ?我将它复制到 onActivityResult(快速启动应用程序)中,我收到如下错误:无法从 DriveId 类型对非静态方法 getResourceId() 进行静态引用。而GAC是字符串变量?
    • GAC 是 GoogleApiClient 的一个实例。静态/非静态不匹配属于 Java 生态系统,我不知道你的代码,所以我帮不了你(我也不想)。否则,上面的答案说明了一个简单的事实,即您可以检索 RESOURCE ID(通过 getResourceId())字符串,该字符串允许您形成所需的 URL。 URL 本身有多种形式,但 RESOURCE ID 是标识 Google Drive 中文件/文件夹的变量实体。 'fetchDriveId()' 是一种反向方法。您将 RESOUCE ID 传递给它,它会为您提供 GDAA 生态系统中所需的 DriveId。
    • 我添加了代码。如何获取上传图片的 ResourceId?我必须在哪里插入什么?
    • 如果你有时间,请帮帮我,因为我ve tried in many ways, but it didnt 工作过
    【解决方案2】:

    我使用另一种方法将新照片上传到 Google 云端硬盘,因为我还需要对其进行 OCR。现在我可以轻松获取文件的ID了。

    //upload the file and OCR it 
    File file = service.files().insert(body, mediaContent).setOcr(true).execute();
    
    //save the id into a string      
    String fileid=file.getId();
    

    【讨论】:

      猜你喜欢
      • 2020-03-09
      • 2014-11-22
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 2020-02-10
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多