Last active
January 30, 2019 18:14
-
-
Save Razeeman/5836643a4a143032a27ad4afcdad32c1 to your computer and use it in GitHub Desktop.
Android, Java, AsyncTaskLoader.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity implements | |
LoaderManager.LoaderCallbacks<String> { | |
private static final int LOADER_ID = 22; | |
private static final String SEARCH_QUERY_URL_EXTRA = "query"; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
Bundle queryBundle = new Bundle(); | |
queryBundle.putString(SEARCH_QUERY_URL_EXTRA, searchUrl.toString()); | |
LoaderManager loaderManager = getSupportLoaderManager(); | |
Loader<String> searchLoader = loaderManager.getLoader(LOADER_ID); | |
if (searchLoader == null) { | |
loaderManager.initLoader(LOADER_ID, queryBundle, this); | |
} else { | |
loaderManager.restartLoader(LOADER_ID, queryBundle, this); | |
} | |
} | |
@Override | |
public Loader<String> onCreateLoader(int id, final Bundle args) { | |
return new AsyncTaskLoader<String>(this) { | |
// query response cache | |
String mJson; | |
@Override | |
protected void onStartLoading() { | |
if (args == null) { | |
return; | |
} | |
if (mJson != null) { | |
deliverResult(mJson); | |
} else { | |
forceLoad(); | |
} | |
} | |
@Override | |
public String loadInBackground() { | |
String searchQueryUrlString = args.getString(SEARCH_QUERY_URL_EXTRA); | |
if (searchQueryUrlString == null || searchQueryUrlString.isEmpty()) { | |
return null; | |
} | |
try { | |
URL url = new URL(searchQueryUrlString); | |
String searchResults = NetworkUtils.getResponseFromHttpUrl(url); | |
return searchResults; | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
@Override | |
public void deliverResult(String json) { | |
mJson = json; | |
super.deliverResult(json); | |
} | |
}; | |
} | |
@Override | |
public void onLoadFinished(Loader<String> loader, String data) { | |
if (null == data) { | |
showErrorMessage(); | |
} else { | |
showJsonData(data); | |
} | |
} | |
@Override | |
public void onLoaderReset(Loader<String> loader) { | |
// not used | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment