Issue
I had three classes: MainActivity
, Temp
(extends AsyncTask
) and HttpHandler
.
I am trying to call Temp
in MainActivity
. And in Temp
, it will call HttpHandler
to get JSON from URL, and finally return it to MainActivity
.
But it can't get anything from the URL.
I have searched this problem online, some people said its about UI thread, but I don't understand why.
Also, is there anyway to make the connection in separated class? Because I have several activities need to connect to internet, and I dun want to copy and paste the extended AsyncTask
class as private class in all the other activities.
Solution
Android does not allow some tasks to run in the main thread, such as http requests, which will slow down main application.You have to do this kind of works in the background with a seperate thread.
AsyncTask and AsyncTaskLoader are good choices to achieve this job. [https://developer.android.com/reference/android/os/AsyncTask.html] [https://developer.android.com/reference/android/content/AsyncTaskLoader.html]
Use AsyncTaskLoader if your work can take a long time and you dont wan't to have memory leaks in some cases.
As a starting point I want to present you the following information:
At your main activity, implement this.
implements LoaderManager.LoaderCallbacks<List<Your Data Type To Fetch>>
Then override these methods:
public Loader<List<YourDataType>> onCreateLoader(int i, Bundle bundle)
public void onLoadFinished(Loader<List<YourDataType>> loader, List<YourDataType> mList)
public void onLoaderReset(Loader<List<YourDataType>> loader)
Now create a loader in a new class like this:
public class SampleLoader extends AsyncTaskLoader<List<YourDataType>>
Override these methods in loader class:
public List<YourDataType> loadInBackground()
protected void onStartLoading()
loadInbackground
method will be your main method to do tasks.onStartLoading
method will be called when loader starts. use forceLoad()
in it. [https://developer.android.com/reference/android/content/Loader.html#forceLoad()]
Finally , creating and starting a loader, use code below in main activity onCreate()
method.
getLoaderManager().initLoader(1, null, this);
Note:1 is a loader identifier number, you can use different numbers.
Note: For a http request with a url and get method:
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
Answered By - ACrescendo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.