First time I am using GoogleApiClient and want to upload all the text messages to google drive when the share button in the app is clicked. But the data is not uploading on the drive.
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);
}
}
}
You might want to check on how you work with File Contents, first you might want to check if there is a value on the variable textFile that you have set.
The example below illustrates how to append "hello world" to the DriveContents.
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();
}
There is a related SO question - Upload text file to Google Drive using Android that you might want to check out. The answer in the question reminds the OP regarding how to feed the file with contents.
Lastly, you might want to check this github. This code show how to insert the content of the chat into a file and save it to the drive.
Hope this helps.
Related
I'm uploading files to Google Drive using Google Drive api . I would like to know, how i can put a check for duplicate files. Because currently when my service runs, it uploads the file to google drive which was already uploaded before,
Here's my code:
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
public ArrayList songsList = new ArrayList();
private static final String TAG = "drive-quickstart";
private GoogleApiClient mGoogleApiClient;
public static ArrayList<File> listAllMusicFiles = new ArrayList<File>();
public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";
private SharedPreferences sharedPreferences;
/**
* DriveId of an existing file to be used in file operation samples..
*/
public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";
/**
* Extra for account name.
*/
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
/**
* Next available request code.
*/
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
private static final String DRIVE_ID = "driveId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final File mainDir = new File(Environment.getExternalStorageDirectory()
.getPath());
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
loadSdcardfiles(mainDir);
}
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive(final File file) {
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
final DriveContents driveContents = result
.getDriveContents();
// Otherwise, we can write our data to the new contents.
Log.i(TAG, "New contents created.");
// Get an output stream for the contents.
OutputStream outputStream = result.getDriveContents()
.getOutputStream();
// Write the bitmap data from it.
try {
#SuppressWarnings("resource")
FileInputStream fileInputStream = new FileInputStream(
file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setTitle(file.getName()).build();
// create a file on root folder
Drive.DriveApi
.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient,
metadataChangeSet, driveContents)
.setResultCallback(fileCallback);
try {
} catch (Exception e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}
private void loadSdcardfiles(File aFile) {
if (aFile.isFile()) {
if (aFile.getAbsolutePath().endsWith(".mp3")) {
listAllMusicFiles.add(aFile);
}
} else if (aFile.isDirectory()) {
File[] listOfFiles = aFile.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
loadSdcardfiles(listOfFiles[i]);
}
}
} else {
}
}
}
#SuppressWarnings("unchecked")
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API).addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
}
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
GoogleApiAvailability.getInstance()
.getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Toast.makeText(this, "API client connected" + listAllMusicFiles.get(0),
1000).show();
if (listAllMusicFiles.size() == 0) {
return;
} else {
for (int i = 0; i < listAllMusicFiles.size(); i++) {
saveFileToDrive(listAllMusicFiles.get(i));
}
}
}
#Override
public void onConnectionSuspended(int cause) {
Toast.makeText(this, "GoogleApiClient connection suspended", 1000)
.show();
}
// private void storeSumFileId(DriveId driveId) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putString(DRIVE_ID, driveId.encodeToString());
// editor.apply();
//
// }
// final private ResultCallback<DriveResource.MetadataResult> metadataRetrievedCallback = new ResultCallback<DriveResource.MetadataResult>() {
// #Override
// public void onResult(DriveResource.MetadataResult result) {
// if (!result.getStatus().isSuccess()) {
// Log.v(TAG, "Problem while trying to fetch metadata.");
// return;
// }
//
// Metadata metadata = result.getMetadata();
// if (metadata.isTrashed()) {
// Log.v(TAG, "Folder is trashed");
// } else {
// Log.v(TAG, "Folder is not trashed");
// }
//
// }
// };
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file with content: "
+ result.getDriveFile().getDriveId());
// storeSumFileId(result.getDriveFile().getDriveId());
}
};
}
i found the following links, but was unable to use it in my code :
Google Drive Android API - Check if folder exists
https://developers.google.com/drive/android/trash#trash_or_untrash_a_file_or_folder
Can anyone tell me how to make ckeck of existing File on drive?
Thanks.
Trying to put all files inside folder but getting result.getDriveFolder().getDriveId().getResourceId() always null. i searched and found some links and i tried to go with the steps mentioned in this linkenter link description here
Here's my code :-
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
public ArrayList songsList = new ArrayList();
private static final String TAG = "drive-quickstart";
private GoogleApiClient mGoogleApiClient;
public static ArrayList<File> listAllMusicFiles = new ArrayList<File>();
protected static final int REQUEST_CODE_RESOLUTION = 1;
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
private DriveId mFolderDriveId;
public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";
public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";
/**
* Extra for account name.
*/
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final File mainDir = new File(Environment.getExternalStorageDirectory()
.getPath());
loadSdcardfiles(mainDir);
}
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive(final File file) {
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
final DriveContents driveContents = result
.getDriveContents();
Log.i(TAG, "New contents created.");
OutputStream outputStream = result.getDriveContents()
.getOutputStream();
try {
#SuppressWarnings("resource")
FileInputStream fileInputStream = new FileInputStream(
file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
DriveFolder folder = mFolderDriveId.asDriveFolder();
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setTitle(file.getName()).setStarred(true)
.build();
// create a file on root folder
folder.createFile(mGoogleApiClient, metadataChangeSet,
driveContents).setResultCallback(fileCallback);
// Drive.DriveApi
// .getRootFolder(mGoogleApiClient)
// .createFile(mGoogleApiClient,
// metadataChangeSet, driveContents)
// .setResultCallback(fileCallback);
try {
} catch (Exception e) {
}
}
});
}
private void loadSdcardfiles(File aFile) {
if (aFile.isFile()) {
if (aFile.getAbsolutePath().endsWith(".mp3")) {
listAllMusicFiles.add(aFile);
}
} else if (aFile.isDirectory()) {
File[] listOfFiles = aFile.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
loadSdcardfiles(listOfFiles[i]);
}
}
} else {
}
}
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API).addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
}
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
GoogleApiAvailability.getInstance()
.getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Toast.makeText(this, "API client connected" + listAllMusicFiles.get(0),
1000).show();
if (listAllMusicFiles.size() == 0) {
return;
} else {
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("Siddharth").build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFolder(mGoogleApiClient, changeSet)
.setResultCallback(callback);
}
}
#Override
public void onConnectionSuspended(int cause) {
Toast.makeText(this, "GoogleApiClient connection suspended", 1000)
.show();
}
final private ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
#Override
public void onResult(DriveIdResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Cannot find DriveId. Are you authorized to view this file?");
return;
}
mFolderDriveId = result.getDriveId();
for (int i = 0; i < listAllMusicFiles.size(); i++) {
saveFileToDrive(listAllMusicFiles.get(i));
}
}
};
final ResultCallback<DriveFolderResult> callback = new ResultCallback<DriveFolderResult>() {
#Override
public void onResult(final DriveFolderResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the folder");
return;
}
showMessage("Created a folder: "
+ result.getDriveFolder().getDriveId());
mFolderDriveId = result.getDriveFolder().getDriveId();
DriveFolder folder = Drive.DriveApi.getFolder(mGoogleApiClient,
result.getDriveFolder().getDriveId());
folder.addChangeSubscription(mGoogleApiClient);
}
};
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file with content: "
+ result.getDriveFile().getDriveId());
}
};
public class MyDriveEventService extends DriveEventService {
#Override
public void onChange(ChangeEvent event) {
Log.d(TAG, event.toString());
Drive.DriveApi.fetchDriveId(mGoogleApiClient,
mFolderDriveId.getResourceId()).setResultCallback(
idCallback);
}
}
}
Can any one suggest me that how to do this, Thanks In advance
finally yes , it was there in my provided links...
here are the changes i made
#Override
public void onConnected(Bundle connectionHint) {
Toast.makeText(this, "API client connected" + listAllMusicFiles.get(0),
1000).show();
if (listAllMusicFiles.size() == 0) {
return;
} else {
if (count == 0) {
count++;
mcreateFolder();
}
}
}
public void mcreateFolder() {
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(
"Siddharth").build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFolder(mGoogleApiClient, changeSet)
.setResultCallback(callback);
}
final ResultCallback<DriveFolderResult> callback = new ResultCallback<DriveFolderResult>() {
#Override
public void onResult(final DriveFolderResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the folder");
return;
}
showMessage("Created a folder: "
+ result.getDriveFolder().getDriveId());
mFolderDriveId = result.getDriveFolder().getDriveId();
Drive.DriveApi.getFolder(mGoogleApiClient, mFolderDriveId)
.addChangeListener(mGoogleApiClient, mChgeLstnr);
mCnt = 0;
mPoker = new Handler();
mPoker.postDelayed(mPoke, mWait);
}
};
final private ChangeListener mChgeLstnr = new ChangeListener() {
#Override
public void onChange(ChangeEvent event) {
// showMessage("event: " + event + " resId: "
// + event.getDriveId().getResourceId());
}
};
private final Runnable mPoke = new Runnable() {
public void run() {
if (mPoker != null && mFolderDriveId != null
&& mFolderDriveId.getResourceId() == null
&& (mCnt++ < ENOUGH)) {
MetadataChangeSet meta = new MetadataChangeSet.Builder()
.build();
Drive.DriveApi
.getFolder(mGoogleApiClient, mFolderDriveId)
.updateMetadata(mGoogleApiClient, meta)
.setResultCallback(
new ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(
DriveResource.MetadataResult result) {
if (result.getStatus().isSuccess()
&& result.getMetadata()
.getDriveId()
.getResourceId() != null) {
showMessage("resId COOL "
+ result.getMetadata()
.getDriveId()
.getResourceId());
mPoker.removeCallbacksAndMessages(mPoke);
Drive.DriveApi.fetchDriveId(
mGoogleApiClient,
result.getMetadata()
.getDriveId()
.getResourceId())
.setResultCallback(
idCallback);
} else {
mPoker.postDelayed(mPoke,
mWait *= 2);
}
}
});
} else {
mPoker = null;
}
}
};
Alot many thanks to #seanpj for such a beautiful elaboration.
cannot get folderId that i just created on google drive
Unpredictable result of DriveId.getResourceId() in Google Drive Android API
I really appreciate your effort.
I have some problem with printing image to AGPtEK 58mm Mini Bluetooth Pocket POS Thermal Receipt Printer. I am trying to convert webview content into image (this is working fine) and after that I want to print it with this printer but it prints only solid black background. Here is my code:
public class PrintDemo extends Activity {
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int PERMISSIONS_REQUEST_BLUETOOTH = 1;
private static final String TAG_REQUEST_PERMISSION = "Request permission";
private static final int PERMISSIONS_REQUEST_INTERNET = 0;
private static final int PERMISSIONS_REQUEST_BT_ADMIN = 2;
private static final int PERMISSIONS_REQUEST_LOCATION = 3;
private static final String WEB_SITE = "Remembered Web Site";
private static final String IS_CHECKED = "Check box";
#Bind(R.id.btn_search)
Button btnSearch;
#Bind(R.id.btn_print)
Button btnSendDraw;
#Bind(R.id.btn_open)
Button btnSend;
#Bind(R.id.btn_close)
Button btnClose;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("State", "Connecting...");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("State", "Not found");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
String path;
File dir;
File file;
#Bind(R.id.check_box)
CheckBox checkBox;
#Bind(R.id.txt_content)
EditText edtContext;
#Bind(R.id.web_view)
WebView webView;
BluetoothService mService;
BluetoothDevice con_dev;
private SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.main);
ButterKnife.bind(this);
mService = new BluetoothService(this, mHandler);
if (!mService.isAvailable()) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDefaultTextEncodingName("utf-8");
webView.setWebViewClient(new WebViewClient() {
#SuppressLint("SdCardPath")
#Override
public void onPageFinished(final WebView view, String url) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
siteToImage(view);
}
}, 5000);
}
});
sharedPref = this.getPreferences(Context.MODE_PRIVATE);
checkPermissions();
}
private void siteToImage(WebView view) {
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap(
picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setRememberedWeb() {
if (checkBox.isChecked()) {
String rememberedWeb = sharedPref.getString(WEB_SITE, "");
if (!rememberedWeb.equals("")) {
edtContext.setText(rememberedWeb);
}
}
}
#Override
protected void onPause() {
super.onPause();
saveState(checkBox.isChecked());
}
#Override
protected void onResume() {
super.onResume();
checkBox.setChecked(load());
setRememberedWeb();
}
private void saveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(IS_CHECKED, isChecked);
if (isChecked) {
editor.putString(WEB_SITE, edtContext.getText().toString());
} else {
editor.putString(WEB_SITE, getString(R.string.txt_content));
}
editor.apply();
}
private boolean load() {
return sharedPref.getBoolean(IS_CHECKED, false);
}
private boolean checkPermissions() {
int permissionCheck =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH);
int permissionInternet =
ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET);
int permissionBTAdmin =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN);
int permissionLocation =
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bluetooth_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.BLUETOOTH)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTPermission();
}
return false;
} else if (permissionInternet == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_internet_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestInternetPermission();
}
return false;
} else if (permissionBTAdmin == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bt_admin_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTAdminPermission();
}
return false;
} else if (permissionLocation == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_location_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestLocationPermission();
}
return false;
} else {
return true;
}
}
private void requestLocationPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
private void requestBTAdminPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},
PERMISSIONS_REQUEST_BT_ADMIN);
}
private void requestInternetPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.INTERNET},
PERMISSIONS_REQUEST_INTERNET);
}
private void requestBTPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH},
PERMISSIONS_REQUEST_BLUETOOTH);
}
#Override
public void onStart() {
super.onStart();
if (!mService.isBTopen()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_print);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btn_open);
btnSend.setOnClickListener(new ClickEvent());
btnClose = (Button) this.findViewById(R.id.btn_close);
btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("TAG", ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, file.getPath());
sendData = pg.printDraw();
mService.write(sendData);
}
public void downloadContent() {
if (!edtContext.getText().toString().equals("") && !edtContext.getText().toString().equals("https://")) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(edtContext.getText().toString())
.build();
HttpService service = retrofit.create(HttpService.class);
Call<ResponseBody> result = service.getContent();
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
try {
if (response.body() != null) {
String summary = response.body().string();
webView.loadData(summary, "text/html; charset=utf-8", null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
public interface HttpService {
#GET("/")
Call<ResponseBody> getContent();
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
downloadContent();
} else if (v == btnClose) {
mService.stop();
} else if (v == btnSendDraw) {
printImage();
}
}
}
}
The result is almost what I want you can see by yourself, but the printed image is not clear:
I fixed it guys, this was the problem, the method siteToImage(). Here are the changes I hope it will helps someone:
private void siteToImage() {
webView.measure(View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
webView.setDrawingCacheEnabled(true);
webView.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(webView.getMeasuredWidth(),
webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Paint paint = new Paint();
int iHeight = b.getHeight();
c.drawBitmap(b, 0, iHeight, paint);
webView.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
b.compress(Bitmap.CompressFormat.PNG, 50, fos);
fos.flush();
fos.close();
b.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
I try to use this library https://github.com/coomar2841/image-chooser-library to load image on my application.
When I select a image, I have this message "could'nt process no such file"
My code:
public class EditListeModelActivity extends Activity implements ImageChooserListener{
EditText titre;
CheckBox isvisible;
ActionBar actionBar;
ImageView ProfileImage;
private static int RESULT_LOAD_IMAGE = 1;
private boolean imageModifie=false;
private Bitmap newImage;
Builder b;
private ProgressBar pbar;
private ImageChooserManager imageChooserManager;
private String filePath;
private int chooserType;
private String uriFile;
private Button btnValide;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_liste_model);
if(savedInstanceState!=null)
{
if (savedInstanceState.containsKey("uri_path")) {
uriFile = savedInstanceState.getString("uri_path");
}
}
actionBar = getActionBar();
actionBar.setDisplayOptions( ActionBar.DISPLAY_SHOW_HOME|ActionBar.DISPLAY_SHOW_TITLE|ActionBar.DISPLAY_SHOW_CUSTOM);
titre=(EditText)findViewById(R.id.nomEdit);
isvisible=(CheckBox)findViewById(R.id.isvisible);
btnValide=(Button)findViewById(R.id.EditListeModelNow);
ProfileImage = (ImageView) findViewById(R.id.profileImageEdit);
if(uriFile==null)
{
}
else
{
ProfileImage.setImageURI(Uri.parse(uriFile));
newImage=BitmapFactory.decodeFile(uriFile);
ProfileImage.setImageBitmap(newImage);
imageModifie=true;
}
b = new Builder(this);
b.setTitle("Choisir photo");
String[] types = {"Prendre une nouvelle photo", "Choisir une photo existante"};
b.setItems(types, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
switch(which){
case 0:
takePicture();
break;
case 1:
chooseImage();
break;
}
}
});
ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
b.show();
//chooseImage();
/*
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);*/
}
});
pbar = (ProgressBar) findViewById(R.id.progressBarEditProfile);
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_liste_model, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK
&& (requestCode == ChooserType.REQUEST_PICK_PICTURE || requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
if (imageChooserManager == null) {
reinitializeImageChooser();
}
Log.e("imageChooserManager data ",data.toString());
imageChooserManager.submit(requestCode, data);
} else {
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
}
}
#Override
public void onImageChosen(final ChosenImage image) {
runOnUiThread(new Runnable() {
#Override
public void run() {
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
if (image != null) {
File f=new File(image.getFileThumbnail());
ProfileImage.setImageURI(Uri.parse(f.toString()));
uriFile=f.toString();
newImage=BitmapFactory.decodeFile(f.toString());
ProfileImage.setImageBitmap(newImage);
imageModifie=true;
}
}
});
}
#Override
public void onError(final String reason) {
runOnUiThread(new Runnable() {
#Override
public void run() {
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
Toast.makeText(EditListeModelActivity.this, reason,
Toast.LENGTH_LONG).show();
}
});
}
// Should be called if for some reason the ImageChooserManager is null (Due
// to destroying of activity for low memory situations)
private void reinitializeImageChooser() {
imageChooserManager = new ImageChooserManager(this, chooserType,
"myfolder", true);
imageChooserManager.setImageChooserListener(this);
imageChooserManager.reinitialize(filePath);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("chooser_type", chooserType);
outState.putString("media_path", filePath);
outState.putString("uri_path", uriFile);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("chooser_type")) {
chooserType = savedInstanceState.getInt("chooser_type");
}
if (savedInstanceState.containsKey("media_path")) {
filePath = savedInstanceState.getString("media_path");
}
if (savedInstanceState.containsKey("uri_path")) {
uriFile = savedInstanceState.getString("uri_path");
}
}
}
private void takePicture() {
chooserType = ChooserType.REQUEST_CAPTURE_PICTURE;
imageChooserManager = new ImageChooserManager(this,
ChooserType.REQUEST_CAPTURE_PICTURE, "myfolder", true);
imageChooserManager.setImageChooserListener(this);
try {
pbar.setVisibility(View.VISIBLE);
ProfileImage.setVisibility(View.GONE);
filePath = imageChooserManager.choose();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void chooseImage() {
chooserType = ChooserType.REQUEST_PICK_PICTURE;
imageChooserManager = new ImageChooserManager(this,
ChooserType.REQUEST_PICK_PICTURE, "myfolder", true);
imageChooserManager.setImageChooserListener(this);
try {
pbar.setVisibility(View.VISIBLE);
ProfileImage.setVisibility(View.GONE);
filePath = imageChooserManager.choose();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
At ligne `Log.e("imageChooserManager data ",data.toString());
the result is
Intent { dat=content://com.android.providers.media.documents/document/image:22501 flg=0x1 }
I think that the probleme is where is stoked my image. How I do to load my image in my application?
That is a Uri. A Uri is not a file, and so you cannot pass it to decodeFile() on BitmapFactory. Either use an image loading library like Picasso or Universal Image Loader, or have your own background thread that uses openInputStream() on a ContentResolver to read in the contents of that Uri, passing the stream to decodeStream() on BitmapFactory.
I want to get File Or Folder ID when that file is changed from the web. I gone through Documentation Listening for Change Events Git Hub Demo But i am not able to implement it.
In my app i am trying to listen to changes and modify those changes to local files also (sync).
In this test code i am just creating a folder and attaching a listner to the folder.
but when i rename folder from web Listner in not listening why?
1>I tried with this code
DriveId ddid = sky.getDriveFolder().getDriveId();
DriveFolder df = Drive.DriveApi.getFolder(mGoogleApiClient, ddid);
df.addChangeListener(getGoogleApiClient(), changeListener2);
2> And also with this line
DriveFolderResult sky = Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet).await();
sky.getDriveFolder().addChangeListener(getGoogleApiClient(), changeListener2);
class file.
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private static final int PICKFILE_RESULT_CODE = 1;
private ContentsResult contentsresult;
private GoogleApiClient mGoogleApiClient;
String EXISTING_FILE_ID = "";
int folderCreated = 0;
SharedPreferences prefs;
ArrayList<String> dbfileid = new ArrayList<String>();
ArrayList<String> dbfilename = new ArrayList<String>();
String fdd="";
DriveFolderResult sky;
private DriveId mFolderDriveId;
String isfolder;
SharedPreferences sp;
String Shared="Shared";
String folderid="";
int j=0;
String songfileid="";
String realid ="";
#Override
protected void onResume() {
super.onResume();
initDrive();
}
private void initDrive() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(com.google.android.gms.drive.Drive.API)
.addScope(com.google.android.gms.drive.Drive.SCOPE_FILE).setAccountName("shivrajp130#gmail.com")
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
if (!result.hasResolution()) {
// show the localized error dialog.
showToast("Error in on connection failed");
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
showToast("error" + e.toString());
}
}
#Override
public void onConnected(Bundle connectionHint) {
showToast("Inside Connected");
sp = getSharedPreferences(Shared, Context.MODE_PRIVATE);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showToast("Thread Started");
createSkyFolder();
}
});
t.start();
}
private void createSkyFolder()
{
// TODO Auto-generated method stub
try
{
showToast("creating Folder");
if(!sp.getString(isfolder, "false").contains("created"))
{
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().
setTitle("Sky folder").build();
sky = Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet).await();
sky.getDriveFolder().addChangeListener(getGoogleApiClient(), changeListener2);
showToast("folder created");
sp.edit().putString(isfolder, "created").commit();
// To store secret ID string of file or folder so that we can later get a DriveId object.
realid = sky.getDriveFolder().getDriveId().encodeToString();
sp.edit().putString(folderid, realid).commit();
showToast("Real== "+realid);
}
Status s = Drive.DriveApi.requestSync(mGoogleApiClient).await();
if(s.isSuccess())
{
showToast("Success");
}
}
#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
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast,
Toast.LENGTH_SHORT).show();
}
});
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
final private Listener<ChangeEvent> changeListener2 = new Listener<ChangeEvent>() {
#Override
public void onEvent(ChangeEvent event) {
showToast("Listening now");
showToast(String.format("The New Id Is %s", event.hasMetadataChanged()));
}
};
#Override
public void onConnectionSuspended(int cause) {
showToast("GoogleApiClient connection suspended");
}
}
Please provide any code snippet for the same.