gpt4 book ai didi

java - Android 更新在 Google 云端硬盘上创建的文件的文件内容

转载 作者:行者123 更新时间:2023-11-30 02:20:28 25 4
gpt4 key购买 nike

我已经完成了谷歌驱动器集成,在集成中我创建了一个文件并在文件上写了一些文本并将其保存到登录用户的驱动器中它运行良好但我想更新我创建的文件的内容保存到驱动器,我已经做了很多研究但找不到演示或任何代码,请任何人指导我,我会在创建文件并保存到我的驱动器的地方发布我的代码

 public class MainActivity extends Activity implements ConnectionCallbacks,OnConnectionFailedListener {

private GoogleApiClient mGoogleApiClient;
Button b ,editfile;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();

b = (Button) findViewById(R.id.createfile);
editfile = (Button) findViewById(R.id.editfile);
b.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub


// create new contents resource
/**
* A code to illustrate how to create a new FILE in the Drive.
*/
Drive.DriveApi.newContents(getGoogleApiClient())
.setResultCallback(contentsCallback);

}
});



}


@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}

/**
* Called when activity gets visible. A connection to Drive services need to
* be initiated as soon as the activity is visible. Registers
* {@code ConnectionCallbacks} and {@code OnConnectionFailedListener} on the
* activities itself.
*/
@Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
//.addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub

}

@Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, 1);
} catch (IntentSender.SendIntentException e) {
// Unable to resolve, message user appropriately
}
} else {
GooglePlayServicesUtil.getErrorDialog(
connectionResult.getErrorCode(), this, 0).show();
}
}

@Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
break;
}
}

public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}





/**
* A code to illustrate how to create a new FILE with some text on the file in the Google Drive.
*/
final private ResultCallback<ContentsResult> contentsCallback = new ResultCallback<ContentsResult>() {
@Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(MainActivity.this,"Error while trying to create new file contents" ,Toast.LENGTH_LONG).show();
return;
}

Contents driveContents = result.getContents();
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
try {
writer.write(information_data());
writer.close();
} catch (IOException e) {
Log.e("IOExceptions=", e.toString());
}

MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("testFile.txt")
.setMimeType("text/plain")
.setStarred(true)
.build();
// create a file on root folder
Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getContents())
.setResultCallback(fileCallback);
}
};

final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
@Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(MainActivity.this,"Error while trying to create the file" ,Toast.LENGTH_LONG).show();

return;
}
Toast.makeText(MainActivity.this,"Created a file: " + result.getDriveFile().getDriveId(),Toast.LENGTH_LONG).show();
Log.e("result.getDriveFile().getDriveId=", ""+result.getDriveFile().getDriveId());
Log.e("result.getStatus()=", ""+result.getStatus().toString());

//Opening the file contents Reading files
driveOpnefileContents(result.getDriveFile());

}
};

public void driveOpnefileContents(DriveFile driveFile) {
// TODO Auto-generated method stub
Log.e("driveOpnefileContents=", "driveOpnefileContents");
driveFile.openContents(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, new DownloadProgressListener() {

@Override
public void onProgress(long bytesDownloaded, long bytesExpected) {
// Update progress dialog with the latest progress.
Log.e("onProgress=", "onProgress");
int progress = (int)(bytesDownloaded*100/bytesExpected);
Log.e("progress", String.format("Loading progress: %d percent=", progress));
}
})
.setResultCallback(contentsOpenedCallback);

}

ResultCallback<ContentsResult> contentsOpenedCallback = new ResultCallback<ContentsResult>() {
@Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
// display an error saying file can't be opened
Toast.makeText(MainActivity.this,"display an error saying file can't be opened" ,Toast.LENGTH_LONG).show();
return;
}
// DriveContents object contains pointers
// to the actual byte stream
try {
Contents driveContents = result.getContents();
BufferedReader reader = new BufferedReader(new InputStreamReader(driveContents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
String contentsAsString = builder.toString();
Log.e("Reading File Contents As String=", ""+contentsAsString);
driveContents.close();
/*try {
ParcelFileDescriptor parcelFileDescriptor = driveContents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);

// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("editing the contents of the saved file");
writer.close();

driveContents.close();

} catch (IOException e) {
Log.e("IOExceptionAppend to the file.=", e.toString());
//java.io.IOException: write failed: EBADF (Bad file number)
}*/
Log.e("Append to the file.=", "Append to the file.");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IOExceptionAppend to the file2.=", e.toString());
}

}
};

public String information_data(){
String result = "";
try {
JSONObject jArrayFacebookData = new JSONObject();
JSONObject jObjectType = new JSONObject();
// put elements into the object as a key-value pair
jObjectType.put("info", "facebook_login");
jArrayFacebookData.put("Result", jObjectType);
// 2nd array for user information
JSONObject jObjectData = new JSONObject();
// Create Json Object using Facebook Data
jObjectData.put("facebook_user_id", "facebook_user_id");
jObjectData.put("first_name", "achin");
jObjectData.put("last_name", "verma");
jObjectData.put("email", "xvz");
jObjectData.put("username", "achin");
jObjectData.put("birthday", "28 april 90");
jObjectData.put("gender", "male");
jObjectData.put("location", "mohali");
jObjectData.put("display_photo", "link");
jArrayFacebookData.put("data", jObjectData);
//Log.e("jArrayFacebookData=", ""+jArrayFacebookData);
result = ""+jArrayFacebookData;
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return result;

}

}

最佳答案

这是一个代码 fragment “更新”,可以满足您的需要(我认为)。它使用的是必须从 UI 线程运行的“等待”调用版本,或者您可以将其转换为回调版本。您实际上只需要以

开头的部分

dFile.open(mGAC, DriveFile.MODE_WRITE_ONLY, null)

(将 DriveId 转换为 DriveFile 之后)并确保对其调用“commit”

  /**
* update file in GOODrive
* @param dId file id
* @param titl new file name (optional)
* @param mime new file mime type (optional, null or MIME_FLDR indicates folder)
* @param buf new file contents (optional)
* @return success status
*/
static boolean update(DriveId dId, String titl, String mime, String desc, byte[] buf){
if (dId == null || !isConnected()) return false; //------------>>>

Boolean bOK = false;
Builder mdBd = new MetadataChangeSet.Builder();
if (titl != null) mdBd.setTitle(titl);
if (mime != null) mdBd.setMimeType(mime);
if (desc != null) mdBd.setDescription(desc);
MetadataChangeSet meta = mdBd.build();

if (mime == null || UT.MIME_FLDR.equals(mime)) {
DriveFolder dFldr = Drive.DriveApi.getFolder(mGAC, dId);
MetadataResult r1 = dFldr.updateMetadata(mGAC, meta).await();
bOK = (r1 != null) && r1.getStatus().isSuccess();

} else {
DriveFile dFile = Drive.DriveApi.getFile(mGAC, dId);
MetadataResult r1 = dFile.updateMetadata(mGAC, meta).await();
if ((r1 != null) && r1.getStatus().isSuccess() && buf != null) {
DriveContentsResult r2 = dFile.open(mGAC, DriveFile.MODE_WRITE_ONLY, null).await();
if (r2.getStatus().isSuccess()) {
Status r3 = bytes2Cont(r2.getDriveContents(), buf).commit(mGAC, meta).await();
bOK = (r3 != null && r3.isSuccess());
}
}
}
return bOK;
}

在您的案例中,元数据不需要更新,因此您可以修改代码或只传递空值。您的新内容必须作为字节缓冲区传递(字符串转换为字节,jpeg 数据缓冲区,...)。

此方法的上下文 can be found here .祝你好运

关于java - Android 更新在 Google 云端硬盘上创建的文件的文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28622664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com