selecting picture from sdcard and store it to goog

2019-04-09 06:35发布

问题:

I am making android app which will simply pick an image from sdcard (phone gallery) and store it to Google drive. I did a lot much effort on this, I took help from the code provided by Google developers on drive quick start. I made a Button control in my main.xml file, when click on this button it takes inside the phone gallery and when I select a picture nothing is happening

This is Log Cat from my eclipse IDE

 05-13 05:05:47.890: D/gralloc_goldfish(16802): Emulator without GPU emulation detected.
05-13 05:08:00.600: W/ActivityThread(17711): Application com.camera is waiting for the debugger on port 8100...
05-13 05:08:00.660: I/System.out(17711): Sending WAIT chunk
05-13 05:08:00.690: I/dalvikvm(17711): Debugger is active
05-13 05:08:00.700: I/System.out(17711): Debugger has connected
05-13 05:08:00.700: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:00.980: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:01.180: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:01.389: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:01.590: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:01.790: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:01.990: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:02.190: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:02.400: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:02.610: I/System.out(17711): debugger has settled (1374)
05-13 05:08:05.090: I/Choreographer(17711): Skipped 40 frames!  The application may be doing too much work on its main thread.
05-13 05:08:05.280: D/gralloc_goldfish(17711): Emulator without GPU emulation detected.
05-13 05:08:10.120: I/Choreographer(17711): Skipped 47 frames!  The application may be doing too much work on its main thread.
05-13 05:08:13.369: I/Choreographer(17711): Skipped 89 frames!  The application may be doing too much work on its main thread.
05-13 05:08:14.699: D/dalvikvm(17711): GC_FOR_ALLOC freed 52K, 8% free 2544K/2752K, paused 187ms, total 220ms
05-13 05:08:14.879: I/dalvikvm-heap(17711): Grow heap (frag case) to 4.455MB for 1920016-byte allocation
05-13 05:08:15.029: D/dalvikvm(17711): GC_FOR_ALLOC freed 4K, 5% free 4415K/4628K, paused 141ms, total 141ms
05-13 05:08:15.059: W/CursorWrapperInner(17711): Cursor finalized without prior close()
05-13 05:08:15.329: D/dalvikvm(17711): GC_CONCURRENT freed <1K, 5% free 4415K/4628K, paused 13ms+34ms, total 303ms
05-13 05:08:16.469: I/Choreographer(17711): Skipped 1536 frames!  The application may be doing too much work on its main thread.
05-13 05:08:17.159: I/Choreographer(17711): Skipped 268 frames!  The application may be doing too much work on its main thread.
05-13 05:08:18.049: I/Choreographer(17711): Skipped 41 frames!  The application may be doing too much work on its main thread.
05-13 05:08:22.580: W/AbstractGoogleClient(17711): Application name is not set. Call Builder#setApplicationName.
05-13 05:08:22.970: I/Choreographer(17711): Skipped 82 frames!  The application may be doing too much work on its main thread.

Here is my Java Code

import java.io.IOException;
import com.camera.R;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity{

    private static final int REQUEST_ACCOUNT_PICKER = 1;
    private static final int SELECT_PICTURE = 3;
    private static final int REQUEST_AUTHORIZATION = 2;

    private static Drive service;
    private GoogleAccountCredential credential;  
   private static Uri selectedImageUri;

    private String selectedImagePath;
    private ImageView img;
    private TextView tv;
    Intent pictureintent;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        img = (ImageView)findViewById(R.id.ImageView01);
        ((Button) findViewById(R.id.Button01)).setOnClickListener(new OnClickListener() {
                     public void onClick(View v) {

                         pictureintent = new Intent();
                         pictureintent.setType("image/jpeg");
                         pictureintent.setAction(Intent.ACTION_GET_CONTENT);
                         pictureintent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
                         startActivityForResult(pictureintent, SELECT_PICTURE);

                    }
                }); 


    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode){
        case REQUEST_ACCOUNT_PICKER:
            if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
                String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                if (accountName != null) {
                  credential.setSelectedAccountName(accountName);
                  service = getDriveService(credential);
                  saveFileToDrive();
                }
              }
              break;
        case REQUEST_AUTHORIZATION:
              if (resultCode == Activity.RESULT_OK) {
                saveFileToDrive();
              } else {
                startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
              }

        case SELECT_PICTURE:
        if (resultCode == Activity.RESULT_OK) {

                selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                tv = (TextView) findViewById(R.id.text1);
                tv.setText("File Path: " + selectedImagePath);
                //showToast("File Path: " + selectedImagePath);
                //System.out.println("Image Path : " + selectedImagePath);
                img.setImageURI(selectedImageUri); 
                startpictureIntent();

        }

    }
}



    private Drive getDriveService(GoogleAccountCredential credential) {
        return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
            .build();
      }

    public void startpictureIntent(){


        credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
        startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);


    }



    private void saveFileToDrive() {

       Thread t = new Thread(new Runnable() {
          @Override
          public void run() {
            try {
              // File's binary content
              java.io.File fileContent = new java.io.File(selectedImageUri.getPath());
              FileContent mediaContent = new FileContent("image/jpeg", fileContent);

              // File's metadata.
              File body = new File();
              body.setTitle(fileContent.getName());
              body.setMimeType("image/jpeg");

              File file = service.files().insert(body, mediaContent).execute();
              if(file != null) {

                showToast("Photo uploaded: " + file.getTitle());

              }

            }catch (UserRecoverableAuthIOException e) {
                startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
            }   catch (IOException e) {
              e.printStackTrace();
            }
          }
        });
        t.start();
      }



        public String getPath(Uri uri) {
             String[] projection = { MediaStore.Images.Media.DATA };
             Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
             int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
             cursor.moveToFirst();
            return cursor.getString(column_index);
        }  



         public void showToast(final String toast) {
                runOnUiThread(new Runnable() {
                  @Override
                  public void run() {

                    Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_LONG).show();

                  }
                });
              }

}

Finally This is my Android Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.camera"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.READ_SYNC_STATS" />
    <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
    <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />



    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >


  <meta-data android:name="com.google.android.apps.drive.APP_ID" android:value="id=829672----" />
        <intent-filter>
            <action android:name="android.intent.action.GoogleDrive" />
        <action android:name="com.google.android.apps.drive.DRIVE_OPEN" />
        <data android:mimeType="application/vnd.google-apps.drive-sdk.829672----" />
        <data android:mimeType="image/png" />
        <data android:mimeType="image/jpeg" />
        <data android:mimeType="image/jpg" />
        </intent-filter>

        <activity
            android:name="com.example.drivequickstart.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />                
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

any help will be appreciated. Thanks in advance

回答1:

You're getting this error because Google Play Services don't exist on your phone or is out of the date. Install the latest version of the Google Play Services, it's at the store https://play.google.com/store/apps/details?id=com.google.android.gms



回答2:

At Last I have found my solution and now I am able to send images to Google Drive from camera (Which is available on Drive Quick Start) and second part I have done that select a picture from Gallery and store it to Google Drive as well. See Code below

@Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) 
    {
        switch (requestCode) 
        {
        case REQUEST_ACCOUNT_PICKER:
            if (resultCode == RESULT_OK && data != null && data.getExtras() != null) 
            {
                String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                if (accountName != null) 
                {
                    credential.setSelectedAccountName(accountName);
                    service = getDriveService(credential);
                }
            }
            break;

        case REQUEST_AUTHORIZATION:
            if (resultCode == Activity.RESULT_OK) 
            {
                saveFileToDrive();
            } 

            else 
            {
                startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
            }
            break;

        case SELECT_PICTURE:
            if (resultCode == Activity.RESULT_OK) 
            {
                    selectedImageUri = data.getData();
                    selectedImagePath = getPath(selectedImageUri);
                    tvPath.setText("File Path: " + selectedImagePath);
                    System.out.println("Image Path : " + selectedImagePath);
                    img.setImageURI(selectedImageUri); 
            }
            break;

        case CAPTURE_IMAGE:
            if (resultCode == Activity.RESULT_OK) 
            {
                /*String mediaStorageDir = Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES).getPath();
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
                selectedImageUri = Uri.fromFile(new java.io.File(mediaStorageDir + java.io.File.separator + "IMG_"
                        + timeStamp + ".jpg"));*/
                selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                img.setImageURI(selectedImageUri);
            }
            break;
        }
    }

/*************** This method leads you to start your device's camera *****************/
    private void startCameraIntent() 
    { 
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
        startActivityForResult(cameraIntent, CAPTURE_IMAGE);
    }

    /*************** This method will take you to gallery *****************/
    private void selectPictureIntent() 
    {       
        Intent pictureintent = new Intent();
        pictureintent.setType("image/jpeg");
        pictureintent.setAction(Intent.ACTION_GET_CONTENT);
        pictureintent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
        startActivityForResult(pictureintent, SELECT_PICTURE);

    }

private void saveFileToDrive() 
    {
        Thread t = new Thread(new Runnable() 
        {
            @Override
            public void run() 
            {
            try 
            {
            // File's binary content
        java.io.File fileContent = new java.io.File(selectedImagePath);// here I was wrong I was sending selectedImageUri.getPath(); and now I am getting path by making getPath() Method and get Path where the image is saved in phone.
            FileContent mediaContent = new FileContent("image/jpeg", fileContent);

                    // File's metadata.
                    File body = new File();
                    body.setTitle(fileContent.getName());
                    body.setMimeType("image/jpeg");

                    File file = service.files().insert(body, mediaContent).execute();
                    if (file != null) 
                    {                       
                        pd.dismiss();

                    }
                    else
                    {
                        pd.dismiss();
                                            System.out.println("File not sent...");


                    }
                } 

                catch (UserRecoverableAuthIOException e) 
                {
                    startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                } 

                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
        });
        t.start();
}

    public String getPath(Uri uri) 
        {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
           return cursor.getString(column_index);
       }