I have successfuly signed in to Sky Drive account using Live Sdk (One Drive) libraries. And have also fetched the files and folder of the Root Directory of My One Drive (Sky Drive) account. Now i want to fetch files when i click on the the folder which is in the root directory.
I got my solution. Its simple and clean code i am here to paste for getting files from any folder id.
Just cancatinate 'files' after the folder id, like Folder_id+"/files" and it will retrieve all
the files
client.getAsync(Folder_id+"/files", new LiveOperationListener()
{
public void onComplete(LiveOperation operation)
{
final JSONObject result = operation.getResult();
final JSONArray data = result.optJSONArray("data");
if (result.has("error"))
{
final JSONObject error = result.optJSONObject("error");
final String message = error.optString("message");
final String code = error.optString("code");
ShowToast("mssg"+message);
return;
}
for (int i = 0; i < data.length(); i++)
{
final JSONObject oneDriveItem = data.optJSONObject(i);
if (oneDriveItem != null) {
final String itemName = oneDriveItem.optString("name");
final String itemType = oneDriveItem.optString("type");
final String ids=oneDriveItem.optString("id");
ShowToast("Folder ID = " + ids + ", name = " + itemName);
// ShowToast("Name: "+itemName+"\n"+"Type: "+itemType+"\n ID: "+ oneDriveItem.optString("id"));
}
}
//JSONObject result = operation.getResult();
Log.e("realllt",result.toString() );
}
public void onError(LiveOperationException exception, LiveOperation operation) {
resultTextView.setText("Error reading folder: " + exception.getMessage());
}
});
Related
I already found out how to get all storages with either of these answers: with proc/mounts and with mount command, but now I want to put a name on the paths returned. I have no problem with Internal Storage, however these methods can't distinguish between a SD card and a USB stick. If it sees two drives connected how can I be sure which one is the SD Card and which is the USB, or are they two SD Cards? Or two USB drives?
I found part of the solution, however I won't get any farther because it's getting complicated and this is not the main feature of my app anyway.
public static class Storage extends File {
public static final int INTERNAL_STORAGE = 1;
public static final int SD_CARD = 2;
public static final int USB_DRIVE = 3;
public String name;
public int type;
public Storage(String path, String name, int type) {
super(path);
this.name = name;
this.type = type;
}
}
public static ArrayList<Storage> getStorages(Context context) {
ArrayList<Storage> storages = new ArrayList<>();
// Internal storage
storages.add(new Storage(Environment.getExternalStorageDirectory().getPath(),
"Internal Storage", Storage.INTERNAL_STORAGE));
// SD Cards
ArrayList<File> extStorages = new ArrayList<>();
extStorages.addAll(Arrays.asList(context.getExternalFilesDirs(null)));
extStorages.remove(0); // Remove internal storage
String secondaryStoragePath = System.getenv("SECONDARY_STORAGE");
for (int i = 0; i < extStorages.size(); i++) {
String path = extStorages.get(i).getPath().split("/Android")[0];
if (Environment.isExternalStorageRemovable(extStorages.get(i)) || secondaryStoragePath != null && secondaryStoragePath.contains(path)) {
String name = "SD Card" + (i == 0 ? "" : " " + String.valueOf(i+1));
storages.add(new Storage(path, name, Storage.SD_CARD));
}
}
// USB Drives
ArrayList<String> drives = new ArrayList<>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s += new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec") && line.matches(reg)) {
String[] parts = line.split(" ");
for (String path : parts) {
if (path.startsWith(File.separator) && !path.toLowerCase(Locale.US).contains("vold")) {
drives.add(path);
}
}
}
}
// Remove SD Cards from found drives (already found)
ArrayList<String> ids = new ArrayList<>();
for (Storage st : storages) {
String[] parts = st.getPath().split(File.separator);
ids.add(parts[parts.length-1]);
}
for (int i = drives.size() - 1; i >= 0; i--) {
String[] parts = drives.get(i).split(File.separator);
String id = parts[parts.length-1];
if (ids.contains(id)) drives.remove(i);
}
// Get USB Drive name
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
Collection<UsbDevice> dList = usbManager.getDeviceList().values();
ArrayList<UsbDevice> deviceList = new ArrayList<>();
deviceList.addAll(dList);
for (int i = 0; i < deviceList.size(); i++) {
storages.add(new Storage(drives.get(i), deviceList.get(i).getProductName(), Storage.USB_DRIVE));
}
return storages;
}
Find internal storage
Find all SD Cards
Find all external drives, then remove SD Cards from them, because they were already found. The point of this is to separate SD Cards from USB devices.
I didn't test this with any other device than mine, it won't likely work for every device. Also it is possible that keyboards or mouses counts as connected devices and that will screw up the whole thing.
I am trying to sort a list of array based on the name in alphabetical order which contain type, name, url and date. I retrieved the information from Browser.BookmarkColumns except for type.
Before:
Default Browser Google www.Google.com 14/12/2013
Default Browser BBC www.BBC.com 13/12/2015
Default Browser Amazon www.Amazon.com 11/11/2014
After:
Default Browser Amazon www.Amazon.com 11/11/2014
Default Browser BBC www.BBC.com 13/12/2015
Default Browser Google www.Google.com 14/12/2013
Here is what i have tried but it is not working.
int j = mCur.getCount();
String[] mType = new String[j];
String[] mTitles = new String[j];
String[] murls = new String[j];
long[] date = new long[j];
for (int q=0; q<(j-1); q++) {
String a = (mTitles[q]).toLowerCase();
String b = (mTitles[q+1].toLowerCase());
char[] c = a.toCharArray();
char[] d = b.toCharArray();
String temp, temp2, temp3 = null;
long temp4 = 0;
int lenc = c.length;
int lend = d.length;
int min =0;
int count =0;
if (lenc < lend)
min = lenc;
else
min = lend;
if (c[count] > d[count]) {
temp = mTitles[count];
temp2 = mType[count];
temp3 = murls[count];
temp4 = date[count];
mTitles[count] = mTitles[count + 1];
mType[count] = mType[count + 1];
murls[count] = murls[count + 1];
date[count] = date[count + 1];
mTitles[count + 1] = temp;
mType[count + 1] = temp2;
murls[count + 1] = temp3;
date[count + 1] = temp4;
} else if (c[count] == d[count]) {
for (int w = 1; w < min; w++) {
if (c[w] > d[w]) {
temp = mTitles[w];
temp2 = mType[w];
temp3 = murls[w];
temp4 = date[w];
mTitles[w] = mTitles[w + 1];
mType[w] = mType[w + 1];
murls[w] = murls[w + 1];
date[w] = date[w + 1];
mTitles[w + 1] = temp;
mType[w + 1] = temp2;
murls[w + 1] = temp3;
date[w + 1] = temp4;
}
}
}
}
Above answers are giving best example for efficient sorting Array list in java.
Before it please read description of above mentioned answer here
I just simplified above answer for your better understanding it gives exact output what u required.
ArrayList<UserContainer> userList = new ArrayList<>();
userList.add(new UserContainer("www.Google.com", "Google", "14/12/2013"));
userList.add(new UserContainer("www.BBC.com", "BBC", "13/12/2015"));
userList.add(new UserContainer("www.Amazon.com", "Amazon", "11/11/2014"));
Log.i("Before Sorting :", "==========================>>");
for (UserContainer obj : userList) {
System.out.println("Default Browser: \t" + obj.name + "\t" + obj.date + "\t" + obj.webSite);
}
Collections.sort(userList, new Comparator<UserContainer>() {
#Override
public int compare(UserContainer first, UserContainer second) {
return first.name.compareToIgnoreCase(second.name);
}
});
Log.i("After Sorting :", "==========================>>");
for (UserContainer obj : userList) {
System.out.println("Default Browser: \t" + obj.name + "\t" + obj.date + "\t" + obj.webSite);
}
Model Class:
public class UserContainer {
public UserContainer(String webSite, String name, String date) {
this.webSite = webSite;
this.name = name;
this.date = date;
}
public String webSite = "";
public String name = "";
public String date = "";
}
First of all it would be much simplier task if instead of sorting 3 string arrays + long array You encapsulate all the fields and create a class (lets call it MyData) containing all four fields. Then you can use put all newly create objects in some collection (for example ArrayList).
So, when you have your ArrayList<MyData> you can easliy use Collections.sort passing both your list and implementation of Comparator<T> interface where all the sorting logic would be.
For example, if you want to sort whole list using only String title field it can look like this:
Comparator<MyData> with implemented compare function compare(MyData o1, MyData o2){return o1.title.compareTo(o2);
My advice to create custom array list.
private ArrayList<UserContainer> userList=new ArrayList<UserContainer>();
UserContainer usercontainer=new UserContainer()
usercontainer.name=Amazon;
usercontainer.date=11/11/2014;
userList.add(usercontainer);
UserContainer usercontainer2=new UserContainer()
usercontainer.name=Google;
usercontainer.date=11/11/2014;
userList.add(usercontainer);
UserContainer usercontainer3=new UserContainer()
usercontainer.name=BBC;
usercontainer.date=11/11/2014;
userList.add(usercontainer);
Collections.sort(userList, new Comparator<UserContainer>() {
#Override
public int compare(UserContainer s1, UserContainer s2) {
return s1.name.compareToIgnoreCase(s2.name);
}
});
Model:-
public class UserContainer {
public String name = "";
public String date = "";
}
I hope to help you.
Create a class and use comparator or comparable.
for further reference please check (How to sort an ArrayList in Java)
Arrays.sort(stringArray);
Its a nice way to sort.
I recommend you to create a Object for example 'BrowserStoredData' for each element of the list. With the strings required:
public class BrowserStoredData implements Comparable<BrowserStoredData> {
String browserType;
String browserName;
String browserUrl;
String browserDate;
public BrowserStoredData(String browserType, String browserName,
String browserUrl, String browserDate) {
super();
this.browserType = browserType;
this.browserName = browserName;
this.browserUrl = browserUrl;
this.browserDate = browserDate;
}
public int compareTo(BrowserStoredData bsd) {
return (this.browserName).compareTo(bsd.browserName);
}
#Override
public String toString() {
return browserType + "\t\t" + browserName + "\t\t" + browserUrl
+ "\t\t" + browserDate;
}
}
With that object you easily can order a list of BrowserStoredData objects simply by using Collections.sort(yourList)
For example:
BrowserStoredData bsd1 = new BrowserStoredData("Default Browser", "Google", "www.Google.com", "14/12/2013");
BrowserStoredData bsd2 = new BrowserStoredData("Default Browser", "BBC", "www.BBC.com", "13/12/2015");
BrowserStoredData bsd3 = new BrowserStoredData("Default Browser", "Amazon", "www.Amazon.com", "11/11/2014");
List<BrowserStoredData> listBrowsers = new ArrayList<BrowserStoredData>();
listBrowsers.add(bsd1);
listBrowsers.add(bsd2);
listBrowsers.add(bsd3);
Collections.sort(listBrowsers);
for (int i = 0 ; i < listBrowsers.size() ; i++){
BrowserStoredData bsd = listBrowsers.get(i);
System.out.println(bsd.toString());
}
The exit will be:
Default Browser Amazon www.Amazon.com 11/11/2014
Default Browser BBC www.BBC.com 13/12/2015
Default Browser Google www.Google.com 14/12/201
I am retrieving an object from amazon s3.How to get metadata of retrieved object in android? From the metadata, i want to find out whether that object is image or Non-image (like pdf, csv, ...)
Thanks for any help.
I am using the following code for getting list of names under a folder.
AmazonS3Client s3Client;
s3Client = new AmazonS3Client(new BasicAWSCredentials(
Constants.ACCESS_KEY_ID, Constants.SECRET_KEY));
ObjectListing objListOfPath = s3Client.listObjects(
Constants.getPictureBucket(), path);
List<S3ObjectSummary> keyListOfObjectSummaries = objListOfPath
.getObjectSummaries();
ObjectListing next = s3Client.listNextBatchOfObjects(objListOfPath);
keyListOfObjectSummaries.addAll(next.getObjectSummaries());
System.out.println("keyListOfObjectSummaries size() "
+ keyListOfObjectSummaries.size());
ArrayList<String> arrListImageName = new ArrayList<String>();
if (keyListOfObjectSummaries.size() > 0) {
for (int i = 0; i < keyListOfObjectSummaries.size(); i++) {
String imagePath = keyListOfObjectSummaries.get(i).getKey();
arrListImageName.add(strImageName);
}
for (int i = 0; i < arrListImageName.size(); i++) {
System.out.println("Index " + i + " image Name "
+ arrListImageName.get(i));
String strReceiptImageName = arrListImageName.get(i);
String strReceiptNameExtension = extractReceiptNameExtension(arrListImageName.get(i));
S3Object objectReceiptFromAmazonS3 = s3Client.getObject(
Constants.PICTURE_BUCKET, keyListOfObjectSummaries
.get(i).getKey());
InputStream inputStreamReceiptObject = objectReceiptFromAmazonS3
.getObjectContent();
SOLUTION:
System.out.println("CONTENT TYPE " +objectReceiptFromAmazonS3.getObjectMetadata().getContentType());
Thanks to Harshit and sanket !
This has worked for me to download a file hosted in S3 from a simple servlet.
private static final int BYTES_DOWNLOAD = 1024;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String key = request.getParameter("key");
HttpSession session = request.getSession();
String bucketname = (String) session.getAttribute("BUCKETNAME");
AmazonS3 s3 = new AmazonS3Client(Constants.credentials);
Region usWest2 = Region.getRegion(Regions.US_WEST_2);
s3.setRegion(usWest2);
S3Object object = s3.getObject(new GetObjectRequest(bucketname, key));
response.setContentType(object.getObjectMetadata().getContentType());
response.setHeader("Content-Disposition","attachment;filename="+object.getKey());
InputStream is = object.getObjectContent();int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
use this couple of lines :
ObjectMetadata metaData = new ObjectMetadata();
metaData.addUserMetadata("key", key of your file);
System.out.println("Content type is========"+metaData.getContentType());
this might be help you..
i have an array of names which have multiple files and folders...now i want to sort the names according to files and folders.all folders first and then all files should display.i have the variable to check whether on particular index of array their is file or folder.but unable to think the logic..
i am attaching some of my codes.
////////////////////////////////
case 0://Sort By Name
{
if(m_sortType == SORT_BY_NAME && temp==false)
{
m_sortType = SORT_BY_NAME;
m_sortOrder=SORT_ORDER_DESCENDING;
temp= true;
//Log.d("SORTING", "SORT - NAME - DES");
}
else
{
m_sortType = SORT_BY_NAME;
m_sortOrder=SORT_ORDER_ASCENDING;
temp=false;
//Log.d("SORTING", "SORT - NAME - AES");
}
//Log.d("SORTING", "Data bfore sort");
for (int k=0; k<m_adapter.m_env.m_count; k++)
//Log.d("SORTING DATA", k + ": " + m_adapter.m_env.m_fs.get(m_SortArray[k]).m_name);
m_adapter.sortListing(m_sortType,m_sortOrder);
//Log.d("SORTING", "Data after sort");
for (int k=0; k<m_adapter.m_env.m_count; k++)
//Log.d("SORTING DATA", k + ": " + m_adapter.m_env.m_fs.get(m_SortArray[k]).m_name);
//Refresh();
break;
}
////////////////
private void sortListing(int sortType, int sortOrder)
{
m_sortType = sortType;
m_sortOrder = sortOrder;
Arrays.sort( m_SortArray , new Comparator() {
public int compare(Integer a1, Integer a2)
{
if(m_sortType == SORT_BY_NAME)
{
String s1 = null,s2 = null;
FileFolderEnum t2 = null;
FileFolderEnum t1 = null;
int i;
if(m_sortOrder==SORT_ORDER_ASCENDING)
{
s1 = m_env.m_fs.get(a1).m_name;
s2 = m_env.m_fs.get(a2).m_name;
t1 = m_env.m_fs.get(a1).m_type;
t2 = m_env.m_fs.get(a2).m_type;
}
else if(m_sortOrder==SORT_ORDER_DESCENDING)
{
s1 = m_env.m_fs.get(a2).m_name;
s2 = m_env.m_fs.get(a1).m_name;
t1 = m_env.m_fs.get(a2).m_type;
t2 = m_env.m_fs.get(a1).m_type;
}
//Log.d("SORTING COMPARE", "(" + Integer.toString(a1)+") s1: " + s1);
//Log.d("SORTING COMPARE", "(" + Integer.toString(a2)+") s2: " + s2);
if((t1.equals(CFileFolder.FileFolderEnum.FFE_FOLDER)&&(t2.equals(CFileFolder.FileFolderEnum.FFE_FOLDER))))
{
i=s1.compareToIgnoreCase (s2);
}
i=s1.compareToIgnoreCase (s2);
//Log.d("SORTING COMPARE", "s1.compareTo(s2): " + Integer.toString(i));
return i;
}
///////////////////
Code I pulled from my own file browser. Use as you wish. :
File[] directoryList = currentFolder.listFiles();
if (directoryList != null) {
List<File> directoryListing = new ArrayList<File>();
directoryListing.addAll(Arrays.asList(directoryList));
Collections.sort(directoryListing, new SortFileName());
Collections.sort(directoryListing, new SortFolder());
}
//sorts based on the files name
public class SortFileName implements Comparator<File> {
#Override
public int compare(File f1, File f2) {
return f1.getName().compareTo(f2.getName());
}
}
//sorts based on a file or folder. folders will be listed first
public class SortFolder implements Comparator<File> {
#Override
public int compare(File f1, File f2) {
if (f1.isDirectory() == f2.isDirectory())
return 0;
else if (f1.isDirectory() && !f2.isDirectory())
return -1;
else
return 1;
}
}
I know it's an old post but I needed to solve this issue and came across the post. dymmeh's solution was a good start but I wanted to sort in one pass and I wanted Windows-like sorting (case not considered). Here's what I came up with:
import java.io.File;
import java.util.Comparator;
public class FileComparator implements Comparator<File> {
#Override
public int compare(File lhs, File rhs) {
if (lhs.isDirectory() == rhs.isDirectory()) { // Both files are directory OR file, compare by name
return lhs.getName().toLowerCase().compareTo(rhs.getName().toLowerCase());
} else if (lhs.isDirectory()) { // Directories before files
return -1;
} else { // rhs must be a directory
return 1;
}
}
}
Usage is straight forward:
final File file = new File(_directory);
final File[] files = file.listFiles();
Arrays.sort(files, new FileComparator());
Well you have the variable to check the name is of file and folder, I can think of a way to sort them as per your requirement. Make two ArrayLists. Separate folders and files in these two ArrayList and then sort both according to the names, simple sort operation for string. Then simply append the files List at the end of Folder List. May be it will work. Seems simple.
I am new to Android and I have one project which contains an .so file. In one .java file, this lib is used and I want to read that .so file.
You will have to put the .so file in the lib folder. Then access it using the demo function as shown below:
public static boolean loadNativeLibrary() {
try {
Log.i(TAG, "Attempting to load library: " + LIBRARY_NAME);
System.loadLibrary(LIBRARY_NAME);
} catch (Exception e) {
Log.i(TAG, "Exception loading native library: " + e.toString());
return false;
}
return true;
}
You can't really "read" a .so file; it's a compiled binary that contains machine code. It's not really possible to edit it.
You can list the symbols in it though, for example:
android-ndk-r6b/toolchains/arm-linux-androideabi-4.4.3/prebuilt/darwin-x86/bin/arm-linux-androideabi-nm ./path/to/libfoo.so
yes you can. You will need hex editor to read that. Because, as far as I understand, .so is just like .dll in windows.
Actually inside your JNI folder, android NDK which convert your native code like c or c++ into binary compiled code that is called "filename.so".You cannot read the binary code .so it wil create lib folder inside your libs/armeabi/ filename.so file.
You probably can read.*.so files. for this you need a Linux base Computer, & you need leafpad with this you can view the *.so file the most readable view to read, It will happen if you use leafpad on Linux or Notepad++.
Have a try.
Thank you
Yes you can read it using ReadElf.java.
https://android.googlesource.com/platform/cts/+/17fcb6c/libs/deviceutil/src/android/cts/util/ReadElf.java.
Below code is reading .SO file and finding out the architecture type.
Complete Code- https://github.com/robust12/ArchFinderBLStack.git
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private final String ARMV7ABI = "armeabi-v7a";
private final String X86 = "x86";
private final String MIPS = "mips";
private final String X86_64 = "x86_64";
private final String ARM64_V8 = "arm64-v8a";
private final String ARMABI = "armeabi";
private String result = "";
private File[] libFilesArray;
private int request_code = 1;
HashMap<Integer, String> typeMap;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textViewId);
typeMap = new HashMap<>();
initializeMap();
readFilesFromStorage();
textView.setText(result);
textView.setMovementMethod(new ScrollingMovementMethod());
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
private void readFilesFromStorage() throws NullPointerException {
String filePath = Environment.getExternalStorageDirectory() + "/test-input/";
File readSOFILE = new File(filePath);
if(!readSOFILE.exists()) {
result = getString(R.string.path_not_exist);
return;
}
libFilesArray = readSOFILE.listFiles();
if(libFilesArray == null) {
result = getString(R.string.error);
return;
}
findAbiType();
}
private void findAbiType() {
int count = libFilesArray.length;
int soCount = 0;
result = "";
Log.e(TAG, "Count is " + count);
for (int i = 0; i < count; i++) {
try {
if (libFilesArray[i].isFile()) {
int type = ReadElf.read(libFilesArray[i]).getType();
if (type == 3) {
soCount++;
int archCode = ReadElf.e_machine;
result += libFilesArray[i].getName() + " - " + typeMap.get(archCode) + "\n\n";
Log.e(TAG, "Code is " + archCode);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if(soCount != 0) {
result += "Total Libs Count: " + soCount + "\n\n";
} else{
result = getString(R.string.incorrect_type_libs);
}
}
private void initializeMap() {
typeMap.put(40, ARMV7ABI);
typeMap.put(3, X86);
typeMap.put(8, MIPS);
typeMap.put(62, X86_64);
typeMap.put(183, ARM64_V8);
typeMap.put(164, ARMABI);
}
}