简要说明:
在下面的代码中,我想要做的是当在驱动器文件夹中创建新文件时,我想将文件Id存储在本地数据库中,而这个id我将用于获取该文件。
upload()在此实际上会创建文件并上传到驱动器
fileIds.add(dfres.getDriveFile()。getDriveId()。encodeToString()是否正确?
同步() 这是我收到错误的地方: - DriveId做了= DriveId.decodeFromString(dbfileid.get(i));
请帮助
代码:* 已编辑*
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
int j=0;
private static final String LOGTAG="EXPLORECA";
private static final String DATABASE_NAME="file.db";
private static final int DATABASE_VERSION=1;
private static final String TABLE="fileids";
private static final String filename="fname";
private static final String fileid="fid";
Date driveFileDate=new Date();
Date localFileDate=new Date();
ArrayList<String> fileNames = new ArrayList<String>();
ArrayList<String> fileIds = new ArrayList<String>();
ArrayList<String> dbfilename = new ArrayList<String>();
ArrayList<String> dbfileid = new ArrayList<String>();
long lastSyncTime=0;
private static final int REQUEST_CODE_RESOLUTION = 3;
//String[] fileNames = new String[]{""};
Button b1;
private ContentsResult result;
private GoogleApiClient mGoogleApiClient;
byte[] buffer;
int i=111;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lastSyncTime= System.currentTimeMillis()-200000;
//b1=(Button)findViewById(R.id.button1);
getfiles();
if(fileNames.size()>0)
{
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.
try
{
mGoogleApiClient.connect();
}catch(Exception e)
{
showToast(""+e.toString());
}
}
else
{
showToast("Else Part ");
}
@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
showToast("connected");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("Sky folder").build();
DriveFolderResult sky = Drive.DriveApi.getRootFolder(getGoogleApiClient()).createFolder(
getGoogleApiClient(), changeSet).await();
showToast("folder created");
upload();
}
}
private void upload() {
// TODO Auto-generated method stub
showToast("Inside Connected");
for(int i=0;i<fileNames.size();i++)
{
result = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = result.getContents().getOutputStream();
String s=Environment.getExternalStorageDirectory().toString()+"/AudioRecorder";
File file = new File(s+"/"+fileNames.get(i));
showToast(file.getName()+" id uploading");
// showToast("Path="+Environment.DIRECTORY_DOWNLOADS+"/k.mp3 "+file.length());
buffer = new byte[(int)file.length()];
try {
showToast("started reading n writing");
FileInputStream is = new FileInputStream(file);
//ByteArrayInputStream iss = new ByteArrayInputStream(buffer, 0, 0);
int l =is.read(buffer);
//is.read
outputStream.write(buffer);
showToast("Buffer is written");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast(""+e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast(""+e.toString());
}
showToast(""+result.getContents().toString());
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(fileNames.get(i)+i)
.setMimeType("audio/MP3")
.setStarred(true).build();
showToast("meta data created");
DriveFileResult dfres= Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getContents())
.await();
showToast("await() complete");
if (!result.getStatus().isSuccess()) {
showToast("Error while trying to create the file");
return;
}
fileIds.add(dfres.getDriveFile().getDriveId().encodeToString());
// showToast("Created a file: " + dfres.getDriveFile().getDriveId());
}
showToast("fileIds = "+fileIds.size()+" first file"+fileIds.get(0));
add_to_db();
getvalues();
synch();
}
private void synch() {
// TODO Auto-generated method stub
for(int i=0;i<fileIds.size();i++)
{
String path = Environment.getExternalStorageDirectory().toString()+"/AudioRecorder/"+dbfilename.get(i);
showToast("Files Path: " + path);
File f = new File(path);
//long fileModifiedTime = f.lastModified();
localFileDate= new Date(f.lastModified());
showToast(""+localFileDate);
//fetchDriveId(getGoogleApiClient(), dbfileid.get(i).toString()).await();
DriveId did = DriveId.decodeFromString(dbfileid.get(i));
DriveFile file2= Drive.DriveApi.getFile(getGoogleApiClient(),did);
//DriveFile file2 = Drive.DriveApi.getFile(getGoogleApiClient(),result2.getDriveId());
MetadataResult metadata=file2.getMetadata(getGoogleApiClient()).await();
Metadata md =metadata.getMetadata();
driveFileDate=md.getModifiedByMeDate();
if(f.getName().equals(md.getTitle()))
{
showToast("File Not Changed"+f.getName()+" Drive Name"+md.getTitle());
}
else
{
if(localFileDate.getTime() < driveFileDate.getTime())
{
File f2 = new File(md.getTitle());
f.renameTo(f2);
showToast("After Renaming ="+f.getName());
}
else
{
MetadataChangeSet changeSet2 = new MetadataChangeSet.Builder()
.setStarred(true)
.setTitle(f.getName().toString()).build();
file2.updateMetadata(getGoogleApiClient(), changeSet2).await();
showToast("file renamed in drive");
}
}
}
}
private void getfiles() {
// TODO Auto-generated method stub
String path = Environment.getExternalStorageDirectory().toString()+"/AudioRecorder";
showToast("Files Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
//showToast("Files Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
// showToast("Files FileName:" + file[i].getName());
if(file[i].getName().contains(".mp3")||file[i].getName().contains(".wav"))
{
if(lastSyncTime < file[i].lastModified())
{
fileNames.add(file[i].getName().toString());
}
}
}
showToast("fileNames contains:"+fileNames.size());
}
private void getDriveFiles() {
// TODO Auto-generated method stub
showToast("Getting Drive files");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
// Called whenever the API client fails to connect.
//Log.i("GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
showToast("Error in on connection failed");
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) {
showToast("error"+e.toString());
// Log.e(TAG, "Exception while starting resolution activity", e);
}
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
showToast("Connected");
}
}
@Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});
}
public void add_to_db()
{
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
for(int i=0;i< fileNames.size();i++)
{
String name = fileNames.get(i);
String id = fileIds.get(i).substring(8);
showToast("database id ="+id);
values.put(filename,name);
values.put(fileid,id);
}
database.insert(TABLE, null, values);
database.close();
Toast.makeText(this,"Added Successfully" ,Toast.LENGTH_LONG).show();
}
public void getvalues()
{
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE;
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
dbfilename.add(cursor.getString(0));
dbfileid.add(cursor.getString(1));
showToast(dbfilename.get(j).toString()+" = "+dbfileid.get(j).toString());
j++;
} while (cursor.moveToNext());
}
}
}
fileiddb.java
public class fileiddb extends SQLiteOpenHelper {
private static final String LOGTAG="EXPLORECA";
private static final String DATABASE_NAME="file.db";
private static final int DATABASE_VERSION=1;
private static final String TABLE="fileids";
private static final String filename="fname";
private static final String fileid="fid";
private static final String TABLE_CREATE=
"CREATE TABLE "+TABLE +
" ("
+filename+" TEXT,"
+fileid +" TEXT primary key not null "
+")";
public fileiddb(Context context) {
super(context, DATABASE_NAME, null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(TABLE_CREATE);
Log.i(LOGTAG,"Table is Created");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+TABLE);
onCreate(sqLiteDatabase);
}
}
答案 0 :(得分:0)
如果您初始化并连接“GoogleApiClient”,那么上面的代码如何工作/编译?并使用&#39; getGoogleApiClient()&#39;来自godknowswhere。我建议你从原始示例like this one开始,然后从那里构建。这个例子很简单,你可以得到GAC类是大多数GDAA场景的完整包装器,如果你从那里开始构建,你的大部分问题将由你自己的调试器来回答。