Example usage for android.support.v4.content AsyncTaskLoader AsyncTaskLoader

List of usage examples for android.support.v4.content AsyncTaskLoader AsyncTaskLoader

Introduction

In this page you can find the example usage for android.support.v4.content AsyncTaskLoader AsyncTaskLoader.

Prototype

public AsyncTaskLoader(Context context) 

Source Link

Usage

From source file:com.ihelp101.instagram.FilePickerFragment.java

/**
 * Get a loader that lists the Files in the current path,
 * and monitors changes.//  w  w  w .  ja  v  a  2  s .c  o  m
 */
@Override
public Loader<SortedList<File>> getLoader() {
    return new AsyncTaskLoader<SortedList<File>>(getActivity()) {

        FileObserver fileObserver;

        @Override
        public SortedList<File> loadInBackground() {
            File[] listFiles = mCurrentPath.listFiles();
            final int initCap = listFiles == null ? 0 : listFiles.length;

            SortedList<File> files = new SortedList<>(File.class,
                    new SortedListAdapterCallback<File>(getDummyAdapter()) {
                        @Override
                        public int compare(File lhs, File rhs) {
                            return compareFiles(lhs, rhs);
                        }

                        @Override
                        public boolean areContentsTheSame(File file, File file2) {
                            return file.getAbsolutePath().equals(file2.getAbsolutePath())
                                    && (file.isFile() == file2.isFile());
                        }

                        @Override
                        public boolean areItemsTheSame(File file, File file2) {
                            return areContentsTheSame(file, file2);
                        }
                    }, initCap);

            files.beginBatchedUpdates();
            if (listFiles != null) {
                for (File f : listFiles) {
                    if (isItemVisible(f)) {
                        files.add(f);
                    }
                }
            }
            files.endBatchedUpdates();

            return files;
        }

        /**
         * Handles a request to start the Loader.
         */
        @Override
        protected void onStartLoading() {
            super.onStartLoading();

            // handle if directory does not exist. Fall back to root.
            if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
                mCurrentPath = getRoot();
            }

            // Start watching for changes
            fileObserver = new FileObserver(mCurrentPath.getPath(), FileObserver.CREATE | FileObserver.DELETE
                    | FileObserver.MOVED_FROM | FileObserver.MOVED_TO) {

                @Override
                public void onEvent(int event, String path) {
                    // Reload
                    onContentChanged();
                }
            };
            fileObserver.startWatching();

            forceLoad();
        }

        /**
         * Handles a request to completely reset the Loader.
         */
        @Override
        protected void onReset() {
            super.onReset();

            // Stop watching
            if (fileObserver != null) {
                fileObserver.stopWatching();
                fileObserver = null;
            }
        }
    };
}

From source file:com.nononsenseapps.filepicker.sample.ftp.FtpPickerFragment.java

/**
 * Get a loader that lists the files in the current path,
 * and monitors changes.//  ww w .  j a v  a2s . c om
 */
@NonNull
@Override
public Loader<SortedList<FtpFile>> getLoader() {
    return new AsyncTaskLoader<SortedList<FtpFile>>(getContext()) {
        @Override
        public SortedList<FtpFile> loadInBackground() {
            SortedList<FtpFile> sortedList = new SortedList<>(FtpFile.class,
                    new SortedListAdapterCallback<FtpFile>(getDummyAdapter()) {
                        @Override
                        public int compare(FtpFile lhs, FtpFile rhs) {
                            if (lhs.isDirectory() && !rhs.isDirectory()) {
                                return -1;
                            } else if (rhs.isDirectory() && !lhs.isDirectory()) {
                                return 1;
                            } else {
                                return lhs.getName().compareToIgnoreCase(rhs.getName());
                            }
                        }

                        @Override
                        public boolean areContentsTheSame(FtpFile oldItem, FtpFile newItem) {
                            return oldItem.getName().equals(newItem.getName());
                        }

                        @Override
                        public boolean areItemsTheSame(FtpFile item1, FtpFile item2) {
                            return item1.getName().equals(item2.getName());
                        }
                    });

            if (!ftp.isConnected()) {
                // Connect
                try {
                    ftp.connect(server, port);

                    ftp.setFileType(FTP.ASCII_FILE_TYPE);
                    ftp.enterLocalPassiveMode();
                    ftp.setUseEPSVwithIPv4(false);

                    if (!(loggedIn = ftp.login(username, password))) {
                        ftp.logout();
                        Log.e(TAG, "Login failed");
                    }
                } catch (IOException e) {
                    if (ftp.isConnected()) {
                        try {
                            ftp.disconnect();
                        } catch (IOException ignored) {
                        }
                    }
                    Log.e(TAG, "Could not connect to server.");
                }
            }

            if (loggedIn) {
                try {
                    // handle if directory does not exist. Fall back to root.
                    if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
                        mCurrentPath = getRoot();
                    }

                    sortedList.beginBatchedUpdates();
                    for (FTPFile f : ftp.listFiles(mCurrentPath.getPath())) {
                        FtpFile file;
                        if (f.isDirectory()) {
                            file = new FtpDir(mCurrentPath, f.getName());
                        } else {
                            file = new FtpFile(mCurrentPath, f.getName());
                        }
                        if (isItemVisible(file)) {
                            sortedList.add(file);
                        }
                    }
                    sortedList.endBatchedUpdates();
                } catch (IOException e) {
                    Log.e(TAG, "IOException: " + e.getMessage());
                }
            }

            return sortedList;
        }

        /**
         * Handles a request to start the Loader.
         */
        @Override
        protected void onStartLoading() {
            super.onStartLoading();

            // handle if directory does not exist. Fall back to root.
            if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
                mCurrentPath = getRoot();
            }

            forceLoad();
        }
    };
}

From source file:it.polimi.spf.app.fragments.contacts.CircleFragment.java

@Override
public Loader<Collection<String>> onCreateLoader(int id, final Bundle args) {
    final PersonRegistry registry = SPF.get().getSecurityMonitor().getPersonRegistry();
    switch (id) {
    case LoadersConfig.LOAD_CIRCLE_LOADER:
        return new AsyncTaskLoader<Collection<String>>(getActivity()) {

            @Override/*www.  ja  va 2s  .  co m*/
            public Collection<String> loadInBackground() {
                return registry.getGroups();
            }
        };
    case LoadersConfig.ADD_CIRCLE_LOADER:
        return new AsyncTaskLoader<Collection<String>>(getActivity()) {

            @Override
            public Collection<String> loadInBackground() {
                String group = args.getString(LoadersConfig.EXTRA_CIRCLE);
                registry.addGroup(group);
                return registry.getGroups();
            }
        };
    case LoadersConfig.DELETE_CIRCLE_LOADER:
        return new AsyncTaskLoader<Collection<String>>(getActivity()) {

            @Override
            public Collection<String> loadInBackground() {
                String group = args.getString(LoadersConfig.EXTRA_CIRCLE);
                registry.removeGroup(group);
                return registry.getGroups();
            }
        };

    default:
        return null;
    }
}

From source file:org.rm3l.ddwrt.tiles.status.wireless.WirelessIfaceTile.java

@Nullable
@Override//  w  w  w  .jav a2 s . c  o  m
protected Loader<NVRAMInfo> getLoader(int id, Bundle args) {
    return new AsyncTaskLoader<NVRAMInfo>(this.mParentFragmentActivity) {

        @Nullable
        @Override
        public NVRAMInfo loadInBackground() {

            try {
                Log.d(LOG_TAG,
                        "Init background loader for " + WirelessIfaceTile.class + ": routerInfo=" + mRouter
                                + " / this.mAutoRefreshToggle= " + mAutoRefreshToggle + " / nbRunsLoader="
                                + nbRunsLoader);

                if (nbRunsLoader > 0 && !mAutoRefreshToggle) {
                    //Skip run
                    Log.d(LOG_TAG, "Skip loader run");
                    return new NVRAMInfo().setException(new DDWRTTileAutoRefreshNotAllowedException());
                }
                nbRunsLoader++;

                final NVRAMInfo nvramInfo = getIfaceNvramInfo(iface);
                if (parentIface != null && !parentIface.isEmpty()) {
                    nvramInfo.putAll(getIfaceNvramInfo(parentIface));
                }

                if (nvramInfo.isEmpty()) {
                    throw new DDWRTNoDataException("No Data!");
                }

                return nvramInfo;

            } catch (@NotNull final Exception e) {
                e.printStackTrace();
                return new NVRAMInfo().setException(e);
            }
        }

        @NotNull
        private NVRAMInfo getIfaceNvramInfo(@NotNull String wlIface) throws Exception {

            if (DDWRTCompanionConstants.TEST_MODE) {
                return new NVRAMInfo()
                        .setProperty(WIRELESS_IFACE + (wlIface.equals(parentIface) ? "_parent" : ""), wlIface)
                        .setProperty(wlIface + "_radio", String.valueOf(new Random().nextInt()))
                        .setProperty(wlIface + "_mode", "Mode")
                        .setProperty(wlIface + "_hwaddr", "hw:ad:dr:rd:da:wh")
                        .setProperty(wlIface + "_ifname", wlIface + " ifname")
                        .setProperty(wlIface + "_net_mode", "ng-only").setProperty(wlIface + "_ssid", "SSID")
                        .setProperty(wlIface + "_channel", String.valueOf(new Random().nextInt(100)))
                        .setProperty(wlIface + "_txpwr", String.valueOf(new Random().nextInt(100)))
                        .setProperty(wlIface + "_rate", String.valueOf(new Random().nextInt(100)))
                        .setProperty(wlIface + "_akm", "psk psk2");
            }

            final NVRAMInfo nvramInfo = new NVRAMInfo();

            NVRAMInfo nvramInfoTmp = null;
            try {
                nvramInfoTmp = SSHUtils.getNVRamInfoFromRouter(mRouter, mGlobalPreferences, wlIface + "_radio",
                        wlIface + "_mode", wlIface + "_hwaddr", wlIface + "_ifname", wlIface + "_net_mode",
                        wlIface + "_ssid", wlIface + "_channel", wlIface + "_txpwr", wlIface + "_rate",
                        wlIface + "_akm", wlIface + "_wpa_psk");
            } finally {
                if (nvramInfoTmp != null) {
                    nvramInfo.putAll(nvramInfoTmp);
                }
                nvramInfo.setProperty(WIRELESS_IFACE + (wlIface.equals(parentIface) ? "_parent" : ""), wlIface);

                //Set Temp, RX and TX Network Bandwidths on Physical Interface
                final String phyIface = nvramInfo.getProperty(wlIface + "_ifname");
                if (!isNullOrEmpty(phyIface)) {

                    //Set temperature
                    //noinspection ConstantConditions
                    final Map<TemperatureUnit, String> ifaceTemperatures = getIfaceTemperature(phyIface);
                    final String celsius = ifaceTemperatures.get(CELSIUS);
                    final String fahrenheit = ifaceTemperatures.get(FAHRENHEIT);
                    if (!(isNullOrEmpty(celsius) || isNullOrEmpty(fahrenheit))) {
                        nvramInfo.setProperty(wlIface + "_temperature", celsius + DEGREE_SYMBOL + CELSIUS + " ("
                                + fahrenheit + DEGREE_SYMBOL + FAHRENHEIT + ")");
                    }

                    //RX and TX Bytes
                    //noinspection ConstantConditions
                    final Map<IfaceStatsType, Long> ifaceRxAndTxRates = getIfaceRxAndTxRates(phyIface);
                    final Long rxBps = ifaceRxAndTxRates.get(IfaceStatsType.RX_BYTES);
                    final Long txBps = ifaceRxAndTxRates.get(IfaceStatsType.TX_BYTES);
                    if (rxBps != null) {
                        nvramInfo.setProperty(wlIface + "_rx_rate_human_readable",
                                rxBps + " B/s (" + FileUtils.byteCountToDisplaySize(rxBps) + "/s)");
                    }
                    if (txBps != null) {
                        nvramInfo.setProperty(wlIface + "_tx_rate_human_readable",
                                txBps + " B/s (" + FileUtils.byteCountToDisplaySize(txBps) + "/s)");
                    }

                    //Packet Info
                    final String sysClassNetStatsFolder = String.format(CAT_SYS_CLASS_NET_S_STATISTICS,
                            phyIface);
                    try {
                        final String[] packetsInfo = SSHUtils.getManualProperty(mRouter, mGlobalPreferences,
                                String.format("%s/rx_packets", sysClassNetStatsFolder),
                                String.format("%s/rx_errors", sysClassNetStatsFolder),
                                String.format("%s/tx_packets", sysClassNetStatsFolder),
                                String.format("%s/tx_errors", sysClassNetStatsFolder));

                        if (packetsInfo != null) {
                            final long rxErrors = Long.parseLong(packetsInfo[1]);
                            nvramInfo.setProperty(wlIface + "_rx_packets",
                                    String.format("%s (%s)", packetsInfo[0], rxErrors <= 0 ? "no error"
                                            : (rxErrors + String.format("error%s", rxErrors > 1 ? "s" : ""))));
                            final long txErrors = Long.parseLong(packetsInfo[3]);
                            nvramInfo.setProperty(wlIface + "_tx_packets",
                                    String.format("%s (%s)", packetsInfo[2], txErrors <= 0 ? "no error"
                                            : (txErrors + String.format(" error%s", txErrors > 1 ? "s" : ""))));
                        }
                    } catch (final Exception e) {
                        e.printStackTrace();
                        //No worries
                    }
                }
            }

            return nvramInfo;
        }

        @NotNull
        private Map<TemperatureUnit, String> getIfaceTemperature(@NotNull final String phyIface) {
            final Map<TemperatureUnit, String> result = Maps.newHashMapWithExpectedSize(2);
            final String phyIfaceVarNameInRouter = WirelessIfaceTile.class.getSimpleName()
                    + "TemperatureCelsius";
            try {
                final String[] temperatures = SSHUtils.getManualProperty(mRouter, mGlobalPreferences,
                        String.format(
                                "%s=$(echo $((`wl -i %s phy_tempsense | awk {' print $1 '}`/2+20))); echo \"C:$%s\"; echo \"F:$(($%s*9/5+32))\"",
                                phyIfaceVarNameInRouter, phyIface, phyIfaceVarNameInRouter,
                                phyIfaceVarNameInRouter));
                if (temperatures != null && temperatures.length >= 2) {
                    for (final String temperature : temperatures) {
                        if (temperature == null) {
                            continue;
                        }
                        if (temperature.startsWith("C:")) {
                            result.put(CELSIUS, temperature.replaceAll("C:", "").trim());
                        } else if (temperature.startsWith("F:")) {
                            result.put(FAHRENHEIT, temperature.replaceAll("F:", "").trim());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

        @NotNull
        private Map<IfaceStatsType, Long> getIfaceRxAndTxRates(@NotNull final String phyIface) {
            final Map<IfaceStatsType, Long> result = Maps.newHashMapWithExpectedSize(2);
            final String sysClassNetStatsFolder = String.format(CAT_SYS_CLASS_NET_S_STATISTICS, phyIface);
            final String rxBytesCmd = String.format("%s/rx_bytes", sysClassNetStatsFolder);
            final String txBytesCmd = String.format("%s/tx_bytes", sysClassNetStatsFolder);

            try {
                final long[] bytesBeforeAndAfter = parseFloatDataFromOutput(SSHUtils.getManualProperty(mRouter,
                        mGlobalPreferences, rxBytesCmd, txBytesCmd, "sleep 1", rxBytesCmd, txBytesCmd));
                if (bytesBeforeAndAfter.length >= 4) {
                    result.put(IfaceStatsType.RX_BYTES,
                            Math.abs(bytesBeforeAndAfter[1] - bytesBeforeAndAfter[0]));
                    result.put(IfaceStatsType.TX_BYTES,
                            Math.abs(bytesBeforeAndAfter[3] - bytesBeforeAndAfter[2]));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

        @NotNull
        private long[] parseFloatDataFromOutput(@Nullable final String[] output) {
            if (output == null || output.length == 0) {
                throw new IllegalArgumentException("Output null or empty");
            }
            final long[] result = new long[output.length];
            for (int i = 0; i < output.length; i++) {
                result[i] = Long.parseLong(output[i]);

            }
            return result;
        }

    };
}

From source file:com.home.young.filepicker.FilePickerFragment.java

/**
 * Get a loader that lists the Files in the current path,
 * and monitors changes.//ww w  .  j  a  va 2s  . c om
 */
@NonNull
@Override
public Loader<SortedList<File>> getLoader() {
    return new AsyncTaskLoader<SortedList<File>>(getActivity()) {

        FileObserver fileObserver;

        @Override
        public SortedList<File> loadInBackground() {
            File[] listFiles = mCurrentPath.listFiles();
            final int initCap = listFiles == null ? 0 : listFiles.length;

            SortedList<File> files = new SortedList<>(File.class,
                    new SortedListAdapterCallback<File>(getDummyAdapter()) {
                        @Override
                        public int compare(File lhs, File rhs) {
                            return compareFiles(lhs, rhs);
                        }

                        @Override
                        public boolean areContentsTheSame(File file, File file2) {
                            return file.getAbsolutePath().equals(file2.getAbsolutePath())
                                    && (file.isFile() == file2.isFile());
                        }

                        @Override
                        public boolean areItemsTheSame(File file, File file2) {
                            return areContentsTheSame(file, file2);
                        }
                    }, initCap);

            files.beginBatchedUpdates();
            if (listFiles != null) {
                for (java.io.File f : listFiles) {
                    if (isItemVisible(f)) {
                        files.add(f);
                    }
                }
            }
            files.endBatchedUpdates();

            return files;
        }

        /**
         * Handles a request to start the Loader.
         */
        @Override
        protected void onStartLoading() {
            super.onStartLoading();

            // handle if directory does not exist. Fall back to root.
            if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
                mCurrentPath = getRoot();
            }

            // Start watching for changes
            fileObserver = new FileObserver(mCurrentPath.getPath(), FileObserver.CREATE | FileObserver.DELETE
                    | FileObserver.MOVED_FROM | FileObserver.MOVED_TO) {

                @Override
                public void onEvent(int event, String path) {
                    // Reload
                    onContentChanged();
                }
            };
            fileObserver.startWatching();

            forceLoad();
        }

        /**
         * Handles a request to completely reset the Loader.
         */
        @Override
        protected void onReset() {
            super.onReset();

            // Stop watching
            if (fileObserver != null) {
                fileObserver.stopWatching();
                fileObserver = null;
            }
        }
    };
}

From source file:it.polimi.spf.app.fragments.NotificationFragment.java

@Override
public Loader<List<NotificationMessage>> onCreateLoader(int id, final Bundle args) {
    switch (id) {
    case LoadersConfig.MESSAGE_LOADER_ID:
        return new AsyncTaskLoader<List<NotificationMessage>>(getActivity()) {

            @Override//from   ww  w . ja v  a 2  s.c  o  m
            public List<NotificationMessage> loadInBackground() {
                return SPF.get().getNotificationManager().getAvailableNotifications();
            }
        };
    case LoadersConfig.MESSAGE_DELETER_ID:
        return new AsyncTaskLoader<List<NotificationMessage>>(getActivity()) {

            @Override
            public List<NotificationMessage> loadInBackground() {
                if (args == null) {
                    SPF.get().getNotificationManager().deleteAllNotifications();
                } else {
                    long msgId = args.getLong(LoadersConfig.EXTRA_MESSAGE_ID);
                    SPF.get().getNotificationManager().deleteNotification(msgId);
                }
                return SPF.get().getNotificationManager().getAvailableNotifications();
            }
        };

    default:
        return null;
    }
}

From source file:it.polimi.spf.app.fragments.contacts.PeopleFragment.java

@Override
public Loader<List<PersonInfo>> onCreateLoader(int id, Bundle args) {
    switch (id) {
    case LoadersConfig.LOAD_CONTACTS_LOADER:
        return new AsyncTaskLoader<List<PersonInfo>>(getActivity()) {

            @Override/*from w  ww  . j a v  a2  s .  c  om*/
            public List<PersonInfo> loadInBackground() {
                return SPF.get().getSecurityMonitor().getPersonRegistry().getAvailableContacts();
            }
        };
    case LoadersConfig.LOAD_REQUEST_LOADER:
        return new AsyncTaskLoader<List<PersonInfo>>(getActivity()) {

            @Override
            public List<PersonInfo> loadInBackground() {
                return SPF.get().getSecurityMonitor().getPersonRegistry().getPendingRequests();
            }
        };
    default:
        return null;
    }
}

From source file:cn.tycoon.lighttrans.fileManager.FilePickerFragment.java

/**
 * Get a loader that lists the Files in the current path,
 * and monitors changes./*www  . j  a va  2  s . com*/
 */
@Override
public Loader<SortedList<File>> getLoader() {
    return new AsyncTaskLoader<SortedList<File>>(getActivity()) {

        FileObserver fileObserver;

        @Override
        public SortedList<File> loadInBackground() {
            File[] listFiles = mCurrentPath.listFiles();
            final int initCap = listFiles == null ? 0 : listFiles.length;

            SortedList<File> files = new SortedList<>(File.class,
                    new SortedListAdapterCallback<File>(getDummyAdapter()) {
                        @Override
                        public int compare(File lhs, File rhs) {
                            return compareFiles(lhs, rhs);
                        }

                        @Override
                        public boolean areContentsTheSame(File file, File file2) {
                            return file.getAbsolutePath().equals(file2.getAbsolutePath())
                                    && (file.isFile() == file2.isFile());
                        }

                        @Override
                        public boolean areItemsTheSame(File file, File file2) {
                            return areContentsTheSame(file, file2);
                        }
                    }, initCap);

            files.beginBatchedUpdates();
            if (listFiles != null) {
                for (java.io.File f : listFiles) {
                    //if (isItemVisible(f)) {
                    files.add(f);
                    //}
                }
            }
            files.endBatchedUpdates();

            return files;
        }

        /**
         * Handles a request to start the Loader.
         */
        @Override
        protected void onStartLoading() {
            super.onStartLoading();

            // handle if directory does not exist. Fall back to root.
            if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
                mCurrentPath = getRoot();
            }

            // Start watching for changes
            fileObserver = new FileObserver(mCurrentPath.getPath(), FileObserver.CREATE | FileObserver.DELETE
                    | FileObserver.MOVED_FROM | FileObserver.MOVED_TO) {

                @Override
                public void onEvent(int event, String path) {
                    // Reload
                    onContentChanged();
                }
            };
            fileObserver.startWatching();

            forceLoad();
        }

        /**
         * Handles a request to completely reset the Loader.
         */
        @Override
        protected void onReset() {
            super.onReset();

            // Stop watching
            if (fileObserver != null) {
                fileObserver.stopWatching();
                fileObserver = null;
            }
        }
    };
}

From source file:org.rm3l.ddwrt.tiles.services.vpn.OpenVPNClientTile.java

@Nullable
@Override/*from  w  w  w.  j  a v a 2 s  .c o  m*/
protected Loader<NVRAMInfo> getLoader(int id, Bundle args) {
    return new AsyncTaskLoader<NVRAMInfo>(this.mParentFragmentActivity) {

        @Nullable
        @Override
        public NVRAMInfo loadInBackground() {

            try {
                Log.d(LOG_TAG,
                        "Init background loader for " + OpenVPNClientTile.class + ": routerInfo=" + mRouter
                                + " / this.mAutoRefreshToggle= " + mAutoRefreshToggle + " / nbRunsLoader="
                                + nbRunsLoader);

                if (nbRunsLoader > 0 && !mAutoRefreshToggle) {
                    //Skip run
                    Log.d(LOG_TAG, "Skip loader run");
                    return new NVRAMInfo().setException(new DDWRTTileAutoRefreshNotAllowedException());
                }
                nbRunsLoader++;

                mNvramInfo = null;

                @NotNull
                final NVRAMInfo nvramInfo = new NVRAMInfo();

                NVRAMInfo nvramInfoTmp = null;

                try {
                    nvramInfoTmp = SSHUtils.getNVRamInfoFromRouter(mRouter, mGlobalPreferences,
                            //Status: {1,0}
                            OPENVPNCL_ENABLE,
                            //Server IP Name
                            OPENVPNCL_REMOTEIP,
                            //Port (from 1 to 65535): default=1194
                            OPENVPNCL_REMOTEPORT,
                            //Tunnel Device: {"tun", "tap"}
                            OPENVPNCL_TUNTAP,
                            //Tunnel Protocol: { "udp", "tcp-client"}
                            OPENVPNCL_PROTO,
                            //Encryption Cipher:
                            //{aes-512-cbc, aes-256-cbc, aes-192-cbc, aes-128-cbc, bf-cbc, none}
                            OPENVPNCL_CIPHER,
                            //Hash Algorithm
                            //{sha512, sha256, sha1, md5, md4, none}
                            OPENVPNCL_AUTH,
                            //TLS Cipher
                            //{TLS-DHE-RSA-WITH-AES-256-GCM-SHA384,
                            //TLS-DHE-RSA-WITH-AES-256-CBC-SHA256,
                            //TLS-DHE-RSA-WITH-AES-128-CBC-SHA,
                            //TLS-RSA-WITH-AES-256-GCM-SHA384,
                            //TLS-RSA-WITH-AES-256-CBC-SHA256,
                            //TLS-RSA-WITH-AES-128-CBC-SHA,
                            //TLS-RSA-WITH-RC4-128-MD5,
                            //0}
                            //Advanced Options: {1,0}
                            OPENVPNCL_ADV, OPENVPNCL_TLSCIP,
                            //LZO Compression: {yes, adaptive, no, off}
                            OPENVPNCL_LZO,
                            //NAT: {1, 0}
                            OPENVPNCL_NAT,
                            //Firewall Protection (enabled if openvpncl_nat==1): {1,0}
                            OPENVPNCL_SEC,
                            //Bridge TAP to br0 (enabled if openvpncl_nat==0)"{1,0}
                            OPENVPNCL_BRIDGE,
                            //IP Address
                            OPENVPNCL_IP,
                            //Subnet Mask
                            OPENVPNCL_MASK,
                            //Tunnel MTU Setting: (from 1 to 65535)
                            OPENVPNCL_MTU,
                            //Tunnel UDP Fragment (num max chars=5): if nothing => Disabled
                            OPENVPNCL_FRAGMENT,
                            //Tunnel UDP MSS-Fix: {1,0}
                            OPENVPNCL_MSSFIX,
                            //nsCertType verification: {1,0}
                            OPENVPNCL_CERTTYPE,
                            //TLS Auth Key
                            OPENVPNCL_TLSAUTH,
                            //Additional Config
                            OPENVPNCL_CONFIG,
                            //Policy based Routing
                            OPENVPNCL_ROUTE,
                            //PKCS12 Key
                            OPENVPNCL_PKCS_12,
                            //Static Key
                            OPENVPNCL_STATIC,
                            //CA Cert
                            OPENVPNCL_CA,
                            //Public Client Cert
                            OPENVPNCL_CLIENT,
                            //Private Client Key
                            OPENVPNCL_KEY);
                } finally {
                    if (nvramInfoTmp != null) {
                        nvramInfo.putAll(nvramInfoTmp);
                    }

                    final String[] devDeviceLine = SSHUtils.getManualProperty(mRouter, mGlobalPreferences,
                            "cat /tmp/openvpncl/openvpn.conf | grep \"dev \"");
                    String openvpnclIface = null;
                    if (devDeviceLine != null && devDeviceLine.length > 0) {
                        openvpnclIface = devDeviceLine[0].replace("dev ", "").trim();
                    }

                    if (!Strings.isNullOrEmpty(openvpnclIface)) {
                        nvramInfo.setProperty(OPENVPNCL__DEV, openvpnclIface);
                        //noinspection ConstantConditions
                        final Map<WirelessIfaceTile.IfaceStatsType, Long> ifaceRxAndTxRates = getIfaceRxAndTxRates(
                                openvpnclIface);

                        final Long rxBps = ifaceRxAndTxRates.get(RX_BYTES);
                        final Long txBps = ifaceRxAndTxRates.get(TX_BYTES);
                        if (rxBps != null) {
                            nvramInfo.setProperty(OPENVPNCL__DEV_RX_RATE,
                                    rxBps + " B/s (" + FileUtils.byteCountToDisplaySize(rxBps) + "/s)");
                        }
                        if (txBps != null) {
                            nvramInfo.setProperty(OPENVPNCL__DEV_TX_RATE,
                                    txBps + " B/s (" + FileUtils.byteCountToDisplaySize(txBps) + "/s)");
                        }

                        //Packet Info
                        final String sysClassNetStatsFolder = String.format(CAT_SYS_CLASS_NET_S_STATISTICS,
                                openvpnclIface);
                        try {
                            final String[] packetsInfo = SSHUtils.getManualProperty(mRouter, mGlobalPreferences,
                                    String.format("%s/rx_packets", sysClassNetStatsFolder),
                                    String.format("%s/rx_errors", sysClassNetStatsFolder),
                                    String.format("%s/tx_packets", sysClassNetStatsFolder),
                                    String.format("%s/tx_errors", sysClassNetStatsFolder));

                            if (packetsInfo != null) {
                                final long rxErrors = Long.parseLong(packetsInfo[1]);
                                nvramInfo.setProperty(OPENVPNCL__DEV_RX_PACKETS,
                                        String.format("%s (%s)", packetsInfo[0], rxErrors <= 0 ? "no error"
                                                : (rxErrors
                                                        + String.format("error%s", rxErrors > 1 ? "s" : ""))));
                                final long txErrors = Long.parseLong(packetsInfo[3]);
                                nvramInfo.setProperty(OPENVPNCL__DEV_TX_PACKETS,
                                        String.format("%s (%s)", packetsInfo[2], txErrors <= 0 ? "no error"
                                                : (txErrors
                                                        + String.format(" error%s", txErrors > 1 ? "s" : ""))));
                            }
                        } catch (final Exception e) {
                            e.printStackTrace();
                            //No worries
                        }
                    }

                }

                if (nvramInfo.isEmpty()) {
                    throw new DDWRTNoDataException("No Data!");
                }

                return nvramInfo;

            } catch (@NotNull final Exception e) {
                e.printStackTrace();
                return new NVRAMInfo().setException(e);
            }

        }

        @NotNull
        private Map<WirelessIfaceTile.IfaceStatsType, Long> getIfaceRxAndTxRates(
                @NotNull final String phyIface) {
            final Map<WirelessIfaceTile.IfaceStatsType, Long> result = Maps.newHashMapWithExpectedSize(2);
            final String sysClassNetStatsFolder = String.format(CAT_SYS_CLASS_NET_S_STATISTICS, phyIface);
            final String rxBytesCmd = String.format("%s/rx_bytes", sysClassNetStatsFolder);
            final String txBytesCmd = String.format("%s/tx_bytes", sysClassNetStatsFolder);

            try {
                final long[] bytesBeforeAndAfter = parseFloatDataFromOutput(SSHUtils.getManualProperty(mRouter,
                        mGlobalPreferences, rxBytesCmd, txBytesCmd, "sleep 1", rxBytesCmd, txBytesCmd));
                if (bytesBeforeAndAfter.length >= 4) {
                    result.put(RX_BYTES, Math.abs(bytesBeforeAndAfter[1] - bytesBeforeAndAfter[0]));
                    result.put(TX_BYTES, Math.abs(bytesBeforeAndAfter[3] - bytesBeforeAndAfter[2]));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

        @NotNull
        private long[] parseFloatDataFromOutput(@Nullable final String[] output) {
            if (output == null || output.length == 0) {
                throw new IllegalArgumentException("Output null or empty");
            }
            final long[] result = new long[output.length];
            for (int i = 0; i < output.length; i++) {
                result[i] = Long.parseLong(output[i]);

            }
            return result;
        }
    };
}

From source file:com.android.julia.todolist.ui.MainActivity.java

/**
 * Instantiates and returns a new AsyncTaskLoader with the given ID.
 * This loader will return task data as a Cursor or null if an error occurs.
 *
 * Implements the required callbacks to take care of loading data at all stages of loading.
 *//*from w  ww. ja v a 2  s.c  om*/
@Override
public Loader<Cursor> onCreateLoader(int id, final Bundle loaderArgs) {

    return new AsyncTaskLoader<Cursor>(this) {

        // Initialize a Cursor, this will hold all the task data
        Cursor mTaskData = null;

        // onStartLoading() is called when a loader first starts loading data
        @Override
        protected void onStartLoading() {
            if (mTaskData != null) {
                // Delivers any previously loaded data immediately
                deliverResult(mTaskData);
            } else {
                // Force a new load
                forceLoad();
            }
        }

        // loadInBackground() performs asynchronous loading of data
        @Override
        public Cursor loadInBackground() {
            // Will implement to load data

            // Query and load all task data in the background; sort by priority

            try {
                return getContentResolver().query(TaskContract.TaskEntry.CONTENT_URI, null, null, null,
                        TaskContract.TaskEntry.COLUMN_PRIORITY);

            } catch (Exception e) {
                Log.e(TAG, "Failed to asynchronously load data.");
                e.printStackTrace();
                return null;
            }
        }

        // deliverResult sends the result of the load, a Cursor, to the registered listener
        public void deliverResult(Cursor data) {
            mTaskData = data;
            super.deliverResult(data);
        }
    };
}