List of usage examples for android.support.v4.content AsyncTaskLoader AsyncTaskLoader
public AsyncTaskLoader(Context context)
From source file:com.armannds.eldgos.katla.popularmovies.ui.MainActivity.java
@Override public Loader<List<Movie>> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<List<Movie>>(this) { List<Movie> mMovies; @Override/*from w ww . j av a2 s. com*/ public void onStartLoading() { if (mMovies != null) { deliverResult(mMovies); } else { mLoadingIndicator.setVisibility(View.VISIBLE); forceLoad(); } } @Override public void deliverResult(List<Movie> data) { mMovies = data; super.deliverResult(data); } @Override public List<Movie> loadInBackground() { Call<TheMovieDbResponse> theMovieDbResponse; if (mMovieFilter == R.string.top_rated) { theMovieDbResponse = theMovieDbService.getTopRatedMovies(); } else { theMovieDbResponse = theMovieDbService.getPopularMovies(); } List<Movie> movies = null; if (theMovieDbResponse != null) { try { movies = theMovieDbResponse.execute().body().getResults(); } catch (IOException e) { Log.e(TAG, "Error retrieving movies!"); } } return movies; } }; }
From source file:com.example.android.asynctaskloader.MainActivity.java
@Override public Loader<String> onCreateLoader(int id, final Bundle args) { return new AsyncTaskLoader<String>(this) { // TODO (1) Create a String member variable called mGithubJson that will store the raw JSON String mGithubJson;/*from w w w .j a v a2s .co m*/ @Override protected void onStartLoading() { /* If no arguments were passed, we don't have a query to perform. Simply return. */ if (args == null) { return; } /* * When we initially begin loading in the background, we want to display the * loading indicator to the user */ mLoadingIndicator.setVisibility(View.VISIBLE); // TODO (2) If mGithubJson is not null, deliver that result. Otherwise, force a load if (mGithubJson != null) { deliverResult(mGithubJson); } else { forceLoad(); } } @Override public String loadInBackground() { /* Extract the search query from the args using our constant */ String searchQueryUrlString = args.getString(SEARCH_QUERY_URL_EXTRA); /* If the user didn't enter anything, there's nothing to search for */ if (searchQueryUrlString == null || TextUtils.isEmpty(searchQueryUrlString)) { return null; } /* Parse the URL from the passed in String and perform the search */ try { URL githubUrl = new URL(searchQueryUrlString); String githubSearchResults = NetworkUtils.getResponseFromHttpUrl(githubUrl); return githubSearchResults; } catch (IOException e) { e.printStackTrace(); return null; } } // TODO (3) Override deliverResult and store the data in mGithubJson // TODO (4) Call super.deliverResult after storing the data @Override public void deliverResult(String data) { mGithubJson = data; super.deliverResult(data); } }; }
From source file:com.kafilicious.popularmovies.ui.activity.MainActivity.java
@Override public Loader<List<MovieList>> onCreateLoader(int id, final Bundle args) { return new AsyncTaskLoader<List<MovieList>>(this) { List<MovieList> movies = new ArrayList<MovieList>(); @Override//from ww w . j a v a2 s. co m protected void onStartLoading() { if (!movies.isEmpty()) { deliverResult(movies); Log.i(TAG, "Loader: movie list not empty, delivering results"); } else { showLoading(); forceLoad(); Log.i(TAG, "Loader: movie list empty, loading started"); } } @Override public List<MovieList> loadInBackground() { String urlQuery = null; if (args != null) { urlQuery = args.getString(SEARCH_QUERY_URL_EXTRA); if (urlQuery == null || TextUtils.isEmpty(urlQuery)) { Log.i(TAG, "Loader: Request URL is null or is empty"); return null; } } try { Log.i(TAG, "Loader: Request URL is not null and its not empty, loading started"); URL movieRequestUrl = new URL(urlQuery); String jsonResponse = NetworkUtils.getResponseFromHttpUrl(movieRequestUrl); try { List<MovieList> movieLists = new ArrayList<MovieList>(); JSONObject object = new JSONObject(jsonResponse); totalPages = object.getLong("total_pages"); totalPageNo = (int) totalPages; totalResults = object.getLong("total_results"); JSONArray jsonArray = object.getJSONArray("results"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject obj = jsonArray.getJSONObject(i); MovieList addMovies = new MovieList(); addMovies.overview = obj.getString("overview"); addMovies.releaseDate = obj.getString("release_date"); addMovies.title = obj.getString("title"); addMovies.voteAverage = obj.getDouble("vote_average"); addMovies.voteCount = obj.getLong("vote_count"); addMovies.id = obj.getInt("id"); addMovies.posterPath = obj.getString("poster_path"); addMovies.backdropPath = obj.getString("backdrop_path"); movieLists.add(addMovies); } return movieLists; } catch (JSONException j) { j.printStackTrace(); return null; } } catch (IOException e) { e.printStackTrace(); return null; } } public void deliverResult(List<MovieList> data) { movies = data; super.deliverResult(data); } }; }
From source file:com.delaroystudios.weatherapp.MainActivity.java
/** * Instantiate and return a new Loader for the given ID. * * @param id The ID whose loader is to be created. * @param loaderArgs Any arguments supplied by the caller. * * @return Return a new Loader instance that is ready to start loading. *//*from w w w . j av a 2 s .co m*/ @Override public Loader<String[]> onCreateLoader(int id, final Bundle loaderArgs) { return new AsyncTaskLoader<String[]>(this) { /* This String array will hold and help cache our weather data */ String[] mWeatherData = null; /** * Subclasses of AsyncTaskLoader must implement this to take care of loading their data. */ @Override protected void onStartLoading() { if (mWeatherData != null) { deliverResult(mWeatherData); } else { mLoadingIndicator.setVisibility(View.VISIBLE); forceLoad(); } } /** * This is the method of the AsyncTaskLoader that will load and parse the JSON data * from OpenWeatherMap in the background. * * @return Weather data from OpenWeatherMap as an array of Strings. * null if an error occurs */ @Override public String[] loadInBackground() { URL weatherRequestUrl = NetworkUtils.getUrl(MainActivity.this); try { String jsonWeatherResponse = NetworkUtils.getResponseFromHttpUrl(weatherRequestUrl); String[] simpleJsonWeatherData = OpenWeatherJsonUtils .getSimpleWeatherStringsFromJson(MainActivity.this, jsonWeatherResponse); return simpleJsonWeatherData; } catch (Exception e) { e.printStackTrace(); return null; } } /** * Sends the result of the load to the registered listener. * * @param data The result of the load */ public void deliverResult(String[] data) { mWeatherData = data; super.deliverResult(data); } }; }
From source file:xyz.jc.zeus.moviesguide.MainActivity.java
@Override public Loader<String[][]> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<String[][]>(this) { String[][] moviesInfo = null; @Override// w ww .j a v a 2 s . c om protected void onStartLoading() { if (moviesInfo != null) { deliverResult(moviesInfo); } else { mLoadingIndicator.setVisibility(View.VISIBLE); forceLoad(); } } @Override public String[][] loadInBackground() { String category = sortBy; URL[] movieDbRequestUrl = NetworkUtils.buildUrl(category); List<String[]> tempMovieInfo = new ArrayList<>(); try { if (!sortBy.equals(getString(R.string.pref_sort_favourite))) { //Iterating through the array of URL received from NetworkUtils.buildUrl() for (URL aMovieDbRequestUrl : movieDbRequestUrl) { String jsonMovieDbResponse = NetworkUtils.getResponseFromHttpUrl(aMovieDbRequestUrl); String[][] tmpMInfo = MovieDBJsonUtils.getMoviesInfoStringsFromJson(MainActivity.this, jsonMovieDbResponse); if (tmpMInfo != null) { Collections.addAll(tempMovieInfo, tmpMInfo); } } } else { ContentResolver resolver = getContentResolver(); Cursor cursor = resolver.query(MovieProvider.Movies.CONTENT_URI, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { String[][] tmpMInfo = new String[cursor.getCount()][6]; cursor.moveToFirst(); while (!cursor.isAfterLast()) { tmpMInfo[cursor.getPosition()][0] = cursor .getString(cursor.getColumnIndex(MovieColumns.ID)); tmpMInfo[cursor.getPosition()][1] = cursor .getString(cursor.getColumnIndex(MovieColumns.ORIGINAL_TITLE)); tmpMInfo[cursor.getPosition()][2] = cursor .getString(cursor.getColumnIndex(MovieColumns.POSTER_PATH)); tmpMInfo[cursor.getPosition()][3] = cursor .getString(cursor.getColumnIndex(MovieColumns.MOVIES_OVERVIEW)); tmpMInfo[cursor.getPosition()][4] = cursor .getString(cursor.getColumnIndex(MovieColumns.RELEASE_DATE)); tmpMInfo[cursor.getPosition()][5] = cursor .getString(cursor.getColumnIndex(MovieColumns.USER_RATING)); cursor.moveToNext(); } cursor.close(); Collections.addAll(tempMovieInfo, tmpMInfo); } } moviesInfo = new String[tempMovieInfo.size()][]; moviesInfo = tempMovieInfo.toArray(moviesInfo); return moviesInfo; } catch (Exception e) { e.printStackTrace(); return null; } } public void deliverResult(String[][] data) { moviesInfo = data; super.deliverResult(data); } }; }
From source file:it.polimi.spf.demo.chat.ConversationActivity.java
@Override public Loader<List<Message>> onCreateLoader(int id, Bundle args) { switch (id) { case MESSAGE_LOADER_ID: return new AsyncTaskLoader<List<Message>>(this) { @Override/*from www . j ava 2 s .co m*/ public List<Message> loadInBackground() { mStorage.markAsRead(mConversation); return mStorage.getAllMessages(mConversation); } }; default: return null; } }
From source file:com.jefftharris.passwdsafe.StorageFileListFragment.java
@Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { return new AsyncTaskLoader<Cursor>(getActivity()) { /** Handle when the loader is reset */ @Override/*ww w .j a v a 2s . c om*/ protected void onReset() { super.onReset(); onStopLoading(); } /** Handle when the loader is started */ @Override protected void onStartLoading() { forceLoad(); } /** Handle when the loader is stopped */ @Override protected void onStopLoading() { cancelLoad(); } /** Load the files in the background */ @Override public Cursor loadInBackground() { PasswdSafeUtil.dbginfo(TAG, "loadInBackground"); int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION; ContentResolver cr = getContext().getContentResolver(); List<Uri> permUris = ApiCompat.getPersistedUriPermissions(cr); for (Uri permUri : permUris) { PasswdSafeUtil.dbginfo(TAG, "Checking persist perm %s", permUri); Cursor cursor = null; try { cursor = cr.query(permUri, null, null, null, null); if ((cursor != null) && (cursor.moveToFirst())) { ApiCompat.takePersistableUriPermission(cr, permUri, flags); } else { ApiCompat.releasePersistableUriPermission(cr, permUri, flags); itsRecentFilesDb.removeUri(permUri); } } catch (Exception e) { Log.e(TAG, "File remove error: " + permUri, e); } finally { if (cursor != null) { cursor.close(); } } } try { return itsRecentFilesDb.queryFiles(); } catch (Exception e) { Log.e(TAG, "Files load error", e); } return null; } }; }
From source file:com.example.android.movies.MainActivity.java
@Override public Loader<List<Movie>> onCreateLoader(int id, final Bundle args) { return new AsyncTaskLoader<List<Movie>>(this) { List<Movie> moviesData = null; /**/*w ww . j a v a2s . c o m*/ * Subclasses of AsyncTaskLoader must implement this to take care of loading their data. */ @Override protected void onStartLoading() { if (moviesData != null) { deliverResult(moviesData); } else { mLoadingIndicator.setVisibility(View.VISIBLE); forceLoad(); } } /** * This is the method of the AsyncTaskLoader that will load and parse the JSON data * from OpenWeatherMap in the background. * * @return Weather data from OpenWeatherMap as an array of Strings. * null if an error occurs */ @Override public List<Movie> loadInBackground() { String sortByParameter = "popular"; if (args.getString("sortByParam") != null) sortByParameter = args.getString("sortByParam"); try { URL movieRequestUrl = NetworkUtils.buildMoviesUrl(sortByParameter); try { String jsonMovieResponse = NetworkUtils.getResponseFromHttpUrl(movieRequestUrl); ArrayList<Movie> simpleJsonMovieData = (ArrayList<Movie>) TheMovieDBJsonUtils .getMovieObjectsFromJson(MainActivity.this, jsonMovieResponse); return simpleJsonMovieData; } catch (Exception e) { e.printStackTrace(); return null; } } catch (Exception e) { e.printStackTrace(); return null; } } /** * Sends the result of the load to the registered listener. * * @param data The result of the load */ public void deliverResult(List<Movie> data) { moviesData = data; super.deliverResult(data); } }; }
From source file:de.grobox.liberario.ui.LocationView.java
@Override public AsyncTaskLoader onCreateLoader(int id, Bundle args) { AsyncTaskLoader loader = new AsyncTaskLoader<List<Location>>(getContext()) { @Override/*from www .jav a 2 s.co m*/ public List<Location> loadInBackground() { String search = getText(); if (search.length() < LocationAdapter.THRESHOLD) return null; NetworkProvider np = NetworkProviderFactory.provider(Preferences.getNetworkId(getContext())); try { // get locations from network provider SuggestLocationsResult result = np.suggestLocations(search); return result.getLocations(); } catch (Exception e) { e.printStackTrace(); return null; } } }; loader.setUpdateThrottle(750); return loader; }
From source file:it.geosolutions.geocollect.android.core.form.FormPageFragment.java
public Loader<Void> onCreateLoader(int id, Bundle args) { Log.d(TAG, "onCreateLoader(): id=" + id); Loader<Void> loader = new AsyncTaskLoader<Void>(getActivity()) { @Override//from ww w . j a v a2 s . com public Void loadInBackground() { Activity activity = getSherlockActivity(); Mission m = (Mission) getActivity().getIntent().getExtras().getSerializable(ARG_MISSION);//TODO investigate sometimes m is null if (m != null) { m.setTemplate(MissionUtils.getDefaultTemplate(activity)); if (activity instanceof FormEditActivity) { Log.d(TAG, "Loader: Connecting to Activity database"); m.db = ((FormEditActivity) activity).spatialiteDatabase; } else { Log.w(TAG, "Loader: Could not connect to Activity database"); } mission = m; return null; } else { //TODO notify error Toast.makeText(getActivity(), R.string.error_getting_data_from_database, Toast.LENGTH_LONG) .show(); getActivity().finish(); return null; } } }; //TODO create loader; loader.forceLoad(); return loader; }