0

我的應用可以將圖片保存到Google雲端硬盤(例如https://github.com/googledrive/android-quickstart)。如何獲取上傳圖像的URL並將其保存在變量中,以便在textview中將其顯示給用戶,並將其保存到SQLite數據庫中?將Google雲端硬盤中的圖片網址保存到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(); 

} 
}; 

}

回答

0

我用另一種方法將新照片上傳到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(); 
1

有一個叫資源ID從DriveId.getResourceId(),看到SO 21800257,使您可以形成文件的URL獲得一個ID,東西看起來像

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

你的問題的其餘部分應該很容易回答的問題。這是一個字符串所以它可以被保存,顯示,...等等。但請確保您正確地形成URL字符串。上面的例子只是一個特定於我的應用程序。密鑰仍然是資源ID。

+0

我應該在哪裏插入這些2行 DriveIdResult結果= Drive.DriveApi.fetchDriveId(GAC,DriveId.getResourceId())等待(); DriveId drvID = result.getDriveId(); ? 我將它複製到o​​nActivityResult(快速啓動應用程序)中,並且出現如下錯誤:無法對類型爲DriveId的非靜態方法getResourceId()進行靜態引用。 而GAC是一個字符串變量? – Zsombor

+0

GAC是GoogleApiClient的一個實例。靜態/非靜態不匹配屬於Java生態系統,我不知道你的代碼,所以我不能幫你(我都不想)。否則,上面的答案指出了一個簡單的事實,即您可以檢索RESOURCE ID(通過getResourceId())字符串,該字符串允許您形成您要求的URL。 URL本身具有多種風格,但RESOURCE ID是標識Google Drive中文件/文件夾的變量實體。 'fetchDriveId()'是一種相反的方法。您將RESOUCE ID傳遞給它,它將爲您提供您在GDAA生態系統中所需的DriveId。 – seanpj

+0

我添加了代碼。我怎樣才能獲得上傳圖片的ResourceId?我需要插入的地方和內容? – Zsombor

相關問題