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.nononsenseapps.filepicker.sample.dropbox.DropboxFilePickerFragment.java

@Override
public Loader<SortedList<DropboxAPI.Entry>> getLoader() {
    return new AsyncTaskLoader<SortedList<DropboxAPI.Entry>>(getActivity()) {

        @Override/*from ww w .j  av a2s . co  m*/
        public SortedList<DropboxAPI.Entry> loadInBackground() {
            SortedList<DropboxAPI.Entry> files = new SortedList<>(DropboxAPI.Entry.class,
                    new SortedListAdapterCallback<DropboxAPI.Entry>(getAdapter()) {
                        @Override
                        public int compare(DropboxAPI.Entry lhs, DropboxAPI.Entry rhs) {
                            if (isDir(lhs) && !isDir(rhs)) {
                                return -1;
                            } else if (isDir(rhs) && !isDir(lhs)) {
                                return 1;
                            } else {
                                return lhs.fileName().toLowerCase().compareTo(rhs.fileName().toLowerCase());
                            }
                        }

                        @Override
                        public boolean areContentsTheSame(DropboxAPI.Entry lhs, DropboxAPI.Entry rhs) {
                            return lhs.fileName().equals(rhs.fileName()) && (lhs.isDir == rhs.isDir);
                        }

                        @Override
                        public boolean areItemsTheSame(DropboxAPI.Entry lhs, DropboxAPI.Entry rhs) {
                            return areContentsTheSame(lhs, rhs);
                        }
                    }, 0);

            try {

                if (!dbApi.metadata(mCurrentPath.path, 1, null, false, null).isDir) {
                    mCurrentPath = getRoot();
                }

                DropboxAPI.Entry dirEntry = dbApi.metadata(mCurrentPath.path, 0, null, true, null);

                files.beginBatchedUpdates();

                for (DropboxAPI.Entry entry : dirEntry.contents) {
                    if ((mode == MODE_FILE || mode == MODE_FILE_AND_DIR) || entry.isDir) {
                        files.add(entry);
                    }
                }

                files.endBatchedUpdates();
            } catch (DropboxException ignored) {
            }

            return files;
        }

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

            if (mCurrentPath == null || !mCurrentPath.isDir) {
                mCurrentPath = getRoot();
            }

            forceLoad();
        }

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

From source file:org.rm3l.ddwrt.tiles.status.bandwidth.BandwidthMonitoringTile.java

@Override
protected Loader<None> getLoader(int id, Bundle args) {
    return new AsyncTaskLoader<None>(this.mParentFragmentActivity) {

        @Nullable/*from   ww  w . j a v a  2  s .  c  o  m*/
        @Override
        public None loadInBackground() {

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

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

                //Get ifaces and fetch data points for each of these ifaces
                fillIfacesDataPoints(getIfaces());

                return new None();

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

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

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

        @Nullable
        @Override
        public ClientDevices loadInBackground() {

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

            //Determine broadcast address at each run (because that might change if connected to another network)
            try {
                final WifiManager wifiManager = (WifiManager) mParentFragmentActivity
                        .getSystemService(Context.WIFI_SERVICE);

                mCurrentIpAddress = Utils.intToIp(wifiManager.getConnectionInfo().getIpAddress());

                final InetAddress broadcastAddress = Utils.getBroadcastAddress(wifiManager);
                if (broadcastAddress != null) {
                    mBroadcastAddress = broadcastAddress.getHostAddress();
                }
            } catch (@NotNull final Exception e) {
                e.printStackTrace();
                //No worries
            }

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

            final ClientDevices devices = new ClientDevices();

            if (DDWRTCompanionConstants.TEST_MODE) {
                //FIXME TEST MODE
                for (int i = 1, j = i + 1; i <= 15; i++, j++) {
                    final int randomI = new Random().nextInt(i);
                    final int randomJ = new Random().nextInt(j);
                    devices.addDevice(
                            new Device(String.format("A%1$s:B%1$s:C%1$s:D%2$s:E%2$s:F%2$s", randomI, randomJ))
                                    .setIpAddress(String.format("172.17.1%1$s.2%2$s", randomI, randomJ))
                                    .setSystemName(String.format("Device %1$s-%2$s", randomI, randomJ)));
                }
                Log.d(LOG_TAG, "wireless client devices: " + devices);
                return devices;
                //FIXME END TEST MODE
            }

            try {
                @Nullable
                final String[] output = SSHUtils.getManualProperty(mRouter, mGlobalPreferences,
                        "grep dhcp-host /tmp/dnsmasq.conf | sed 's/.*=//' | awk -F , '{print \"" + MAP_KEYWORD
                                + "\",$1,$3 ,$2}'",
                        "awk '{print \"" + MAP_KEYWORD + "\",$2,$3,$4}' /tmp/dnsmasq.leases",
                        "awk 'NR>1{print \"" + MAP_KEYWORD + "\",$4,$1,\"*\"}' /proc/net/arp", "echo done");

                Log.d(LOG_TAG, "output: " + (output == null ? "NULL" : Arrays.toString(output)));

                if (output == null) {
                    return null;
                }

                for (final String stdoutLine : output) {
                    if ("done".equals(stdoutLine)) {
                        break;
                    }
                    final List<String> as = Splitter.on(" ").splitToList(stdoutLine);
                    if (as != null && as.size() >= 4 && MAP_KEYWORD.equals(as.get(0))) {
                        final String macAddress = as.get(1);
                        if ("00:00:00:00:00:00".equals(macAddress)) {
                            //Skip clients with incomplete ARP set-up
                            continue;
                        }
                        final Device device = new Device(macAddress);
                        device.setIpAddress(as.get(2));

                        final String systemName = as.get(3);
                        if (!"*".equals(systemName)) {
                            device.setSystemName(systemName);
                        }
                        devices.addDevice(device);
                    }

                }

                return devices;

            } catch (@NotNull final Exception e) {
                Log.e(LOG_TAG, e.getMessage() + ": " + Throwables.getStackTraceAsString(e));
                return new ClientDevices().setException(e);
            }
        }
    };
}

From source file:org.rm3l.ddwrt.tiles.syslog.StatusSyslogTile.java

@Override
protected Loader<NVRAMInfo> getLoader(int id, Bundle args) {
    return new AsyncTaskLoader<NVRAMInfo>(this.mParentFragmentActivity) {

        @Nullable//from w  w w  .  java  2 s. c  o m
        @Override
        public NVRAMInfo loadInBackground() {
            try {
                Log.d(LOG_TAG,
                        "Init background loader for " + StatusSyslogTile.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++;

                @NotNull
                final NVRAMInfo nvramInfo = new NVRAMInfo();
                if (DDWRTCompanionConstants.TEST_MODE) {
                    @NotNull
                    final String syslogData = "Space suits go with future at the carnivorous alpha quadrant!\n"
                            + "Cur guttus mori? Ferox, clemens hippotoxotas acceleratrix "
                            + "anhelare de germanus, camerarius bubo. Always purely feel the magical lord.\n"
                            + "Refrigerate roasted lobsters in a cooker with hollandaise sauce for about an hour to enhance their thickness."
                            + "With escargots drink BBQ sauce.Yarr there's nothing like the misty amnesty screaming on the sea.\n"
                            + "Death is a stormy whale.The undead parrot smartly leads the anchor.\n\n\n";
                    nvramInfo.setProperty(SYSLOG, syslogData);
                    nvramInfo.setProperty(SYSLOGD_ENABLE, String.valueOf(new Random().nextInt()));
                } else {
                    NVRAMInfo nvramInfoTmp = null;
                    try {
                        nvramInfoTmp = SSHUtils.getNVRamInfoFromRouter(mRouter, mGlobalPreferences,
                                SYSLOGD_ENABLE);
                    } finally {
                        if (nvramInfoTmp != null) {
                            nvramInfo.putAll(nvramInfoTmp);
                        }

                        String[] logs = null;
                        try {
                            //Get last log lines
                            logs = SSHUtils.getManualProperty(mRouter, mGlobalPreferences,
                                    String.format("tail -n %d /tmp/var/log/messages %s", MAX_LOG_LINES,
                                            isNullOrEmpty(mGrep) ? "" : " | grep -i -E \"" + mGrep + "\""));
                        } finally {
                            if (logs != null) {
                                nvramInfo.setProperty(SYSLOG, LOGS_JOINER.join(logs));
                            }
                        }
                    }
                }

                return nvramInfo;

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

From source file:com.example.android.popularmovies.fragments.MovieTrailersFragment.java

@Override
public Loader<Results<Trailer>> onCreateLoader(int id, Bundle args) {
    final ITheMovieDbApi theMovieDbApi = NetworkUtils.buildRetrofit();
    final String apiKey = getContext().getResources().getString(R.string.api_key_the_movie_db);

    return new AsyncTaskLoader<Results<Trailer>>(getContext()) {
        @Override// w  w w .  jav  a  2s  . co  m
        public Results<Trailer> loadInBackground() {

            Call<Results<Trailer>> call = theMovieDbApi.loadTrailers(mMovie.getId(), apiKey);
            try {
                Response<Results<Trailer>> res = call.execute();
                return res.body();
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "loadInBackground: " + e.toString());
                return null;
            }
        }
    };
}

From source file:it.polimi.spf.app.fragments.personas.PersonasFragment.java

@Override
public Loader<List<SPFPersona>> onCreateLoader(final int id, final Bundle args) {
    final SPFProfileManager profile = SPF.get().getProfileManager();

    switch (id) {
    case LoadersConfig.CREATE_PERSONA_LOADER:
        return new AsyncTaskLoader<List<SPFPersona>>(getActivity()) {

            @Override/*from  w  ww .j  a v a  2s.com*/
            public List<SPFPersona> loadInBackground() {
                SPFPersona persona = args.getParcelable(LoadersConfig.EXTRA_PERSONA);
                profile.addPersona(persona);
                return profile.getAvailablePersonas();
            }
        };

    case LoadersConfig.DELETE_PERSONA_LOADER:
        return new AsyncTaskLoader<List<SPFPersona>>(getActivity()) {

            @Override
            public List<SPFPersona> loadInBackground() {
                SPFPersona persona = args.getParcelable(LoadersConfig.EXTRA_PERSONA);
                profile.removePersona(persona);
                return profile.getAvailablePersonas();
            }
        };
    case LoadersConfig.LOAD_PERSONAS_LOADER:
        return new AsyncTaskLoader<List<SPFPersona>>(getActivity()) {

            @Override
            public List<SPFPersona> loadInBackground() {
                return profile.getAvailablePersonas();
            }
        };
    default:
        return null;
    }
}

From source file:org.exoplatform.ui.social.SpaceSelectorActivity.java

@Override
public Loader<List<SocialSpaceInfo>> onCreateLoader(int id, Bundle args) {
    return new AsyncTaskLoader<List<SocialSpaceInfo>>(this) {
        @Override// w  ww  . ja  v a2  s  .c o m
        public List<SocialSpaceInfo> loadInBackground() {
            List<SocialSpaceInfo> spacesNames = new ArrayList<SocialSpaceInfo>();
            if (SocialServiceHelper.getInstance().spaceService == null) {
                Log.e(LOG_TAG, "Cannot retrieve spaces. Social Space service is null.");
                return null;
            }
            List<RestSpace> spaces = SocialServiceHelper.getInstance().spaceService.getMySocialSpaces();
            String currentServer = AccountSetting.getInstance().getDomainName();
            for (RestSpace space : spaces) {
                SocialSpaceInfo sp = new SocialSpaceInfo();
                sp.displayName = space.getDisplayName();
                sp.name = space.getName();
                sp.avatarUrl = currentServer + space.getAvatarUrl();
                sp.groupId = space.getGroupId();
                spacesNames.add(sp);
            }
            return spacesNames;
        }
    };
}

From source file:it.polimi.spf.demo.chat.ProfileFragment.java

@Override
public Loader<ProfileFieldContainer> onCreateLoader(int id, Bundle args) {
    return new AsyncTaskLoader<ProfileFieldContainer>(getActivity()) {
        @Override/*ww w  .j av a 2  s . c  o  m*/
        public ProfileFieldContainer loadInBackground() {
            ProfileFieldContainer result;
            if (SELF_IDENTIFIER.equals(mProfileIdentifier)) {
                result = mLocalProfile.getValueBulk(FIELDS);
                mLocalProfile.disconnect();
            } else {
                SPFSearch search = mSpf.getComponent(SPF.SEARCH);
                SPFPerson person = search.lookup(mProfileIdentifier);
                if (person == null) {
                    Log.w(TAG, "Person " + mProfileIdentifier + " is not available");
                    return null;
                }

                result = person.getProfile(mSpf).getProfileBulk(FIELDS);
            }

            return result;
        }
    };
}

From source file:org.rm3l.ddwrt.tiles.status.wan.WANMonthlyTrafficTile.java

@Nullable
@Override//from w  w w . j  a  v a  2s .com
protected Loader<NVRAMInfo> getLoader(int id, Bundle args) {

    if (nbRunsLoader <= 0 || mAutoRefreshToggle) {
        setLoadingViewVisibility(View.VISIBLE);
    }

    return new AsyncTaskLoader<NVRAMInfo>(this.mParentFragmentActivity) {

        @Nullable
        @Override
        public NVRAMInfo loadInBackground() {

            try {

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

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

                @NotNull
                final NVRAMInfo nvramInfo = new NVRAMInfo();

                NVRAMInfo nvramInfoTmp = null;
                try {
                    //noinspection ConstantConditions
                    nvramInfoTmp = NVRAMParser.parseNVRAMOutput(SSHUtils.getManualProperty(mRouter,
                            mGlobalPreferences, "nvram show 2>/dev/null | grep traff[-_]"));
                } finally {
                    if (nvramInfoTmp != null) {
                        nvramInfo.putAll(nvramInfoTmp);
                    }

                }

                traffDataTableBuilder = ImmutableTable.builder();

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

                @SuppressWarnings("ConstantConditions")
                final Set<Map.Entry<Object, Object>> entries = nvramInfo.getData().entrySet();

                for (final Map.Entry<Object, Object> entry : entries) {
                    final Object key;
                    final Object value;
                    if (entry == null || (key = entry.getKey()) == null || (value = entry.getValue()) == null) {
                        continue;
                    }

                    if (!StringUtils.startsWithIgnoreCase(key.toString(), "traff-")) {
                        continue;
                    }

                    final String month = key.toString().replace("traff-", DDWRTCompanionConstants.EMPTY_STRING);

                    final String yearlyTraffData = value.toString();
                    final List<String> yearlyTraffDataList = MONTHLY_TRAFF_DATA_SPLITTER
                            .splitToList(yearlyTraffData);
                    if (yearlyTraffDataList == null || yearlyTraffDataList.isEmpty()) {
                        continue;
                    }

                    int dayNum = 1;
                    for (final String dailyInOutTraffData : yearlyTraffDataList) {
                        if (StringUtils.contains(dailyInOutTraffData, "[")) {
                            continue;
                        }
                        final List<String> dailyInOutTraffDataList = DAILY_TRAFF_DATA_SPLITTER
                                .splitToList(dailyInOutTraffData);
                        if (dailyInOutTraffDataList == null || dailyInOutTraffDataList.size() < 2) {
                            continue;
                        }
                        final String inTraff = dailyInOutTraffDataList.get(0);
                        final String outTraff = dailyInOutTraffDataList.get(1);

                        traffDataTableBuilder.put(month, dayNum++,
                                Lists.newArrayList(Double.parseDouble(inTraff), Double.parseDouble(outTraff)));

                    }
                }

                traffData = traffDataTableBuilder.build();

                return nvramInfo;

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

        }
    };
}

From source file:com.delaroystudios.todolist.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.
 *//*  w  w  w . j  av a 2s . 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
            // [Hint] use a try/catch block to catch any errors in loading data

            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);
        }
    };

}