Android: How to add AsyncTaskLoader to this RecyclerView - android

[Update] Added repository link to download the project
I'm having this activity which connects to a URL to fetch data and display it using RecyclerView with a custom adapter. How can I edit this code to use AsyncTaskLoader instead of AsyncTask? here's the repository to download the very simple project Soonami tutorial app
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
public static QuakesAdapter quakesAdapter;
public static ArrayList<Event> eventsList = new ArrayList<>();
public static final String USGS_REQUEST_URL =
"https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2018-01-01&endtime=2018-12-01&minmagnitude=6&limit=50";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
quakesAdapter = new QuakesAdapter(this, eventsList);
//defining recyclerView and setting the adapter
quakesAdapter.notifyDataSetChanged();
FetchData fetchData= new FetchData();
fetchData.execute();
}
private class FetchData extends AsyncTask<String, Void, ArrayList<Event>> {
String myDdata = "";
String line = "";
#Override
protected ArrayList<Event> doInBackground(String... params) {
try {
//opening the connection
if (httpURLConnection.getResponseCode() == 200) {
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while(line != null){
line = bufferedReader.readLine();
myDdata = myDdata + line;
}
JSONObject jsonObject = new JSONObject(myDdata);
eventsList.clear();
JSONArray jsonArray = jsonObject.getJSONArray("features");
for(int i = 0; i < jsonArray.length(); i++){
//getting values of the 3 attributes
eventsList.add(new Event(title, time, tsunamiAlert));
}
if (inputStream != null) {
inputStream.close();
}
} else {
Log.e("Connection Error: ", "Error response code: " + httpURLConnection.getResponseCode());
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<Event> result) {
super.onPostExecute(result);
quakesAdapter.notifyDataSetChanged();
}
}
}
I have tested multiple examples but they have different codes and triggers multiple errors with my code like this one and still looking for a solution which makes my code works fine.

Set adpter in your recyclerview and then call the loader like this way:
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Event>> {
{
private RecyclerView recyclerView;
public static QuakesAdapter quakesAdapter;
public static ArrayList<Event> eventsList = new ArrayList<>();
public static final String USGS_REQUEST_URL =
"https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2018-01-01&endtime=2018-12-01&minmagnitude=6&limit=50";
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
quakesAdapter = new QuakesAdapter(this, eventsList);
//defining recyclerView and setting the adapter
recyclerView.setAdapter(quakesAdapter);
getSupportLoaderManager().initLoader(1, null, this).forceLoad();
}
#Override
public Loader<List<Event>> onCreateLoader ( int id, Bundle args){
return new FetchData(MainActivity.this);
}
#Override
public void onLoadFinished (Loader < List < Event >> loader, List < Event > data){
quakesAdapter.setData(data);
}
#Override
public void onLoaderReset (Loader < List < Event >> loader) {
quakesAdapter.setData(new ArrayList<Event>());
}
Performs actual task in background and returns the result.
private static class FetchData extends AsyncTaskLoader<List<Event>>{
String myDdata = "";
String line = "";
public FetchData(Context context) {
super(context);
}
#Override
public List<Event> loadInBackground () {
try {
List<Event> list = new ArrayList<Event>();
//opening the connection
if (httpURLConnection.getResponseCode() == 200) {
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while (line != null) {
line = bufferedReader.readLine();
myDdata = myDdata + line;
}
JSONObject jsonObject = new JSONObject(myDdata);
JSONArray jsonArray = jsonObject.getJSONArray("features");
for (int i = 0; i < jsonArray.length(); i++) {
//getting values of the 3 attributes
eventsList.add(new Event(title, time, tsunamiAlert));
}
if (inputStream != null) {
inputStream.close();
}
} else {
Log.e("Connection Error: ", "Error response code: " + httpURLConnection.getResponseCode());
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return eventsList;
}
}
Add a method in your adapter like this:
public void setData(List<Event> data) {
this.data=data;
notifyDataSetChanged();
}

Which kind of error do you encounter?
I suggest using Java Interface and CallBack method for your AsynkTask, in this scenario, whenever your AsynkTask task is done, it notify the Activity with that callback method and you can execute notifyDataSetChange method of the adapter.

Related

retrieve arraylist from AsyncTask class object after the doInBackground method is finished

i have classes in my projects that only does the server operations such as getting and putting data. i have class which populating list and then method to get this list. the problem is that i'm calling the "getList" method and the background operation hasent finished then i get null from the "getList" method
this is my AsyncTask class, as you can see the "getList" suppose to give me the list completed
public class GetRoomatesListActivity extends AsyncTask<String, String, String> {
private ArrayList<RoomateModel> tmpList;
private ArrayList<RoomateModel> completeList;
DBHelper db;
Context context;
public GetRoomatesListActivity(Context context){
this.context = context;
}
#Override
protected String doInBackground(String... params) {
db = DBHelper.getInstance(context);
HttpURLConnection connection = null;
BufferedReader reader = null;
tmpList = new ArrayList<RoomateModel>();
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("result");//creates array of Roomates of the selected apartment
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);//get the cuttent json object which is representaion of roomate object
String Fname = finalObject.getString("firstName");
String Lname = finalObject.getString("lastName");
String phone = finalObject.getString("phone");
RoomateModel item = new RoomateModel(Fname, Lname, phone);//creates roomates model with the current item data from the array
tmpList.add(item);//adds the roomate to the list of roomates
//add the roomates to local data base
db.addRoomate(item,apartment);
}
return null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
completeList = tmpList;
}
public ArrayList<RoomateModel> getList(){
return completeList;
}
}
and this is the class which im trying to get the list to in order to use it but its retrieving null
public class roomatesScreen extends Activity {
ListView items;
ArrayList<RoomateModel> list; //list to compare with the list rerived from GetRoomatesListActivity
RoomatesAdapter adapter;
DBHelper db;
ApartmentModel apartment;
SharedPreferences preferences;
GetRoomatesListActivity r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roomates_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
items = (ListView) findViewById(R.id.roomatesList);
db = DBHelper.getInstance(this);
Bundle bundle = getIntent().getExtras();
int number = bundle.getInt("number");
apartment = new ApartmentModel(number);// creates apartment model with the user's apartment number
final String num = Integer.toString(number);
r = new GetRoomatesListActivity(this);
r.execute("this is the link to my query" + num);
list = r.getList(); //here list is null
adapter = new RoomatesAdapter(roomatesScreen.this, list);
items.setAdapter(adapter);//here application crushes because of nullPointerExpeption
The best way is to perform the update on UI is in PostExecute method of AsyncTask..
At the time you are accessing it, the control is in the doInBackground method. So your list is null at that time.
put this
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
adapter = new RoomatesAdapter(roomatesScreen.this, tmpList);
items.setAdapter(adapter);/
}
into the onPostExecute().
2nd solution
Initialize the list when you are setting it to adapter. like:
list = new ArrayList();
and rest work (update the list and call notifyDataSetChanged() on adapter object) in onPostExecute().
Change doInBackground() method return type
public class GetRoomatesListActivity extends AsyncTask<String, String, ArrayList<Object>> {
private ArrayList<RoomateModel> tmpList;
private ArrayList<RoomateModel> completeList;
DBHelper db;
Context context;
public GetRoomatesListActivity(Context context){
this.context = context;
}
#Override
protected ArrayList<Object> doInBackground(String... params) {
db = DBHelper.getInstance(context);
HttpURLConnection connection = null;
BufferedReader reader = null;
tmpList = new ArrayList<RoomateModel>();
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("result");//creates array of Roomates of the selected apartment
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);//get the cuttent json object which is representaion of roomate object
String Fname = finalObject.getString("firstName");
String Lname = finalObject.getString("lastName");
String phone = finalObject.getString("phone");
RoomateModel item = new RoomateModel(Fname, Lname, phone);//creates roomates model with the current item data from the array
tmpList.add(item);//adds the roomate to the list of roomates
//add the roomates to local data base
db.addRoomate(item,apartment);
}
return null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
completeList = tmpList;
}
public ArrayList<RoomateModel> getList(){
return completeList;
}
}

How to get result on onPostExecute from a separate Asynctask class to another fragment class?

I try it but it not show anything, I thing I don't know how to get result of onPostExecute method from separate AsyncTask class to fragment class.
Please Help me...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager()
.beginTransaction()
.add(R.id.Fragment_Container, new ForecastFragment(),
ForecastTask.class.getSimpleName())
.commit();
}
2- AsyncTask class
public class ForecastTask extends AsyncTask<String, String, `List<MovieModel>> {`
private final String LOG_TAG = ForecastTask.class.getSimpleName();
private List<MovieModel> movieModelList;
public AsyncResponse delegate=null;
public ForecastTask(AsyncResponse listener) {
delegate = listener;
}
#Override
protected List<MovieModel> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(param[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject jsonObject = new JSONObject(buffer.toString());
JSONArray jsonArray = jsonObject.getJSONArray("results");
movieModelList= new ArrayList<>();
//adding JSON Array data into MovieModel Class object
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject finalObject = jsonArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setId(finalObject.getInt("id"));
movieModel.setTitle(finalObject.getString("title"));
movieModel.setPoster_path(finalObject.getString("poster_path"));
}
return movieModelList;
} catch (JSONException | IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public ForecastTask() {
super();
}
#Override
protected void onPostExecute( List<MovieModel> movieModels) {
delegate.processFinish(movieModels);
}
}
3- Fragment class
public class ForecastFragment extends Fragment implements AsyncResponse {
private String Popular = "http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxx";
private List<MovieModel> movieModels;
private static final String STATE_MOVIES ="state_movies";
CustomAdapter customAdapter=null;
GridView gridView=null;
View rootView=null;
ForecastTask forecastTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_main, container, false);
gridView=(GridView)rootView.findViewById(R.id.gridView);
movieModels=new ArrayList<MovieModel>();
forecastTask=new ForecastTask(this);
forecastTask.delegate = this;
forecastTask.execute(Popular);
customAdapter = new CustomAdapter(getActivity(), movieModels);
gridView.setAdapter(customAdapter);
return rootView;
}
#Override
public void processFinish(List<MovieModel> movieModels) {
this.movieModels=movieModels;
}
}
4- AsyncResponse Interface
public interface AsyncResponse {
void processFinish(List<MovieModel> movieModels);
}
You are not adding your Movie item in movieModelList. That's why it remains empty. You have to modify like -
movieModelList= new ArrayList<>();
//adding JSON Array data into MovieModel Class object
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject finalObject = jsonArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setId(finalObject.getInt("id"));
movieModel.setTitle(finalObject.getString("title"));
movieModel.setPoster_path(finalObject.getString("poster_path"));
movieModelList.add(movieModel); //Add this line
}
Also, You have to set or refresh the adapter in your processFinish() callback.
Because ForecastTask will run in different thread and is asynchronous.
#Override
public void processFinish(List<MovieModel> movieModels) {
this.movieModels=movieModels;
customAdapter = new CustomAdapter(getActivity(), movieModels);
gridView.setAdapter(customAdapter);
}

Identical Fragments - one works, one doesn't

I have two fragments each being inflated from a sliding menu. One fragment works as expected, the other one force closes the app. The Fragments are identical, except in name. the second has a runtime, fatal exception main in the log.
Here is the Fragment(s):
public class FeedZFragment extends Fragment {
private static final String TAG = "RecyclerViewExample";
private List<FeedZ> feedItemList = new ArrayList<FeedZ>();
//added static might remove
private static RecyclerView mRecyclerView;
private static MyRecyclerAdapterZ adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate( R.layout.fragment_recyclerview, container, false);
/* Allow activity to show indeterminate progress-bar */
getActivity().requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
/* Initialize recycler view */
mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.my_recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),2));
/*Downloading data from below url*/
final String url = "http://www.thisismysite.com/a.json";
new AsyncHttpTask().execute(url);
return rootView;
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
/* #Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}*/
#Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
Integer result = 0;
HttpURLConnection urlConnection = null;
try {
/* forming th java.net.URL object */
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
}else{
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
// setProgressBarIndeterminateVisibility(false);
/* Download complete. Lets update UI */
if (result == 1) {
adapter = new MyRecyclerAdapterZ(getActivity(), feedItemList);
mRecyclerView.setAdapter(adapter);
} else {
Log.e(TAG, "Failed to fetch data!");
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray products = response.optJSONArray("products");
/*Initialize array if null*/
if (null == feedItemList) {
feedItemList = new ArrayList<FeedZ>();
}
for (int i = 0; i < products.length(); i++) {
JSONObject product = products.optJSONObject(i);
FeedZ item = new FeedZ();
item.setTitle(product.optString("title"));
item.setImage_url(product.optString("image_url"));
item.setPackage_url(product.optString("package_url"));
item.setIds(product.optString("ids"));
feedItemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
the error is:
java.lang.NullPointerException
at com.nmthemes.WallFragment.onCreateView(WallFragment.java:44)
SOLUTION:
they weren't exactly identical.
getActivity().findViewById(R.id.my_recycler_view); should have been:
rootView.findViewById(R.id.my_recycler_view);
I changed it in one, not the other.

AsyncTask to fetch global game scores from a server

I am new to android and am completely puzzled by AsyncTasks. I need to create a leaderboard which will pull global leaderboard scores from a server.
I have posted below the two methods that were created in the LeaderboardsFragment which are used to access and display the scores - getGlobalScores and readStream.
I am unsure of how to use these in the AsyncTask - mostly how and what parameters to pass to the AsyncTask - most of the tutorials I have been looking at do not deal with 2D arrays. Any hints would be really appreciated, I am really having trouble understanding the literature surrounding this.
package uk.ni.appidemic.whackamole;
import java.io.BufferedReader;
public class LeaderboardsFragment extends Fragment {
AssetStore AS;
private TextView TopScores;
private String[][] global_scores = new String[10][3];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_leaderboards, container, false);
//Go and get the asset store from the activity
AS = WhackAMoleActivity.getAssetManager();
TopScores = (TextView) rootView.findViewById(R.id.leaderboards);
// Extract and display the top score text view from the preferences
displayLocalScores();
// this method is used to send a highscore to the server (name and score)
// this method may get pulled out to the gameloop as its the only place it should be used in the final game
// but this can be used for testing purposes atm (Server needs to be on)
// sendScoreGlobal("porter", 1001);
//async Get global scores from the server and display them - new thread
new AsyncOperation().execute();
...................
public void getGlobalScores() {
//gets global score in HTML format to be parsed
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL("http://62........./high_scores");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
/gets the data and stores the global scores in a 2d array
//it then displays to screen
public void readStream(InputStream in) {
BufferedReader reader = null;
try {
StringBuilder htmlIn = new StringBuilder();
StringBuilder globalScoreBuilder = new StringBuilder();
htmlIn.append("");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
htmlIn.append(line);
}
// String to be scanned to find the pattern.
String html = htmlIn.toString();
String regexPattern = "<td align=\"left\" style=\"padding-left:10px;\">(\\d+?)</td>|<td align=\"right\" style=\"padding-right:10px;\">(\\w+?)</td>";
// Create a Pattern object
Pattern patternObject = Pattern.compile(regexPattern);
// Now create matcher object.
Matcher matcherObject = patternObject.matcher(html);
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Trying to find regex matches");
TopScores.append("\n");
int nextFreePointer = 0;
int rowCount = 0;
while (matcherObject.find()) {
if (matcherObject.group(1) != null) {
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : " + matcherObject.group(1));
globalScoreBuilder.append(matcherObject.group(1) + " ");
global_scores[rowCount][nextFreePointer] = matcherObject.group(1);
nextFreePointer++;
}
if (matcherObject.group(2) != null) {
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : " + matcherObject.group(2));
globalScoreBuilder.append(matcherObject.group(2) + " ");
global_scores[rowCount][nextFreePointer] = matcherObject.group(2);
nextFreePointer++;
}
if (nextFreePointer > 2) {
nextFreePointer = 0;
rowCount++;
}
globalScoreBuilder.append("\n");
}
StringBuilder sb = new StringBuilder();
String lineSeparator = System.getProperty("line.separator");
for (String[] row : global_scores) {
sb.append(Arrays.toString(row)).append(lineSeparator);
}
String text = sb.toString();
TopScores.append("Global Top 10 Scores\n");
TopScores.append(text);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class AsyncOperation extends AsyncTask<String, Void, Void>{
protected void onPreExecute(){
}//end of onPreExecute
#Override
protected Void doInBackground(Void... values) {
}//doinBackground
protected void onProgressUpdate(Void... values){
}//onProgressUpdate
protected void onPostExecute(Void... result){
}//end of onPostExecute
}//end of AsyncOperation inner class
}//end of Leaderboards class
You should fetch your game score through a WebService class that extentds AsynTask. Below is my class that I am using in order to fetch remote data safely.
CODE:
public class WebServiceRestTask extends AsyncTask<HttpUriRequest, Void, Object> {
private static final String TAG = "WebServiceRestTask";
private AbstractHttpClient mClient;
private WeakReference<WebServiceRestCallback> mCallback;
private int ws_task;
public WebServiceRestTask(int ws_task) {
this(new DefaultHttpClient(), ws_task);
}
public WebServiceRestTask(AbstractHttpClient client, int task_number) {
mClient = client;
this.ws_task = task_number;
}
public interface WebServiceRestCallback {
public void onRequestSuccess(String response);
public void onRequestError(Exception error);
}
public void setResponseCallback(WebServiceRestCallback callback) {
mCallback = new WeakReference<WebServiceRestCallback>(callback);
}
#Override
protected Object doInBackground(HttpUriRequest... params) {
try {
HttpUriRequest request = params[0];
HttpResponse serverResponse = mClient.execute(request);
BasicResponseHandler handler = new BasicResponseHandler();
String response = handler.handleResponse(serverResponse);
return response + ws_task;
} catch (Exception e) {
Log.w(TAG, e);
return e;
}
}
#Override
protected void onPostExecute(Object result) {
if (mCallback != null && mCallback.get() != null) {
if (result instanceof String) {
mCallback.get().onRequestSuccess((String) result);
} else if (result instanceof Exception) {
mCallback.get().onRequestError((Exception) result);
} else {
mCallback.get().onRequestError(
new IOException("Unknown Error Contacting Host"));
}
}
}
}
Not at my workstation but think something like this should work.
public class AsyncOperation extends AsyncTask<String, Void, Void>{
private String[][] global_scores = new String[10][3];
protected void onPreExecute(){
// optionally show loading indicator
TopScores.append("\n");
}//end of onPreExecute
#Override
protected Void doInBackground(Void... values) {
try {
URL url = new URL("http://62........./high_scores");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}//doinBackground
protected void onProgressUpdate(Void... values){
}//onProgressUpdate
protected void onPostExecute(Void... result){
// optionally hide loading indicator
StringBuilder sb = new StringBuilder();
String lineSeparator = System.getProperty("line.separator");
for (String[] row : global_scores) {
sb.append(Arrays.toString(row)).append(lineSeparator);
}
String text = sb.toString();
TopScores.append("Global Top 10 Scores\n");
TopScores.append(text);
}//end of onPostExecute
private void readStream(InputStream in) {
BufferedReader reader = null;
try {
StringBuilder htmlIn = new StringBuilder();
StringBuilder globalScoreBuilder = new StringBuilder();
htmlIn.append("");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
htmlIn.append(line);
}
// String to be scanned to find the pattern.
String html = htmlIn.toString();
String regexPattern = "<td align=\"left\" style=\"padding-left:10px;\">(\\d+?)</td>|<td align=\"right\" style=\"padding-right:10px;\">(\\w+?)</td>";
// Create a Pattern object
Pattern patternObject = Pattern.compile(regexPattern);
// Now create matcher object.
Matcher matcherObject = patternObject.matcher(html);
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Trying to find regex matches");
int nextFreePointer = 0;
int rowCount = 0;
while (matcherObject.find()) {
if (matcherObject.group(1) != null) {
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : " + matcherObject.group(1));
globalScoreBuilder.append(matcherObject.group(1) + " ");
global_scores[rowCount][nextFreePointer] = matcherObject.group(1);
nextFreePointer++;
}
if (matcherObject.group(2) != null) {
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : " + matcherObject.group(2));
globalScoreBuilder.append(matcherObject.group(2) + " ");
global_scores[rowCount][nextFreePointer] = matcherObject.group(2);
nextFreePointer++;
}
if (nextFreePointer > 2) {
nextFreePointer = 0;
rowCount++;
}
globalScoreBuilder.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}//end of AsyncOperation inner class

Can I use AsyncTask inside ListFragment? or should I use AsyncTaskLoader?

I tried the code below and also tried the AsyncTaskLoader approach. The app crashes when I instantiate the AsyncTask. Pleas advise me on the best approach to load JSON in a list fragment inside tab host.
The code below is the tab fragment (I use action bar tabs in main activity):
public class TabTop extends ListFragment {
Context context = getActivity().getBaseContext();
String API_URL = "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/similar.json?apikey=crhhxb4accwwa6cy6fxrm8vj&limit=1";
ArrayList<Deal> deals;
DealsListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
#SuppressWarnings("unused")
int a = 0;
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
GetTopDeals getTopDeals = new GetTopDeals(context);
getTopDeals.execute(API_URL);
super.onActivityCreated(savedInstanceState);
}
class GetTopDeals extends AsyncTask<String, Void, ArrayList<Deal>>{
ProgressDialog progressDialog;
public GetTopDeals(Context activity) {
this.progressDialog = new ProgressDialog(activity);
}
#Override
protected void onPostExecute(ArrayList<Deal> result) {
adapter = new DealsListAdapter(context, result);
setListAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progressDialog.setCancelable(true);
progressDialog.setProgress(0);
progressDialog.setMessage("loading Top deals...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
super.onPreExecute();
}
#Override
protected ArrayList<Deal> doInBackground(String... urls) {
String response = sendRequest(urls[0]); // make request for json
return processResponse(response); // parse the Json and return ArrayList to postExecute
}
private String sendRequest(String apiUrl) {
BufferedReader input = null; // get the json
HttpURLConnection httpCon = null; // the http connection object
StringBuilder response = new StringBuilder(); // hold all the data from the jason in string separated with "\n"
try {
URL url = new URL(apiUrl);
httpCon = (HttpURLConnection) url.openConnection();
if (httpCon.getResponseCode() != HttpURLConnection.HTTP_OK) { // check for connectivity with server
return null;
}
input = new BufferedReader(new InputStreamReader(httpCon.getInputStream())); // pull all the json from the site
String line;
while ((line = input.readLine()) != null) {
response.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpCon != null) {
httpCon.disconnect();
}
}
return response.toString();
}
}
public ArrayList<Deal> processResponse(String response) {
try {
JSONObject responseObject = new JSONObject(response); // Creates a new JSONObject with name/value mappings from the JSON string.
JSONArray results = responseObject.getJSONArray("movies"); // Returns the value mapped by name if it exists and is a JSONArray.
deals = new ArrayList<Deal>();
for (int i = 0; i < results.length(); i++) { // in this loop i copy the json array to movies arraylist in order to display listView
JSONObject jMovie = results.getJSONObject(i);
int api_id = jMovie.getInt("id");
String name = jMovie.getString("title");
String content = jMovie.getString("synopsis");
JSONObject posters = jMovie.getJSONObject("posters");
String image_url = posters.getString("profile");
}
}catch (JSONException e) {
e.printStackTrace();
}
return deals;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getActivity().getBaseContext(), DealInformation.class);
startActivity(intent);
super.onListItemClick(l, v, position, id);
}
}
Make your asynctask in his own file.
And when your asynctask is finish, implement OnPostExecute which is automatically call. Notify your adapter by a notifyDataSetChanged like that :
#Override
protected void onPostExecute(List<NewItem> list) {
Adapter.getListe().clear();
Adapter.getListe().addAll(list);
Adapter.notifyDataSetChanged();
}
thank you guys,
i want to post my answer. after some research i decided to go with AsyncTaskLoader.
this is my code
public class TabOurPicks extends ListFragment implements LoaderCallbacks<String[]> {
// when activity loads- onActivityCreated() calls the initLoader() who activate onCreateLoader()
#Override
public void onActivityCreated(Bundle savedInstance) {
super.onActivityCreated(savedInstance);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, new String[]{}));
getLoaderManager().initLoader(0, null,this).forceLoad();
}
// onCreateLoader instantiate the asynctaskloaser who work in bg
#Override
public RSSLoader onCreateLoader(int arg0, Bundle arg1) {
return new RSSLoader(getActivity()); //
}
// after bg process invoke onLoadFinished() who work in ui thread
#Override
public void onLoadFinished(Loader<String[]> loader, String[] data) {
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, data
) );
}
#Override
public void onLoaderReset(Loader<String[]> arg0) {
// TODO Auto-generated method stub
}
and this is the inner class for the loader:
static public class RSSLoader extends AsyncTaskLoader<String[]>
{
public RSSLoader(Context context) {
super(context);
}
#Override
public String[] loadInBackground() {
String url = "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/similar.json?apikey=crhhxb4accwwa6cy6fxrm8vj&limit=1";
String response = sendRequest(url);
return processResponse(response);
}
private String sendRequest(String url) {
BufferedReader input = null; // get the json
HttpURLConnection httpCon = null; // the http connection object
StringBuilder response = new StringBuilder(); // hold all the data from the jason in string separated with "\n"
try {
URL apiUrl = new URL(url);
httpCon = (HttpURLConnection) apiUrl.openConnection();
if (httpCon.getResponseCode() != HttpURLConnection.HTTP_OK) { // check for connectivity with server
return null;
}
input = new BufferedReader(new InputStreamReader(httpCon.getInputStream())); // pull all the json from the site
String line;
while ((line = input.readLine()) != null) {
response.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpCon != null) {
httpCon.disconnect();
}
}
return response.toString();
}
private String[] processResponse(String response) {
String[] deals = null;
try {
JSONObject responseObject = new JSONObject(response); // Creates a new JSONObject with name/value mappings from the JSON string.
JSONArray results = responseObject.getJSONArray("movies"); // Returns the value mapped by name if it exists and is a JSONArray.
deals = new String[10];
for (int i = 0; i < 9; i++) { // in this loop i copy the json array to movies arraylist in order to display listView
JSONObject jMovie = results.getJSONObject(i);
String name = jMovie.getString("title");
deals[i] = name;
}
}catch (JSONException e) {
e.printStackTrace();
}
return deals;
}
}
}
It doesn't matter if your asynctask has its own file. You just don't want your activity to extends asynctask as this would make your activity asynchronous - but this is impossible to do anyways due to java's double inheritance rule.
Based on the architecture of your app and your programming style the asyntask can be an inner class in the activity. on the PostExecute method make sure you have given data to your adapter and that the adapter is set to the list, then just run notifyDataSetChanged().
Assuming your asynctask is loading data from cache or the network you are on the right track with your approach to this.

Categories

Resources