I am downloading images form URL and saving them in pictures directory in folder name unsplash. Now if a user has already downloaded an image I want to show an alert dialog that picture has already been downloaded and if the user wants to download it again. Please help me through it how can I do that.
downloadBtn.setOnClickListener {
if (ContextCompat.checkSelfPermission(
baseContext,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
== PackageManager.PERMISSION_GRANTED
) {
startDownloading(list,position)
} else {
requestDownloadPermission()
}
}
private fun requestDownloadPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
) {
val dialog = AlertDialog.Builder(this)
dialog.setTitle("Permission Required")
dialog.setMessage("Permission Required for downloading this picture." +
"Please go to settings for accessing permission")
dialog.setPositiveButton("Go to setting") { _: DialogInterface, _: Int ->
val openURL = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
openURL.data = Uri.fromParts("package", packageName, null)
startActivity(openURL)
}
dialog.setNegativeButton("cancel") { _: DialogInterface, _: Int -> }
dialog.show()
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
STORAGE_PERMISSION_CODE
)
}
}
private fun startDownloading(list: ArrayList<ImageModel>, position: Int) {
Toast.makeText(this, "Downloading", Toast.LENGTH_SHORT).show()
val downloadList = list[position].urls.raw
val request = DownloadManager.Request(Uri.parse(downloadList))
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_PICTURES,
"/unsplash/${list[position].id}.jpg"
)
.setTitle("Unsplash Images").setAllowedOverMetered(true)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
val manager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
myId = manager.enqueue(request)
var br = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
var id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
if (id == myId) {
Toast.makeText(baseContext, "Downloaded Successfully", Toast.LENGTH_SHORT)
.show()
}
}
}
registerReceiver(br, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
val list = intent.getStringArrayListExtra("FULLIMAGELIST") as ArrayList<ImageModel>
val position = intent.getIntExtra("POSITION", 0)
startDownloading(list,position)
}
} else {
Toast.makeText(baseContext, "Permission Denied", Toast.LENGTH_SHORT).show()
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
Related
I developed two application, one is a LAUNCHER the other one is the MAIN-APP.
I my MAIN-APP the user can choose the language.
I would like to change automatically the language also in my LAUNCHER.
I would like to create a txt file in Documents folder from my MAIN-APP, so the LAUNCHER can read this file and set the same language.
But now in Android 11 seems impossible to create a file TXT in the Documents folder and read this file from another application.
I tried with MediaStore:
MAIN APP :
private static void saveLanguageOnFile(String lang, String country){
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
File folderDocuments = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
boolean success;
if (!folderDocuments.exists()) {
try {
folderDocuments.mkdir();
} catch (Exception ex) {
ex.printStackTrace();
}
}
success = folderDocuments.exists();
if (success) {
try {
FileOutputStream fos = new FileOutputStream(new File(folderDocuments, "language.txt"));
fos.write((lang + "-" + country).getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Uri contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
ContentResolver contentResolver = ActivitiesManager.getInstance().getTopActivity().getApplication().getApplicationContext().getContentResolver();
String selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?";
String[] selectionArgs = new String[]{Environment.DIRECTORY_DOCUMENTS+"/"};
Cursor cursor = contentResolver.query(contentUri, null, selection, selectionArgs, null);
long idFile = -1;
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
int columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
if (columnIndexDisplayName > 0 && columnIndexId > 0) {
String fileName = cursor.getString(columnIndexDisplayName);
if (fileName.equals("language.txt")) {
idFile = cursor.getLong(columnIndexId);
break;
}
}
}
cursor.close();
}
Uri uriFile;
if (idFile > -1) {
uriFile = ContentUris.withAppendedId(contentUri, idFile);
} else {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, "language.txt"); // file name
values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS);
uriFile = contentResolver.insert(contentUri, values);
}
try {
if (uriFile != null) {
OutputStream outputStream = contentResolver.openOutputStream(uriFile, "rwt");
if (outputStream != null) {
outputStream.write((lang + "-" + country).getBytes());
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ANDROID LAUNCHER APP :
private fun setLanguage() {
var lang = Locale.getDefault().language
var country = Locale.getDefault().country
val previousLang = lang
val previousCountry = country
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
val language = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),"language.txt")
if (language.exists()) {
try {
val br = BufferedReader(FileReader(language))
var st: StringTokenizer
var line: String?
while (br.readLine().also { line = it } != null) {
st = StringTokenizer(line, "-")
lang = st.nextToken()
country = st.nextToken()
}
br.close()
} catch (e: IOException) {
Log.e("LauncherDMD", ".loadFile: err: " + e.message)
}
}
} else {
val contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val contentResolver: ContentResolver = application.applicationContext.contentResolver
val selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?"
val selectionArgs = arrayOf(Environment.DIRECTORY_DOCUMENTS+"/")
val orderBy = MediaStore.MediaColumns.DATE_ADDED + " DESC"
val cursor = contentResolver.query(contentUri, null, selection, selectionArgs, orderBy)
var idFile: Long = -1
if (cursor != null && cursor.count > 0) {
while (cursor.moveToNext()) {
val columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
val columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID)
if (columnIndexDisplayName > 0 && columnIndexId > 0) {
val fileName = cursor.getString(columnIndexDisplayName)
if (fileName.contains("language")) {
idFile = cursor.getLong(columnIndexId)
break
}
}
}
cursor.close()
}
val uriFile: Uri
if (idFile > -1) {
uriFile = ContentUris.withAppendedId(contentUri, idFile)
try {
val br = BufferedReader(InputStreamReader(getContentResolver().openInputStream(uriFile), "UTF-8"))
var st: StringTokenizer
var line: String?
while (br.readLine().also { line = it } != null) {
st = StringTokenizer(line, "-")
lang = st.nextToken()
country = st.nextToken()
}
br.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
val locale = Locale(lang,country)
Lingver.getInstance().setLocale(this.applicationContext, locale)
if(!previousCountry.equals(country) && !previousLang.equals(lang)){
recreate()
}
Log.i("LauncherDMD", "Utility: Nuova lingua impostata: $lang")
Log.i("LauncherDMD", "Utility: Nuova nazione impostata: $country")
}
This solution works BUT the problem is that every time the MAIN-APP is uninstalled and installed again (sometimes it happens), it cannot access to the language file previously created by itself and instead it create a duplicate.
I obviously I cannot delete the old language file before creating new ones.
I also know that I cannot use the special permission "MANAGE_EXTERNAL_STORAGE" because I have to publish the app on the play store.
Thanks in advance!
I have an issue where I am calling a function, it's appending an array, and then I get a random element from it, the problem is that is keeps getting wiped right after the function is called before I can use it, therefore, the random element request is causing a fatal error.
Utilities.getKnockKnockJokes {
self.previousKnockKnockJoke = self.currentKnockKnockJoke
print("currentKnockKnockJoke = \(self.currentKnockKnockJoke)")
self.currentKnockKnockJoke = KnockKnockJokes.knockKnockJokes.randomElement()!
print("newCurrentKnockKnockJoke = \(self.currentKnockKnockJoke)")
self.singleServeText.text = self.currentKnockKnockJoke
}
The function called is below:
static func getKnockKnockJokes(completion: #escaping () -> Void) {
let db = Firestore.firestore()
let group = DispatchGroup()
group.enter()
DispatchQueue.global(qos: .background).async {
print("countKnockKnockJokes = \(self.countKnockKnockJokes)")
if self.countKnockKnockJokes == 0 {
while self.countKnockKnockJokes == 0 {
if self.countKnockKnockJokes == 0 {
self.countKnockKnockJokes = 1
group.leave()
}else {
print("leaving")
group.leave()
}
}
}else {
print("skipped")
group.leave()
}
}
group.notify(queue: .main) {
db.collection("jokes").document("Knock Knock Jokes").addSnapshotListener { document, error in
//check for error
if error == nil {
//check if document exists
if document != nil && document!.exists {
if let JokeNum = document!.get("JokeNum") as? Int {
self.countKnockKnockJokes = JokeNum
UserDefaults.standard.setValue(JokeNum, forKey: "countKnockKnockJokes")
print("KnockKnockJokeNum = \(self.countKnockKnockJokes)")
}
var count = 1
print("count = \(count)/\(self.countKnockKnockJokes)")
print("countKnockKnockJoke = \(self.countKnockKnockJokes)")
//Utilities.knockKnockJokes.removeAll()
KnockKnockJokes.knockKnockJokes.removeAll()
for _ in 0...self.countKnockKnockJokes {
print("count = \(count)/\(self.countKnockKnockJokes)")
if let Joke = document!.get("\(count)") as? String {
print("KnockKnockJokeNum = \(self.countKnockKnockJokes)")
if Utilities.jokes.contains("\(Joke) - From Knock Knock Jokes") {}else {
print("Joke = \(Joke)")
Utilities.jokes.append("\(Joke) - From Knock Knock Jokes")
KnockKnockJokes.knockKnockJokes.append(Joke)
print("KnockKnockJokes = \(KnockKnockJokes.knockKnockJokes)")
UserDefaults.standard.set(KnockKnockJokes.knockKnockJokes, forKey: defaults.knockKnockJokes.rawValue)
Utilities.updateJokesDefaults()
}
print("countKnockKnockFinal = \(count)/\(self.countKnockKnockJokes)")
if count == self.countKnockKnockJokes {
completion()
}
count = count + 1
}
}
}
}
}
}
}
try this:
if count == self.countKnockKnockJokes {
completion()
return // <--- here
}
I fixed it, my remove all was running after all the appends.
Before last Android 11 update, I used to get the file path of my external image to display it on Glide. Because of the last update, I now need to use MediaStore storage option to store my images in external. I successfully save my images but I have a problem retrieving it and displaying it on glide.
I tried to use the code from this question to get the uri :
public Uri getUriFromContentResolver(String fileName) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getApplicationContext().getContentResolver();
Cursor queryCursor = resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.RELATIVE_PATH}, MediaStore.Images.Media.DISPLAY_NAME + "=? ",
new String[]{fileName}, null);
if (queryCursor != null && queryCursor.moveToFirst()) {
return ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, queryCursor.getLong(0));
} else {
return null;
}
} else {
return null;
}
}
And retrieve it to display it on glide :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Uri uriFromContentResolver = new ImageManager(context).getUriFromContentResolver(listPicture.get(pos).getFileName());
if (uriFromContentResolver !=null) {
System.out.println("Uri " + uriFromContentResolver.toString());
Glide.with(context)
.load(uriFromContentResolver)
.placeholder(R.drawable.ic_baseline_person_24_black)
.into(pictureGallery);
}
} else {
Glide.with(context)
.load(listPicture.get(pos).getPath())
.placeholder(R.drawable.ic_baseline_person_24_black)
.into(pictureGallery);
}
I also tested glide to load with the path from uri.getPath() when I save the file using this :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
String path = imageUri.getPath();
I'm not used to the MediaStore system, I will take any advice. Thanks.
I created a class to get the Uri of the file by using the file name
Uri uriFromContentResolver = getUriFromContentResolver(fileName);
public Uri getUriFromContentResolver(String fileName) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getApplicationContext().getContentResolver();
Cursor queryCursor = resolver.query(
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL),
new String[]{
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.RELATIVE_PATH},
MediaStore.Images.Media.DISPLAY_NAME + " = ?",
new String[]{fileName}, null);
if (queryCursor != null && queryCursor.moveToFirst())
{
return ContentUris.withAppendedId(
MediaStore.Images.Media.getContentUri(
MediaStore.VOLUME_EXTERNAL),
queryCursor.getLong(0));
} else
{
return null;
}
} else {
return null;
}
}
Once we have it we call this function with the Uri we just got to get a Path
String path = getRealPathFromURI(uriFromContentResolver);
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(context, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
And with this path, Glide can read the file
Glide.with(context)
.load(path)
.placeholder(R.drawable.ic_baseline_person_24_black)
.into(pictureGallery);
I am new to Google Drive and have following scenarios for which I am not able to find anything (not sure if anything exists or not)
–> I am creating a Windows app which will be SAAS based. Different Users will register and create their company logins and subusers under them. Now I want them to put the google drive credentials in one of the form and this should work for rest of the users. Currently the problem is that while development I got the google log in done and it never asks for the login again but when testing on a different system with different login, it keeps asking for google login. I simply want admin users to put their google drive credentials and it should work for upload and download files for all the users for that company.
–> I want to keep versions of the same file (just like google drive does by default) on google drive. Lets say user A uploaded file xyz and then user B downloaded and changed file xyz and uploaded it on the drive again.
I want 2 things here – only the changed content should get uploaded and not the whole file (this will save time for the user)
2ndly I want to have history of the same file so I can show in my Windows application
#region Get Service Object
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "GoogleDriveClientID",
ClientSecret = "GoogleDriveClientSecret"
},
new[] { DriveService.Scope.Drive }, "user", CancellationToken.None).Result;
// Create the service.
service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "AppName",
});
#endregion
#region Uploading
public void uploadOnGoogleDrive(ObservableCollection<JobAttachments> AttachmentsColl, bool IsDocSaved)
{
try
{
service = getServiceObject();
List<Google.Apis.Drive.v2.Data.File> fileList = retrieveAllFiles(service);
List<Google.Apis.Drive.v2.Data.File> directoryList = GetDirectoryList(service);
if (IsDocSaved)
{
#region for checking if the file already exists
foreach (Google.Apis.Drive.v2.Data.File item in fileList)
{
foreach (JobAttachments attach in AttachmentsColl)
{
if (item.Title == attach.AttachmtGUID)
{
MessageBoxResult result = System.Windows.MessageBox.Show(LogMessages.GetResourceMessage(LogMessages.MessageEnumeration.GD_AlreadyExistsMsg), "Confirmation", MessageBoxButton.YesNoCancel);
if (result == MessageBoxResult.Yes)
{
//DeleteFile(service, item);
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
body.Title = attach.AttachmtGUID;
body.MimeType = item.MimeType;
fileSize = body.FileSize;
byte[] byteArray = System.IO.File.ReadAllBytes(attach.AttachmentName);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.UpdateMediaUpload request = service.Files.Update(body, item.Id, stream, item.MimeType);
request.Upload();
}
else
{
return;
}
break;
}
}
}
#endregion
}
else
{
#region for direct uploading on google drive
if (AttachmentsCollection != null && AttachmentsCollection.Count > 0)
{
string folderID = string.Empty;
if (_IsProject)
{
if (directoryList != null && directoryList.Count > 0)
{
foreach (var dir in directoryList)
{
if (dir.Title.Equals(_ProjectName))
{
folderID = dir.Id;
break;
}
}
}
if (string.IsNullOrEmpty(folderID))
{
Google.Apis.Drive.v2.Data.File foldbody = new Google.Apis.Drive.v2.Data.File();
foldbody.Title = _ProjectName;
foldbody.MimeType = "application/vnd.google-apps.folder";
foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
Google.Apis.Drive.v2.Data.File file = service.Files.Insert(foldbody).Execute();
folderID = file.Id;
}
}
else
{
//project folder
string prjFolder = string.Empty;
string tskFolder = string.Empty;
Google.Apis.Drive.v2.Data.File foldbody;
if (directoryList != null && directoryList.Count > 0)
{
foreach (var dir in directoryList)
{
if (dir.Title.Equals(_ProjectName))
{
prjFolder = dir.Id;
break;
}
}
}
if (string.IsNullOrEmpty(prjFolder))
{
foldbody = new Google.Apis.Drive.v2.Data.File();
foldbody.Title = _ProjectName;
foldbody.MimeType = "application/vnd.google-apps.folder";
foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
Google.Apis.Drive.v2.Data.File file = service.Files.Insert(foldbody).Execute();
prjFolder = file.Id;
}
//task folder
if (directoryList != null && directoryList.Count > 0)
{
foreach (var dir in directoryList)
{
if (dir.Title.Equals(_TaskName) && dir.Parents[0].Id.Equals(prjFolder))
{
folderID = dir.Id;
break;
}
}
}
if (string.IsNullOrWhiteSpace(folderID))
{
foldbody = new Google.Apis.Drive.v2.Data.File();
foldbody.Title = _TaskName;
foldbody.MimeType = "application/vnd.google-apps.folder";
foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = prjFolder } };
Google.Apis.Drive.v2.Data.File file1 = service.Files.Insert(foldbody).Execute();
folderID = file1.Id;
}
}
foreach (JobAttachments item in AttachmentsColl)
{
if (!string.IsNullOrEmpty(item.AttachmentName))
{
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
body.Title = item.AttachmtGUID;
body.MimeType = item.MimeType;
body.Parents = new List<ParentReference>() { new ParentReference() { Id = folderID } };
//fileSize = body.FileSize;
byte[] byteArray = System.IO.File.ReadAllBytes(item.AttachmentName);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, item.MimeType);
request.Upload();
}
}
}
#endregion
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
throw ex.InnerException;
}
}
#endregion
#region Download File
private async Task DownloadFile(DriveService service, string url, string title, long? fSize)
{
service = getServiceObject();
var downloader = new MediaDownloader(service);
//downloader.ChunkSize = 256 * 1024;
downloader.ProgressChanged += Download_ProgressChanged;
var fileName = string.Empty;
//for downloading on system
var SaveFileDialog = new SaveFileDialog();
SaveFileDialog.Title = "Save As";
SaveFileDialog.FileName = title;
Nullable<bool> result = SaveFileDialog.ShowDialog();
if (result == true)
fileName = SaveFileDialog.FileName;
else if (result == false)
{
prgrsBar.StyleSettings = new ProgressBarStyleSettings();
prgrsBar.Value = 0;
return;
}
else
{
if (Directory.Exists(#"\Downloads"))
fileName = #"\Downloads\" + title;
}
if (!string.IsNullOrWhiteSpace(fileName))
using (var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
fileSize = fSize;
var progress = await downloader.DownloadAsync(url, fileStream);
if (progress.Status.ToString() == DownloadStatus.Completed.ToString())
{
fName = fileStream.Name;
prgrsBar.StyleSettings = new ProgressBarStyleSettings();
prgrsBar.Value = 0;
fileStream.Flush();
}
if (progress.Status.ToString() == DownloadStatus.Failed.ToString())
{
HandleDocuments.IsEditButtonClicked = false;
MessageBox.Show("Failed......." + progress.Exception.Message);
}
}
}
#endregion
#region Delete File
private Task DeleteFile(DriveService service, Google.Apis.Drive.v2.Data.File file)
{
service = getServiceObject(); //comment this if calling from another function; create the service object in that function and pass it as parameter to this function.
service.Files.Delete(file.Id).ExecuteAsync();
service.Files.EmptyTrash();
return null;
}
#endregion
#region Get all Directories and Files from Google Drive
public List<Google.Apis.Drive.v2.Data.File> GetDirectoryList(DriveService service)
{
//Creating the global list
List<Google.Apis.Drive.v2.Data.File> AllDirectories = new List<Google.Apis.Drive.v2.Data.File>();
//setting up the Request.
FilesResource.ListRequest request = service.Files.List();
//MaxResults: How many we want back at a time max is 1000
request.MaxResults = 1000;
//Q: Search results. all i want are folders that havent been trashed (deleted)
request.Q = "mimeType='application/vnd.google-apps.folder' and trashed=false";
do
{
try
{
// getting the results
FileList files = request.Execute();
// adding the results to the list.
AllDirectories.AddRange(files.Items);
// If there are more results then your MaxResults you will have a nextPageToken to get the rest of the results.
request.PageToken = files.NextPageToken;
}
catch (Exception ex)
{
request.PageToken = null;
if (ex.InnerException != null)
throw ex.InnerException;
}
} while (!String.IsNullOrEmpty(request.PageToken));
List<Google.Apis.Drive.v2.Data.File> DirsInRoot = AllDirectories.Where(a => (a.Parents.Count > 0 && a.Parents.FirstOrDefault().IsRoot.HasValue) ? a.Parents.FirstOrDefault().IsRoot.Value : false).ToList<Google.Apis.Drive.v2.Data.File>();
List<string> HirearcyList = new List<string>();
// The first Dir is Root it doesnt get returned. But we need it if we
// Want to be able to list the files that are in the root dir.
HirearcyList.Add("Root");
// recersive magic here.
foreach (Google.Apis.Drive.v2.Data.File myDir in DirsInRoot)
{
HirearcyList.Add(" " + myDir.Title);
HirearcyList.AddRange(RecsiveDir(AllDirectories, myDir.Id, " "));
}
return AllDirectories;
}
public List<String> RecsiveDir(List<Google.Apis.Drive.v2.Data.File> allDirs, string ParentId, string Prefix)
{
List<string> result = new List<string>();
List<Google.Apis.Drive.v2.Data.File> DirsInParentId = allDirs.Where(a => (a.Parents.Count > 0 && a.Parents.FirstOrDefault().IsRoot.HasValue) ? a.Parents.FirstOrDefault().Id == ParentId : false).ToList<Google.Apis.Drive.v2.Data.File>();
foreach (Google.Apis.Drive.v2.Data.File myDir in DirsInParentId)
{
result.Add(Prefix + myDir.Title);
result.AddRange(RecsiveDir(allDirs, myDir.Id, Prefix + " "));
}
return result;
}
public static List<Google.Apis.Drive.v2.Data.File> retrieveAllFiles(DriveService service)
{
List<Google.Apis.Drive.v2.Data.File> result = new List<Google.Apis.Drive.v2.Data.File>();
FilesResource.ListRequest request = service.Files.List();
request.MaxResults = 1000;
do
{
try
{
FileList files = request.Execute();
result.AddRange(files.Items);
request.PageToken = files.NextPageToken;
//service.Revisions.List(files.Items[0].Id) // for getting the file Revision history
}
catch (Exception ex)
{
request.PageToken = null;
if (ex.InnerException != null)
throw ex.InnerException;
}
} while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
#endregion
Thanks
Jatinder
I am creating a demo application using wpf with tweetsharp library and I need to get the user acitvity such as TweetDeck activity.
How can we achieve this task?
Please help me.
Any help will be appreciated.
You should use below line of code for getting the twitter activity for tweetsharp library with the help of site stream.
public void Can_stream_from_user_stream()
{
const int maxStreamEvents = 5;
var block = new AutoResetEvent(false);
var count = 0;
var service = GetAuthenticatedService();
service.StreamUser((streamEvent, response) =>
{
if (streamEvent is TwitterUserStreamEnd)
{
block.Set();
}
if (response.StatusCode == 0)
{
if (streamEvent is TwitterUserStreamFriends)
{
var friends = (TwitterUserStreamFriends)streamEvent;
Assert.IsNotNull(friends);
Assert.IsNotNull(friends.RawSource);
Assert.IsTrue(friends.Ids.Any());
}
if (streamEvent is TwitterUserStreamEvent)
{
var #event = (TwitterUserStreamEvent)streamEvent;
Assert.IsNotNull(#event);
Assert.IsNotNull(#event.TargetObject);
Assert.IsNotNull(#event.RawSource);
}
if (streamEvent is TwitterUserStreamStatus)
{
var tweet = ((TwitterUserStreamStatus)streamEvent).Status;
Assert.IsNotNull(tweet);
Assert.IsNotNull(tweet.Id);
Assert.IsNotNull(tweet.User);
Assert.IsNotNull(tweet.RawSource);
Assert.IsNotNull(tweet.User.ScreenName);
}
if (streamEvent is TwitterUserStreamDirectMessage)
{
var dm = ((TwitterUserStreamDirectMessage)streamEvent).DirectMessage;
Assert.IsNotNull(dm);
Assert.IsNotNull(dm.Id);
Assert.IsNotNull(dm.Sender);
Assert.IsNotNull(dm.Recipient);
Assert.IsNotNull(dm.RawSource);
}
if (streamEvent is TwitterUserStreamDeleteStatus)
{
var deleted = (TwitterUserStreamDeleteStatus)streamEvent;
Assert.IsNotNull(deleted);
Assert.IsTrue(deleted.StatusId > 0);
Assert.IsTrue(deleted.UserId > 0);
}
if (streamEvent is TwitterUserStreamDeleteDirectMessage)
{
var deleted = (TwitterUserStreamDeleteDirectMessage)streamEvent;
Assert.IsNotNull(deleted);
Assert.IsTrue(deleted.DirectMessageId > 0);
Assert.IsTrue(deleted.UserId > 0);
}
count++;
if (count == maxStreamEvents)
{
block.Set();
}
}
else
{
Assert.Ignore("Stream responsed with status code: {0}", response.StatusCode);
}
});
block.WaitOne();
service.CancelStreaming();
}
above line of code I am getting from this Link