how to download a video from Google drive? [closed] - android

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I can download video and image, but it was not playable (file format isn't supported, or is the file corrupted?).
I get stuck to get the playable video from google drive.
Any help is appreciable.
-My button onclick to intent google drive.
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClickOpenFile(v);
}
});
public void onClickOpenFile(View view) {
fileOperation = false;
// create new contents resource
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(driveContentsCallback);
}
Open list of folder and file of the Google Drive
public void OpenFileFromGoogleDrive() {
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"image/jpeg", "image/png", "video/mp4"
, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Unable to send intent", e);
}
}
final ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (result.getStatus().isSuccess()) {
OpenFileFromGoogleDrive();
}
}
};
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK) {
video_url = "https://drive.google.com/open?id=" + mFileId.getResourceId();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(video_url));
startActivity(i);
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}

Related

Open a default folder path in Android?

Issue:
Office is a folder in internal memory of Android.
Clicking a button in screen should always take one to default folder, Office.
Appreciate help as no accepted answers found.
In onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null)
return;
if (requestCode == viewfilerequestcode){
Uri Fileuri = data.getData();
String DFLocation="/mnt/sdcard/Office/";
String FilePath="";
if (FilePath.trim().equals(DFLocation.concat(GettheFilename(Fileuri))))
{
FilePath = DFLocation.concat(GettheFilename(Fileuri));
}
......
.......
........
}
.........
..........
}
Intent start:
btnview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent;
String[] mimestoview =
{"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx };
fileintent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
fileintent.setType("*/*");
fileintent.putExtra(Intent.EXTRA_MIME_TYPES, mimestoview );
fileintent.addCategory(Intent.CATEGORY_OPENABLE);
fileintent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
fileintent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivityForResult(fileintent, viewfilerequestcode);
} catch (ActivityNotFoundException e) {
lbl.setText("No activity to handle picking a file. Showing alternatives.");
}
}
});

"Bad notification for startForeground" error when using android-upload-service [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I don't know why I'm getting this error because I haven't actually used any notifications channels in my app and I don't intend to do.
Can somebody help me fix this?
Error:
2019-12-10 16:58:03.151 9542-9542/com.example.demoproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.demoproject, PID: 9542
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: null
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1894)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
Activity:
public class File_upload extends AppCompatActivity {
Button SelectButton, UploadButton;
EditText PdfNameEditText ;
Uri uri;
String username;
public static final String PDF_UPLOAD_HTTP_URL = "https://depcollproj.000webhostapp.com/FileUpload.php";
public int PDF_REQ_CODE = 1;
String PdfNameHolder, PdfPathHolder, PdfID;
#Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(getApplicationContext(),TeacherView.class);
setIntent.putExtra("username",username);
startActivity(setIntent);
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_upload);
AllowRunTimePermission();
Intent i=getIntent();
username=i.getStringExtra("username");
SelectButton = (Button) findViewById(R.id.button);
UploadButton = (Button) findViewById(R.id.button2);
PdfNameEditText = (EditText) findViewById(R.id.editText);
SelectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// PDF selection code start from here .
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PDF_REQ_CODE);
}
});
UploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PdfUploadFunction();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PDF_REQ_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
SelectButton.setText("PDF is Selected");
}
}
public void PdfUploadFunction() {
PdfNameHolder = PdfNameEditText.getText().toString().trim();
PdfPathHolder = FilePath.getPath(this, uri);
if (PdfPathHolder == null) {
Toast.makeText(this, "Please move your PDF file to internal storage & try again.", Toast.LENGTH_LONG).show();
} else {
try {
PdfID = UUID.randomUUID().toString();
new MultipartUploadRequest(this, PdfID, PDF_UPLOAD_HTTP_URL)
.addFileToUpload(PdfPathHolder, "pdf")
.addParameter("name", PdfNameHolder)
//.addParameter("username",username)
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(5)
.startUpload();
Toast.makeText(this, " Upload Successful ", Toast.LENGTH_SHORT).show();
Log.d("Upload Procedure", "PdfUploadFunction: -------"+PdfNameHolder+username);
}
catch (Exception exception) {
Log.d("Upload Procedure", "PdfUploadFunction: Fail");
Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
public void AllowRunTimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(File_upload.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(File_upload.this,"READ_EXTERNAL_STORAGE permission Access Dialog", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(File_upload.this,new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] Result) {
switch (RC) {
case 1:
if (Result.length > 0 && Result[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(File_upload.this,"Permission Granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(File_upload.this,"Permission Canceled", Toast.LENGTH_LONG).show();
}
break;
}
}
}
Could you please try the answer below
Try to update this:
new MultipartUploadRequest(this, PdfID, PDF_UPLOAD_HTTP_URL)
.addFileToUpload(PdfPathHolder, "pdf")
.addParameter("name", PdfNameHolder)
//.addParameter("username",username)
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(5)
.startUpload();
To this:
MultipartUploadRequest uploadRequest = new MultipartUploadRequest(this, PdfID, PDF_UPLOAD_HTTP_URL)
.addFileToUpload(PdfPathHolder, "pdf")
.addParameter("name", PdfNameHolder)
//.addParameter("username",username)
.setMaxRetries(5);
// For Android > 8, we need to set an Channel to the UploadNotificationConfig.
// So, here, we create the channel and set it to the MultipartUploadRequest
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("Upload", "Upload service", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
UploadNotificationConfig notificationConfig = new UploadNotificationConfig();
notificationConfig.setNotificationChannelId("Upload")
uploadRequest.setNotificationConfig(notificationConfig)
} else {
// If android < Oreo, just set a simple notification (or remove if you don't wanna any notification
// Notification is mandatory for Android > 8
uploadRequest.setNotificationConfig(new UploadNotificationConfig())
}
uploadRequest.startUpload();
Reason
Issue is happening because that Upload library you have starts a service. On Android 8, foreground services need a notification and those notifications need a channel. When you use setNotificationConfig(new UploadNotificationConfig()), you are setting the notification but you are not adding setting any channel leading the crash you are observing.
So, in order to fix, you must create UploadNotificationConfig, set a notification channel then, you can set it to the upload request. Start the upload only after that.
EDIT
The channel ID logic was added on version 3.4 of that library. So, you must update your build.gradle to use the version 3.4 at least.
implementation 'net.gotev:uploadservice:3.4'

Google Drive integration - edit, delete, download and update with my Android app

I have implemented Google Drive with my Android application. I am able to view all my files in the app. Now I want to implement delete and update of google drive files.
This is my current code:
public void OpenFileFromGoogleDrive() {
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"text/plain", "text/html"})
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
}
catch (SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
}
final ResultCallback<DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (result.getStatus().isSuccess()) {
OpenFileFromGoogleDrive();
}
}
};
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK) {
mFileId = (DriveId) data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
Log.e("file id", mFileId.getResourceId() + ""); // 0B-KGM98PVf2SdkdYTFRXZlNjSjg
/*String url = "https://drive.google.com/open?id="+ mFileId.getResourceId();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);*/
options();
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
How to delete and update files using DriveId?
You can achieve this doing:
driveFile = Drive.DriveApi.getFile(mGoogleApiClient,
DriveId.decodeFromString(driveIdStr));
// Call to delete file.
driveFile.delete(mGoogleApiClient).setResultCallback(deleteCallback);
Check google drive documentation for more info https://developers.google.com/drive/android/trash?hl=es-419
In addition to #AndroidRuntimeException's answer, you may want to check this Working with File Contents documentation and this Google Drive Android API Demos.
To edit a file:
/**
* An activity to illustrate how to edit contents of a Drive file.
*/
public class EditContentsActivity extends BaseDemoActivity {
private static final String TAG = "EditContentsActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
final 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;
}
DriveId driveId = result.getDriveId();
DriveFile file = driveId.asDriveFile();
new EditContentsAsyncTask(EditContentsActivity.this).execute(file);
}
};
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
.setResultCallback(idCallback);
}
To delete a file:
/**
* An activity to illustrate how to delete contents of a Drive file.
*/
driveFile = Drive.DriveApi.getFile(mGoogleApiClient,
DriveId.decodeFromString(driveIdStr));
// Call to delete file.
driveFile.delete(mGoogleApiClient).setResultCallback(deleteCallback);
Hope this helps!

Android: How can I access a spreadsheet with the google-drive-sdk?

I am working on an android app, which should be able to read a spreadsheet from google drive. However, every time when I try to open a file from google drive I get following message from the DriveContentsResult: "No content is available for this file".
Here is my code, after I got the authorization for google drive via the GoogleApiClient:
private static final int REQUEST_RESOLVE_ERROR = 1001;
public static final int REQUEST_CODE_OPENER = 1002;
private DriveId mSelectedFileDriveId;
public GoogleApiClient mGoogleApiClient;
public void getGoogleDriveFile(View view){
if(mGoogleApiClient.isConnected()){
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[] {"application/vnd.google-apps.spreadsheet"})
.build(mGoogleApiClient);
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.d(TAG, "Unable to send intent" + e);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult");
if (requestCode == REQUEST_RESOLVE_ERROR) {
...
} else if(requestCode == REQUEST_CODE_OPENER){
if(resultCode == RESULT_OK){
mSelectedFileDriveId = (DriveId) data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
if(mSelectedFileDriveId != null){
open();
}
}
}
}
private void open() {
Drive.DriveApi.getFile(mGoogleApiClient, mSelectedFileDriveId)
.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null)
.setResultCallback(driveContentsCallback);
}
private ResultCallback<DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.d(TAG, "Error while opening the file contents " + result.getStatus().getStatusMessage());
return;
}
DriveContents contents = result.getDriveContents();
}
};
Content here refers to binary content. Google Spreadsheets (and the other Google Docs types) are not stored as binary content. The Android-specific API doesn't currently support reading Spreadsheet contents.
Using the RESTful API, you can get it in a binary format like csv using the ExportLinks.
use the "google spreadsheets api" (REST) not drive api.

Android file chooser [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I want to make a file uploader. And I hence I need a file chooser but I don't want to write this by myself. I find OI file manager and I think it suits me.
But how can I force user to install OI file manager?
If I cannot , is there a better way to include a file manager in my app?
Thx
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri in onActivityResult() like so:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath() method in my FileUtils.java is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:
My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.
private void startCreation(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
intent.setDataAndType(startDir,
"vnd.android.cursor.dir/lysesoft.andexplorer.file");
intent.putExtra("browser_filter_extension_whitelist", "*.csv");
intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
intent.putExtra("browser_title_background_color",
getText(R.string.browser_title_background_color));
intent.putExtra("browser_title_foreground_color",
getText(R.string.browser_title_foreground_color));
intent.putExtra("browser_list_background_color",
getText(R.string.browser_list_background_color));
intent.putExtra("browser_list_fontscale", "120%");
intent.putExtra("browser_list_layout", "2");
try{
ApplicationInfo info = getPackageManager()
.getApplicationInfo("lysesoft.andexplorer", 0 );
startActivityForResult(intent, PICK_REQUEST_CODE);
} catch( PackageManager.NameNotFoundException e ){
showInstallResultMessage(R.string.error_install_andexplorer);
} catch (Exception e) {
Log.w(TAG, e.getMessage());
}
}
This methos is just pick up a dialog and if user wants install the external application from market
private void showInstallResultMessage(int msg_id) {
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setMessage(getText(msg_id));
dialog.setButton(getText(R.string.button_ok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setButton2(getText(R.string.button_install),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
startActivity(intent);
finish();
}
});
dialog.show();
}

Categories

Resources