2016-10-24 6 views
1

初めてGoogleApiClientを使用していて、アプリの共有ボタンをクリックすると、すべてのテキストメッセージをGoogleドライブにアップロードします。しかし、データはドライブにアップロードされていません。アンドロイドからGoogleドライブにテキストメッセージをアップロードしていない

MainActivity:

 public class MainActivity extends AppCompatActivity { 


      RecyclerView rv; 
      SmsAdapter adapter; 
      FloatingActionButton fab; 
      Cursor c; 
      ExportTask task; 
      ArrayList<CustomSms> smslistSearch; 

      @Override 
      protected void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.activity_main); 
       Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
       setSupportActionBar(toolbar); 

       smslistSearch = new ArrayList<>(); 
       rv = (RecyclerView) findViewById(R.id.messages_view); 

       LinearLayoutManager llm = new LinearLayoutManager(MainActivity.this); 
       rv.setLayoutManager(llm); 


       fab = (FloatingActionButton) findViewById(R.id.fab); 
       fab.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
         Intent i =new Intent(MainActivity.this,SendSms.class); 
         startActivity(i); 
        } 
       }); 



      } 

      @Override 
      protected void onResume() { 
       super.onResume(); 


       try { 


        final ArrayList<CustomSms> smslist, smsgrouplist; 

        smslist = new ArrayList<>(); 
        smsgrouplist = new ArrayList<>(); 

        //Fetch inobx sms message 
        c = getContentResolver().query(SmsApplication.INBOX_URI, null, null, null, null); 


        while (c.moveToNext()) { 
         String address = c.getString(c.getColumnIndexOrThrow("address")); 
         String date = c.getString(c.getColumnIndexOrThrow("date")); 
         String body = c.getString(c.getColumnIndexOrThrow("body")); 

         smslist.add(new CustomSms(address, date, body)); 
        } 



        smslistSearch = smslist; 
        Map<String, CustomSms> map = new LinkedHashMap<>(); 

        for (CustomSms ays : smslist) { 

         CustomSms existingValue = map.get(ays.address); 
         if(existingValue == null){ 
          map.put(ays.address, ays); 
         } 
        } 

        smsgrouplist.clear(); 
        smsgrouplist.addAll(map.values()); 


        adapter = new SmsAdapter(MainActivity.this); 
        adapter.updateList(smsgrouplist); 
        rv.setAdapter(adapter); 

        rv.addOnItemTouchListener(
          new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() { 
           @Override 
           public void onItemClick(View view, int position) { 
            // TODO Handle item click 
            ArrayList<CustomSms> smsinsidegroup = new ArrayList<CustomSms>(); 

            String n = smsgrouplist.get(position).address; 

            for (int i = 0; i < smslist.size(); i++) { 
             if(smslist.get(i).address.equals(n)) 
              smsinsidegroup.add(smslist.get(i)); 
            } 

            Intent i = new Intent(MainActivity.this, ReadAllSms.class); 
            i.putParcelableArrayListExtra("messages", smsinsidegroup); 
            startActivity(i); 
           } 
          }) 
        ); 
       } 
       catch (Exception e) 
       { 
        e.printStackTrace(); 
       } 


      } 

      class ExportTask extends AsyncTask<Void, Integer, Uri> { 

      ProgressDialog pDialog; 

      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       pDialog = new ProgressDialog(MainActivity.this); 
       pDialog.setMessage("Exporting to file ..."); 
       pDialog.setIndeterminate(false); 
       pDialog.setMax(100); 
       pDialog.setProgress(0); 
       pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
       pDialog.setCancelable(false); 
       pDialog.show(); 
      } 

      @Override 
      protected Uri doInBackground(Void... params) { 
       if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { 
        FileOutputStream fos = null; 
        try { 
         File f = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt"); 
         fos = new FileOutputStream(f); 
         int count = c.getCount(), i = 0; 

         StringBuilder sb = new StringBuilder(); 
         if (c.moveToFirst()) { 
          do { 
           sb.append(c.getString(c.getColumnIndex("address"))) 
             .append("\n"); 
           sb.append(c.getString(c.getColumnIndex("body"))) 
             .append("\n"); 
           sb.append("\n"); 
           publishProgress(++i*100/count); 
          } while (!isCancelled() && c.moveToNext()); 
         } 
         fos.write(sb.toString().getBytes()); 
         return Uri.fromFile(f); 

        } catch (Exception e) { 
        } finally { 
         if (fos != null) { 
          try { 
           fos.close(); 
          } catch (IOException e) {} 
         } 
        } 
       } 

       return null; 
      } 

      @Override 
      protected void onProgressUpdate(Integer... values) { 
       super.onProgressUpdate(values); 
       pDialog.setProgress(values[0]); 
      } 

      @Override 
      protected void onPostExecute(Uri result) { 
       super.onPostExecute(result); 
       pDialog.dismiss(); 

       if (result == null) { 
        Toast.makeText(MainActivity.this, "Export task failed!", 
          Toast.LENGTH_LONG).show(); 
        return; 
       } 

       Intent i = new Intent(MainActivity.this,UploadData.class); 
       startActivity(i); 
      } 

     } 

      @Override 
      public boolean onCreateOptionsMenu(Menu menu) { 
       // Inflate the menu; this adds items to the action bar if it is present. 
       getMenuInflater().inflate(R.menu.menu_main, menu); 
       return true; 
      } 

      @Override 
      public boolean onOptionsItemSelected(MenuItem item) { 
       // Handle action bar item clicks here. The action bar will 
       // automatically handle clicks on the Home/Up button, so long 
       // as you specify a parent activity in AndroidManifest.xml. 
       int id = item.getItemId(); 

       //noinspection SimplifiableIfStatement 
       if (id == R.id.action_search) { 
        Intent i = new Intent(MainActivity.this,SearchActivity.class); 
        i.putParcelableArrayListExtra("search", smslistSearch); 
        startActivity(i); 
        return true; 
       } 
       if (id == R.id.action_share) { 
        /*Intent i = new Intent(MainActivity.this,UploadData.class); 
        startActivity(i);*/ 

        task = new ExportTask(); 
        task.execute(); 
        return true; 
       } 
       return super.onOptionsItemSelected(item); 
      } 

      @Override 
      protected void onPause() { 
       if (task != null) { 
        task.cancel(false); 
        task.pDialog.dismiss(); 
       } 
       super.onPause(); 
      } 

     } 

UploadData:

 public class UploadData extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, 
       GoogleApiClient.OnConnectionFailedListener { 


      private static final String TAG = "upload_file"; 
      private static final int REQUEST_CODE = 101; 
      private File textFile; 
      private GoogleApiClient googleApiClient; 
      public static String drive_id; 
      public static DriveId driveID; 

      FrameLayout rl; 
      TextView success; 
      ProgressBar progressBar; 

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


       rl = (FrameLayout) findViewById(R.id.frame); 
       success = (TextView) findViewById(R.id.success); 
       progressBar = (ProgressBar) findViewById(R.id.progressBar); 

       View root = rl.getRootView(); 
       root.setBackgroundColor(getResources().getColor(R.color.colorBackOrig)); 

       textFile = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt"); 

       buildGoogleApiClient(); 

      } 

      @Override 
      protected void onStart() { 
       super.onStart(); 
       Log.i(TAG, "connecting..."); 
       googleApiClient.connect(); 
      } 

      protected void onStop() { 
       super.onStop(); 
       if (googleApiClient != null) { 
        Log.i(TAG, "disConnecting..."); 
        googleApiClient.disconnect(); 
       } 
      } 

      @Override 
      protected void onActivityResult(int requestCode, int resultCode, 
              Intent data) { 
       super.onActivityResult(requestCode, resultCode, data); 
       if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) { 
        Log.i(TAG, "In onActivityResult() - connecting..."); 
        googleApiClient.connect(); 
       } 
      } 

      @Override 
      public void onConnected(Bundle bundle) { 
       Log.i(TAG, "in onConnected() - connected"); 
       Drive.DriveApi.newDriveContents(googleApiClient) 
         .setResultCallback(driveContentsCallback); 
      } 

      @Override 
      public void onConnectionSuspended(int cause) { 
       switch (cause) { 
        case 1: 
         Log.i(TAG, "Connection suspended - Cause: " + "Service disconnected"); 
         break; 
        case 2: 
         Log.i(TAG, "Connection suspended - Cause: " + "Connection lost"); 
         break; 
        default: 
         Log.i(TAG, "Connection suspended - Cause: " + "Unknown"); 
         break; 
       } 
      } 

      final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback = new 
        ResultCallback<DriveApi.DriveContentsResult>() { 
         @Override 
         public void onResult(DriveApi.DriveContentsResult result) { 
          if (!result.getStatus().isSuccess()) { 
           Log.i(TAG, "Error creating the new file of contents"); 
           return; 
          } 
          final DriveContents driveContents = result.getDriveContents(); 
          new Thread() { 
           @Override 
           public void run() { 
            OutputStream outputStream = driveContents.getOutputStream(); 
            addTextfileToOutputStream(outputStream); 
            MetadataChangeSet changeSet = new MetadataChangeSet.Builder() 
              .setTitle("SmsBackup") 
              .setMimeType("text/plain") 
              .setDescription("This is a text file uploaded from device") 
              .setStarred(true).build(); 
            Drive.DriveApi.getRootFolder(googleApiClient) 
              .createFile(googleApiClient, changeSet, driveContents) 
              .setResultCallback(fileCallback); 
           } 
          }.start(); 
         } 
        }; 

      private void addTextfileToOutputStream(OutputStream outputStream) { 
       byte[] buffer = new byte[1024]; 
       int bytesRead; 
       try { 
        BufferedInputStream inputStream = new BufferedInputStream(
          new FileInputStream(textFile)); 
        while ((bytesRead = inputStream.read(buffer)) != -1) { 
         outputStream.write(buffer, 0, bytesRead); 
        } 
       } catch (IOException e) { 
        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show(); 

         } 
        }); 
        e.printStackTrace(); 
       } 
      } 

      final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new 
        ResultCallback<DriveFolder.DriveFileResult>() { 
         @Override 
         public void onResult(DriveFolder.DriveFileResult result) { 
          if (!result.getStatus().isSuccess()) { 
           Toast.makeText(UploadData.this, 
             "Error adding file to Drive", Toast.LENGTH_SHORT).show(); 
           return; 
          } 

          Toast.makeText(UploadData.this, 
            "File successfully added to Drive", Toast.LENGTH_SHORT).show(); 
          showProgress(false); 

          rl.setBackgroundColor(getResources().getColor(R.color.colorBack)); 
          View root = rl.getRootView(); 
          root.setBackgroundColor(getResources().getColor(R.color.colorBack)); 

          success.setVisibility(View.VISIBLE); 

          final PendingResult<DriveResource.MetadataResult> metadata 
            = result.getDriveFile().getMetadata(googleApiClient); 
          metadata.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() { 
                    @Override 
                    public void onResult(DriveResource.MetadataResult metadataResult) { 
                     Metadata data = metadataResult.getMetadata(); 
                     drive_id = data.getDriveId().encodeToString(); 
                     driveID = data.getDriveId(); 

                    } 
                   }); 
         } 
        }; 

      @Override 
      public void onConnectionFailed(ConnectionResult result) { 
       if (!result.hasResolution()) { 
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show(); 
        return; 
       } 
       try { 
        result.startResolutionForResult(this, REQUEST_CODE); 
       } catch (IntentSender.SendIntentException e) { 
       } 
      } 

      private void buildGoogleApiClient() { 
       if (googleApiClient == null) { 
        googleApiClient = new GoogleApiClient.Builder(this) 
          .addApi(Drive.API) 
          .addScope(Drive.SCOPE_FILE) 
          .addConnectionCallbacks(this) 
          .addOnConnectionFailedListener(this) 
          .build(); 
       } 
      } 

      @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) 
      private void showProgress(final boolean show) { 

       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { 
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); 

        progressBar.setVisibility(show ? View.VISIBLE : View.GONE); 
        progressBar.animate().setDuration(shortAnimTime).alpha(
          show ? 1 : 0).setListener(new AnimatorListenerAdapter() { 
         @Override 
         public void onAnimationEnd(Animator animation) { 
          progressBar.setVisibility(show ? View.VISIBLE : View.GONE); 
         } 
        }); 
       } else { 

        progressBar.setVisibility(show ? View.VISIBLE : View.GONE); 
       } 
      } 
     } 

答えて

0

あなたが持っている変数textFileの値がある場合work with File Contents、まずチェックしたいかもしれませんどのようにチェックしたいかもしれませんセット。

以下の例は、「hello world」をDriveContentsに追加する方法を示しています。あなたがチェックアウトする場合がありますUpload text file to Google Drive using Android -

try { 
ParcelFileDescriptor parcelFileDescriptor = contents.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("hello world"); 
} catch (IOException e) { 
e.printStackTrace(); 
} 

関連のSO質問があります。質問の答えは、ファイルにコンテンツをどのようにフィードするかについてOPを思い出させます。

最後に、githubにチェックを入れたい場合があります。このコードは、チャットのコンテンツをファイルに挿入してドライブに保存する方法を示しています。

これが役に立ちます。

関連する問題