Android 从google Drive检索文件时出错,驱动器ID无效

Android 从google Drive检索文件时出错,驱动器ID无效,android,google-drive-android-api,Android,Google Drive Android Api,简要说明: 在下面的代码中,我试图做的是在驱动器文件夹中创建新文件时,我希望将文件Id存储在本地数据库中,并且我将使用该Id获取该文件 upload()在这种情况下,它将实际创建文件并上载到驱动器 fileid.add(dfres.getDriveFile().getDriveId().encodeToString()是否正确 sync() 这就是我得到错误的地方:- DriveId did=DriveId.decodeFromString(dbfileid.get(i)); 请帮忙 代码:*已

简要说明:

在下面的代码中,我试图做的是在驱动器文件夹中创建新文件时,我希望将文件Id存储在本地数据库中,并且我将使用该Id获取该文件

upload()在这种情况下,它将实际创建文件并上载到驱动器

fileid.add(dfres.getDriveFile().getDriveId().encodeToString()是否正确

sync() 这就是我得到错误的地方:- DriveId did=DriveId.decodeFromString(dbfileid.get(i));

请帮忙

代码:*已编辑*


如果您初始化并连接“mGoogleApiClient”,并且使用“getGoogleApiClient()”,那么上面的代码如何工作/编译“来自godknowswhere。我建议您从原始示例开始,然后从那里构建。示例非常简单。GAC类是大多数GDAA场景的完整包装器,如果您从那里开始构建,您的大多数问题都将由您自己的调试器来回答。

seanpj抱歉,在前面的代码中我没有回答过。”未命名的完整代码刚刚粘贴了主要方法。现在我添加了完整代码。它部分工作。错误在这一行。DriveId did=DriveId.decodeFromString(dbfileid.get(i));DriveFile file2=Drive.DriveApi.getFile(getGoogleApiClient(),did);肖恩,我如何确保我等待足够长的时间才能拿到驾驶证,因为我似乎得到了一些不同的东西,incomplete@Eenvincible我不明白。你能用代码示例单独创建一个问题吗?我已经在@seanpj创建了一个问题
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());
     }
 }

}
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);
}


}