Cómo perder contenido de archivos en Google Drive
Este es un fenómeno muy extraño. Mi aplicación utiliza el SDK de Google Drive para Android para almacenar dos archivos de datos para cada usuario. Estos archivos se encuentran en la carpeta de la aplicación. Para obtener una conexión con el servicio de Google, utilizo:
PlusOptions plusOptions = new Plus.PlusOptions.Builder() .addActivityTypes("http://schemas.google.com/AddActivity").build(); mGoogleApi = new GoogleApiClient.Builder(this).addApi(Plus.API, plusOptions).addScope(Plus.SCOPE_PLUS_LOGIN) .addScope(Plus.SCOPE_PLUS_PROFILE).addApi(Drive.API).addScope(Drive.SCOPE_FILE) .addScope(Drive.SCOPE_APPFOLDER).addConnectionCallbacks(this).addOnConnectionFailedListener(this) .build();
Puedo crear estos archivos y escribirlos. Pero de vez en cuando, los dos archivos desaparecen, y su contenido se pierde. La secuencia logcat contiene mensajes como estos:
- UserRecoverableAuthException: NeedPermission
- Uso de Google Drive para realizar copias de seguridad y restaurar bases de datos SQLite
- ¿Cómo puedo cambiar cuentas en la NUEVA API de Google Drive para Android?
- ¿Cómo configurar proguard para la aplicación de Android con Google Drive SDK?
- No hay intención de UserRecoverableAuthIOException con Drive SDK para Android
05-16 10:15:18.316: W/GLSUser(829): [apk][apk] Permission for debut.kholle to access oauth2:https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me will be managed remotely. 05-16 10:15:18.416: I/qtaguid(14877): Failed write_ctrl(u 56) res=-1 errno=22 05-16 10:15:18.416: I/qtaguid(14877): Untagging socket 56 failed errno=-22 05-16 10:15:18.416: W/NetworkManagementSocketTagger(14877): untagSocket(56) failed with errno -22 05-16 10:15:18.416: I/imp(14877): I/O exception (org.apache.http.NoHttpResponseException) caught when processing request: The target server failed to respond 05-16 10:15:18.416: I/imp(14877): Retrying request 05-16 10:15:18.436: W/GLSUser(829): [apk][apk] Permission for debut.kholle to access oauth2:https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me will be managed remotely. 05-16 10:15:18.516: W/GLSUser(829): GoogleAccountDataService.getToken() 05-16 10:15:18.546: I/qtaguid(21108): Failed write_ctrl(u 85) res=-1 errno=22 05-16 10:15:18.546: I/qtaguid(21108): Untagging socket 85 failed errno=-22 05-16 10:15:18.546: W/NetworkManagementSocketTagger(21108): untagSocket(85) failed with errno -22 05-16 10:15:18.546: I/imp(21108): I/O exception (org.apache.http.NoHttpResponseException) caught when processing request: The target server failed to respond 05-16 10:15:18.546: I/imp(21108): Retrying request 05-16 10:15:19.576: E/SyncSchedulerImpl(14877): Ignoring sync request: rate limited (on connection limit)
Editar:
Aquí está mi código para leer un archivo que contiene los datos de la aplicación. Este código se incluye en la actividad onCreate
procedure:
monGoogleApiLire = new GoogleApiClient.Builder(this).addApi(Drive.API).addScope(Drive.SCOPE_FILE) .addScope(Drive.SCOPE_APPFOLDER).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() { @Override public void onConnected(Bundle connectionHint) { Filter titreFilter = Filters.eq(SearchableField.TITLE, NOM_FICHIER_PLANNING); Query query = new Query.Builder().addFilter(titreFilter).build(); Drive.DriveApi.getAppFolder(monGoogleApiLire).queryChildren(monGoogleApiLire, query) .setResultCallback(new ResultCallback<MetadataBufferResult>() { @Override public void onResult(MetadataBufferResult result) { if (!result.getStatus().isSuccess()) { // showMessage("Error while trying to create the file"); return; } MetadataBuffer meta = result.getMetadataBuffer(); if (meta.getCount() != 0) { int nb = meta.getCount(); DriveId idc = null; for (int i = 0; i < nb; i++) { idc = meta.get(i).getDriveId(); } DriveFile fichier = Drive.DriveApi.getFile(monGoogleApiLire, idc); fichier.openContents(monGoogleApiLire, DriveFile.MODE_READ_ONLY, null) .setResultCallback(new ResultCallback<ContentsResult>() { @Override public void onResult(ContentsResult result) { if (!result.getStatus().isSuccess()) { // display an error saying file can't be opened return; } // Contents object contains pointers // to the actual byte stream Contents contents = result.getContents(); BufferedReader reader = new BufferedReader( new InputStreamReader(contents.getInputStream())); StringBuilder builder = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); } String contentsAsString = builder.toString(); reader.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } contents.close(); // fichier.commitAndCloseContents(gapi, contents); } }); } else { monPlanning = new ArrayList<DonneesPlanning>(); afficherPlanning(); if (monPlanning != null && mesCours != null && mesLieux != null) { ActiviteKholle.this.setProgressBarIndeterminateVisibility(false); monGoogleApiLire.disconnect(); } // monGoogleApiLire.disconnect(); } meta.close(); } }); titreFilter = Filters.eq(SearchableField.TITLE, NOM_FICHIER_COURS); query = new Query.Builder().addFilter(titreFilter).build(); Drive.DriveApi.getAppFolder(monGoogleApiLire).queryChildren(monGoogleApiLire, query) .setResultCallback(new ResultCallback<MetadataBufferResult>() { @Override public void onResult(MetadataBufferResult result) { if (!result.getStatus().isSuccess()) { // showMessage("Error while trying to create the file"); return; } MetadataBuffer meta = result.getMetadataBuffer(); if (meta.getCount() != 0) { int nb = meta.getCount(); DriveId idc = null; for (int i = 0; i < nb; i++) { idc = meta.get(i).getDriveId(); } DriveFile fichier = Drive.DriveApi.getFile(monGoogleApiLire, idc); fichier.openContents(monGoogleApiLire, DriveFile.MODE_READ_ONLY, null) .setResultCallback(new ResultCallback<ContentsResult>() { @Override public void onResult(ContentsResult result) { if (!result.getStatus().isSuccess()) { // display an error saying file can't be opened return; } // Contents object contains pointers // to the actual byte stream Contents contents = result.getContents(); BufferedReader reader = new BufferedReader( new InputStreamReader(contents.getInputStream())); StringBuilder builder = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); } String contentsAsString = builder.toString(); reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } contents.close(); // fichier.commitAndCloseContents(gapi, contents); } }); } else { mesCours = new ArrayList<DonneesCours>(); if (monPlanning != null && mesCours != null && mesLieux != null) { ActiviteKholle.this.setProgressBarIndeterminateVisibility(false); monGoogleApiLire.disconnect(); } } meta.close(); } }); titreFilter = Filters.eq(SearchableField.TITLE, NOM_FICHIER_LIEUX); query = new Query.Builder().addFilter(titreFilter).build(); Drive.DriveApi.getAppFolder(monGoogleApiLire).queryChildren(monGoogleApiLire, query) .setResultCallback(new ResultCallback<MetadataBufferResult>() { @Override public void onResult(MetadataBufferResult result) { if (!result.getStatus().isSuccess()) { // showMessage("Error while trying to create the file"); return; } MetadataBuffer meta = result.getMetadataBuffer(); if (meta.getCount() != 0) { int nb = meta.getCount(); DriveId idc = null; for (int i = 0; i < nb; i++) { idc = meta.get(i).getDriveId(); } DriveFile fichier = Drive.DriveApi.getFile(monGoogleApiLire, idc); fichier.openContents(monGoogleApiLire, DriveFile.MODE_READ_ONLY, null) .setResultCallback(new ResultCallback<ContentsResult>() { @Override public void onResult(ContentsResult result) { if (!result.getStatus().isSuccess()) { // display an error saying file can't be opened return; } // Contents object contains pointers // to the actual byte stream Contents contents = result.getContents(); BufferedReader reader = new BufferedReader( new InputStreamReader(contents.getInputStream())); StringBuilder builder = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); } String contentsAsString = builder.toString(); reader.close(); if (monPlanning != null && mesCours != null && mesLieux != null) { ActiviteKholle.this .setProgressBarIndeterminateVisibility(false); monGoogleApiLire.disconnect(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } contents.close(); // fichier.commitAndCloseContents(gapi, contents); } }); } else { mesLieux = new ArrayList<DonneesLieu>(); if (monPlanning != null && mesCours != null && mesLieux != null) { ActiviteKholle.this.setProgressBarIndeterminateVisibility(false); monGoogleApiLire.disconnect(); } } meta.close(); } }); } @Override public void onConnectionSuspended(int cause) { // TODO Auto-generated method stub } }).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult result) { // TODO Auto-generated method stub } }).build(); monGoogleApiLire.connect();
Hay alguna explicación para esto ?
PS: Después de un montón de pruebas y pruebas, ahora estoy seguro de que el campo "monGoogleApi" está conectado cuando pruebo la existencia del archivo. Cuando utilizo "queryChildren" para buscar el archivo por nombre y tipo mime, en la línea de código:
if (meta.getCount() != 0) { ... }
Durante 15 minutos, meta.getCount es igual a 1, después de 15 minutos, meta.getCount es igual a 0.
- Cómo adjuntar código fuente a la API de Google Drive o `Biblioteca privada de Android 'en Eclipse
- Android: accede a la carpeta de aplicaciones de Google Drive desde otro dispositivo, pero la misma aplicación
- Guardar archivo en una carpeta específica con Google Drive SDK
- Autorizar mi aplicación para usar una carpeta existente
- Google Drive OCR Android
- Abrir y guardar archivos de Android en / desde el SDK de Google Drive
- API de Google Drive: el nombre no debe estar vacío: null (pero había pasado el nombre de cuenta válido a GoogleAccountCredential)
- ¿Cómo configurar las credenciales de Google Drive en la aplicación de Android?
¿Ha comprobado el estado de conexión de "monGoogleApi"?
Esta conexión puede tener un tiempo de espera de sesión.