0

내 앱에서 이미지를 Google 드라이브 (예 : https://github.com/googledrive/android-quickstart)에 저장할 수 있습니다. 어떻게 업로드 된 이미지의 URL을 가져 와서 변수에 저장하여 텍스트 뷰에서 사용자에게 보여주고 SQLite 데이터베이스에 저장할 수 있습니까?Google 드라이브의 이미지 URL을 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

당신이 파일의 URL을 형성 할 수 있습니다 DriveId.getResourceId(), SO 21800257를 참조에서 얻을 자원 ID라는 ID,

처럼 보이는 것이 있습니다

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

질문의 나머지 부분은 대답하기 쉬워야한다. 문자열이므로 저장하고 표시 할 수 있습니다. 그러나 URL 문자열을 올바르게 구성해야합니다. 위의 예는 내 앱에만 해당됩니다. 키는 여전히 자원 ID입니다.

+0

어디 DriveIdResult 결과 = Drive.DriveApi.fetchDriveId (GAC, DriveId.getResourceId()) 기다리고()이 두 라인을 삽입한다; DriveId drvID = result.getDriveId(); ? onActivityResult (quickstart app)에 복사했는데 다음과 같은 오류가 발생합니다. DriveId 유형에서 비 정적 메서드 getResourceId()에 대한 정적 참조를 만들 수 없습니다. 그리고 GAC은 문자열 변수입니까? – Zsombor

+0

GAC는 GoogleApiClient의 인스턴스입니다. 정적/비 정적 불일치는 Java 생태계에 속하므로 코드를 알지 못해서 도울 수 없습니다 (둘 다 원하지 않습니다). 그렇지 않으면 위의 대답은 요청하는 URL을 구성 할 수있는 RESOURCE ID (getResourceId()를 통해) 문자열을 검색 할 수 있다는 간단한 사실을 설명합니다. URL 자체는 다양한 형태로 제공되지만 RESOURCE ID는 Google 드라이브의 파일/폴더를 식별하는 변수 엔티티입니다. 'fetchDriveId()'는 역 방법입니다. RESOUCE ID를 전달하면 GDAA 생태계에 필요한 DriveId가 제공됩니다. – seanpj

+0

코드를 추가했습니다. 업로드 된 이미지의 ResourceId는 어떻게 얻을 수 있습니까? 어디에서 무엇을 삽입해야합니까? – Zsombor