I have an AsyncTask(.execute()) with an onPostExecute method. This method starts another AsyncTask(.execute()) that needs to be done before continuing the execution of the first onPostExecute. Is it possible to pause the first thread and to wait for the second thread to finish? I need the result from the second postExecute method in order to finish the first postExecute.
An example below:
public class RetrieveData extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... strings) {
HttpURLConnection conn = null;
try {
URL url = new URL(strings[0]);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String linieNoua = "";
String crlf = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder();
while((linieNoua = br.readLine()) != null) {
sb.append(linieNoua);
sb.append(crlf);
}
conn.disconnect();
return sb.toString();
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
RetrieveData retrieveData = new RetrieveData() {
#Override
protected void onPostExecute(String s) {
if (s != null) {
retrieveTransport(transportRegNr);
} else {
Toast.makeText(getApplicationContext(), R.string.login_server_error, Toast.LENGTH_LONG).show();
}
}
};
retrieveData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"http://192.168.0.101:3000/route/" + prefs.getString("email",null));
}
private void retrieveTransport(String regNr){
RetrieveData retrieveData = new RetrieveData() {
#Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONObject jsonObject = new JSONObject(s);
String model = jsonObject.getString("model");
String regNr = jsonObject.getString("regNr");
int type = jsonObject.getInt("type");
int seats = jsonObject.getInt("seats");
t = new Transport(model,regNr,null,seats,type);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), R.string.login_server_error, Toast.LENGTH_LONG).show();
}
}
};
retrieveData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"http://192.168.0.101:3000/transport/registryNr/" + regNr);
}
If I use the execute method, onPostExecute from retrieveTransport(String regNr) is never called. If I use executeOnExecutor, they are running simultaneously, and that's not good, either. I need to finish the first retrieveTransport; without that, I can't continue the first onPostExecute.
use
getStatus()
checks whether the the AsyncTask is pending, running, or finished.and when finsh start your new task.like:
if(retrieveTransport.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(retrieveTransport.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(retrieveTransport.getStatus() == AsyncTask.Status.FINISHED){
// START NEW TASK HERE
}
example for your app:
if (retrieveTransport!= null && retrieveTransport.getStatus() == AsyncTask.Status.FINISHED) {
//START retrieveData TASK HERE
}
else
{
//IGNORE
}
Related
I want to show string from another string in my MainActivity, but the string is getting printed in console. Here is my code:
public class MainActivity extends AppCompatActivity {
Button start;
public TextView showText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showText= (TextView)findViewById(R.id.textView);
start = (Button)findViewById(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RetrieveFeedTask click1 = new RetrieveFeedTask();
click1.execute();
showText.setText(click1.getString());
}
});
}
}
And the class:
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
static final String API_URL = "http://numbersapi.com/random/trivia?json";
private Exception exception;
public String finalString;
protected void onPreExecute() { }
protected String doInBackground(Void... urls) {
try {
URL url = new URL(API_URL );
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((finalString = bufferedReader.readLine()) != null) {
stringBuilder.append(finalString).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
public String getString() {
return this.finalString;
}
}
You require the finalString before it's populated with your data. the onPostExecute is executed after the doInBackground so you should pass your text view to your task and set it's value in the onPostExecute
public TextView showText;
public RetrieveFeedTask(TextView showText) { this.showText = showText; }
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
showText.setText(finalString ); // add this
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
The problem is that showText.setText(click1.getString()); of your activity is called earlier than finalString = object.getString("text"); of your task.
Solution:
Create an interface:
public interface DataCallback {
void onNewData(String data);
}
and implement it in your activity:
public class MainActivity extends ... implements DataCallback
public void onNewData(String data) {
showText.setText(data);
}
Pass the interface to your asynctask when you create it:
RetrieveFeedTask click1 = new RetrieveFeedTask(this);
Call the interface inside the task in onPostExecute() to notify the activity that there is new data:
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
callback.onNewData(finalString);
i am making application that have scroll listener that add data from multiple URL
but when i scroll the list jump to first position and than load the URL i know that the adapter in my a sync task get executed every time i load new URL task when i load new item but i don't know how to fix it
public class jsontask extends AsyncTask<String, String, List<newsmodel>> {
#Override
protected List<newsmodel> doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
if (connectiondetector.isConnected()) {
connection.addRequestProperty("Cache-Control", "max-age=0");
} else {
moviemodelList.addAll((List<newsmodel>) cacheThis.readObject(
technology.this, fileName));
}
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("articles");
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalobject = parentarray.getJSONObject(i);
newsmodel newsmodel = new newsmodel();
newsmodel.setAuthor(finalobject.getString("author"));
if (finalobject.isNull("author")) {
}
newsmodel.setDescription(finalobject.getString("description"));
newsmodel.setTitle(finalobject.getString("title"));
newsmodel.setImage(finalobject.getString("urlToImage"));
newsmodel.setUrl(finalobject.getString("url"));
newsmodel.setPublishedAt(finalobject.getString("publishedAt"));
cacheThis.writeObject(technology.this, fileName, moviemodelList);
moviemodelList.add(newsmodel);
}
return moviemodelList;
} catch (MalformedURLException e) {
e.printStackTrace();
return moviemodelList;
} catch (IOException e) {
e.printStackTrace();
return moviemodelList;
} catch (JSONException e) {
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (connection != null) {
}
try {
if (reader != null) {
reader.read();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return moviemodelList;
}
#Override
protected void onPostExecute(List<newsmodel> result) {
super.onPostExecute(result);
newsadapter adapter = new newsadapter(getApplicationContext(), R.layout.row, result);
lvnews.setAdapter(adapter);
}
}
public class newsadapter extends ArrayAdapter {
private List<newsmodel> moviemodelList;
private int resource;
private LayoutInflater inflater;
public newsadapter(Context context, int resource, List<newsmodel> objects) {
super(context, resource, objects);
moviemodelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}`
and this is how i excute my a sync task
protected void onStart() {
super.onStart();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
moviemodelList.clear();
new jsontask().execute("https://newsapi.org/v1/articles?source=engadget&sortBy=top&apiKey=ade8f00a634b4825a028837ec107afae");
lvnews.setOnScrollListener(new EndlessScrollListener() {
#Override
public boolean onLoadMore(int page, int totalItemsCount) {
new jsontask().execute("url1");
new jsontask().execute("url2");
new jsontask().execute("url3");
new jsontask().execute("url4");
new jsontask().execute("url5");
new jsontask().execute("url6");
return false;
}
});
}
Remove these lines from onPostExecute
newsadapter adapter = new newsadapter(getApplicationContext(), R.layout.row, result);
lvnews.setAdapter(adapter);
You are setting adapter eveytime after executing doInBackground. You need to do it only once. You can do it in onCreate
The basic methods used in an android AsyncTask class are defined below
:
doInBackground() : This method contains the code which needs to be executed in background. In this method we can send results multiple
times to the UI thread by publishProgress() method. To notify that the
background processing has been completed we just need to use the
return statements
onPreExecute() : This method contains the code which is executed before the background processing starts
onPostExecute() : This method is called after doInBackground method completes processing. Result from doInBackground is passed to
this method
onProgressUpdate() : This method receives progress updates from doInBackground method, which is published via publishProgress method,
and this method can use this progress update to update the UI thread
Please refer this link to know how Async task
After getting first url response call for second new jsontask().execute("url2"); then call for third, fourth and so on.
Make a common code to reuse it again and again.
try this link : http://www.devexchanges.info/2015/03/android-listview-dynamically-load-more.html
I am having trouble with my code where i have my Activity which i use to call google api's and retrieve jsons, deserialize them and use it's Polylines to draw on the map.
The problem is that getMapAsync() which sends the callback for onMapReady() (which is used to create the map) is executed immediately after executing my Async Tasks which retrieves necessary data to create the map.
How can i make this happen without stopping the UI thread? I tried doing this calling .execute.get() which freeze the UI thread. But if i do that, i won't be able to use ProgressDialog to inform the users about the delay for fetching data from the servers, which they will be exposed to a frozen UI until the task is complete. How can i do this?
public class RouteAssistantActivity extends Activity implements OnMapReadyCallback{
public GoogleMapsDirectionsResponse dirRes;
public GoogleMapsDistanceResponse disRes;
public String jsonString;
private String mapsAPIKey;
private String directionsBaseURL;
private String distanceBaseURL;
MapFragment mapFragment;
private ProgressDialog progress;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ra_route_assisstant);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.ra_map);
progress = new ProgressDialog(RouteAssistantActivity.this);
progress.setTitle("Please Wait");
progress.setMessage("Retrieving Data from the Server");
progress.setIndeterminate(true);
try {
ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
if (appInfo.metaData != null) {
mapsAPIKey = appInfo.metaData.getString("com.google.android.maps.v2.API_KEY");
directionsBaseURL = appInfo.metaData.getString("com.google.android.maps.directions.baseURL");
distanceBaseURL = appInfo.metaData.getString("com.google.android.maps.distance.baseURL");
}
} catch (PackageManager.NameNotFoundException e) {
Log.e("Meta Error", "Meta Data not found. Please check the Manifest and the Meta Data Package Names");
e.printStackTrace();
}
//Test
String directionsURL = directionsBaseURL+"origin=6.948109,79.858191&destination=6.910176,79.894347&key="+mapsAPIKey;
String distanceURL = distanceBaseURL+"units=metric&origins=6.948109,79.858191&destinations=6.910176,79.894347&key="+mapsAPIKey;
Log.e("CA Debug","URL : " + directionsURL);
Log.e("CA Debug","URL : " + distanceURL);
new configurationSyncTask().execute(distanceURL,"distance");
new configurationSyncTask().execute(directionsURL, "direction");
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng rajagiriya = new LatLng(6.910176, 79.894347);
String points = dirRes.getRoutes().get(0).getOverviewPolyline();
List<LatLng> list = PolyUtil.decode(points);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(rajagiriya, 13));
googleMap.addMarker(new MarkerOptions()
.title("Rajagiriya")
.snippet("My Place")
.position(rajagiriya));
googleMap.addPolyline(new PolylineOptions()
.geodesic(false)
.addAll(list)
.color(Color.RED)
.width(25));
}
private class configurationSyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
progress.show();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
String type = params[1];
Log.d("CA Debug", getClass().getSimpleName() + " --> Real URL : " + url);
Log.d("CA Debug", getClass().getSimpleName() + " --> doInBackground requesting content");
jsonString = requestContent(url);
// if the output is null, stop the current task
if (jsonString == null) {
Log.d("CA Debug", getClass().getSimpleName() + " --> Stopping Async Task");
this.cancel(true);
Log.d("CA Debug", getClass().getSimpleName() + " --> Async Task Stopped");
}
return type;
}
#Override
protected void onPostExecute(String types) {
if (types.equalsIgnoreCase("distance")) {
disRes = GMapsDistanceResponseJSONDeserializer.deserialize(jsonString);
} if (types.equalsIgnoreCase("directions")) {
dirRes = GMapsDirectionsResponseJSONDeserializer.deserialize(jsonString);
}
progress.dismiss();
}
}
public String requestContent(String url) {
Log.d("CA Debug",getClass().getSimpleName()+" --> URL : "+url);
try {
URL urlObj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();
con.setChunkedStreamingMode(0);
con.setRequestMethod("GET");
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null,null, new SecureRandom());
con.setSSLSocketFactory(sc.getSocketFactory());
InputStream clientResponse;
String jsonString;
int status = con.getResponseCode();
if(status >= HttpURLConnection.HTTP_BAD_REQUEST){
Log.d("CA Debug", getClass().getSimpleName()+" --> Bad Request");
jsonString = null;
} else {
Log.d("CA Debug", getClass().getSimpleName()+" --> converting Stream To String");
clientResponse = con.getInputStream();
jsonString = convertStreamToString(clientResponse);
}
Log.d("CA Debug", getClass().getSimpleName()+" --> JSON STRING : " + jsonString);
return jsonString;
} catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {
Log.d("CA Debug", getClass().getSimpleName()+" --> Error when creating an Input Stream");
e.printStackTrace();
}
return null;
}
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}
}
Quick and somewhat dirty solution would be to execute both AsyncTasks on a single AsyncTask and then on its onPostExecute code invoke getMapAsync. this way you will be sure your tasks finished before you dealing with map's readyness.
Firstly, run tasks after onMapReady because you will get rid of
concern of ready map.
Your async tasks are not parallel, they working on background but second one will be executed after first one completed, check this link
Move some parts of onMapReady to onPostExecute, something like below
Move
#Override
protected void onPostExecute(String types) {
if (types.equalsIgnoreCase("distance")) {
disRes = GMapsDistanceResponseJSONDeserializer.deserialize(jsonString);
}if (types.equalsIgnoreCase("directions")) {
dirRes = GMapsDirectionsResponseJSONDeserializer.deserialize(jsonString);
String points = dirRes.getRoutes().get(0).getOverviewPolyline();
List<LatLng> list = PolyUtil.decode(points);
googleMap.addPolyline(new PolylineOptions()
.geodesic(false)
.addAll(list)
.color(Color.RED)
.width(25)
);
}
}
AsyncTask.SERIAL_EXECUTOR is used to force AsyncTask to execute in Serial Fashion.
More over for your case a little trick will do the job.
Create call back for same AsyncTask and pass different parameters to differentiate the functions.
Now in the second call back initiate mapFragment.getMapAsync(this);
public class MainFragment ...
{
DataDownloader dataDownloader;
int processCount=1;
void initiateProcessFirst(){
new DataDownloader(this,processCount ).execute();
}
public void initiateSecondProcess(){
processCount++;
new DataDownloader(this,processCount ).execute();
}
public void secondProcessCompleted(){
mapFragment.getMapAsync(this);
}
}
AsyncTask Logic goes like the below
public class DataDownloader extends AsyncTask<Void,Void,Boolean> {
MainFragment context;
int processCount;
public DataDownloader(MainFragment context ,int processCount){
this.context=context;
this.processCount=processCount;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status=false;
// Do logic according to the Process Count
return status;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if(processCount==1)
context.initiateSecondProcess();
else
context.secondProcessCompleted();
}
}
I've been working on an android app ... I am stuck at a point ... after getting the JSON data from the internet I am having trouble to show it in the ListView ... Below is my code ...
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.name_lst_view,
R.id.name_list_view_textview,
blogTitles
);
ListView listView = (ListView) rootView.findViewById(R.id.listview_name);
listView.setAdapter(titleAdapter);
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
}
}
}
From the above code you can see that i am getting that data through doInBackground method of AsyncTask ... Data is coming through perfectly as I can see through the logcat ... The issue is somewhere in this method which I can't seem to figure out ..
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
The above method is called in onPostExecute I mean if i print to logcat within this method I can see the results being printed but when I try to show those results in the onCreateView method results don't show up not even in the logcat ... Any help will be appreciated ... Thanks
Change your code as following:
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
ListView listView;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
listView = (ListView) rootView.findViewById(R.id.listview_name);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
return rootView;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.name_list_view,
R.id.name_list_view_textview,
blogTitles
);
listView.setAdapter(titleAdapter);
}
}
}
Use same array list in both update and initialize so globally declare a single array list and update it in updateList() method,
Try like this,
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];//remove this and use the
//same as you are using in adapter
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
titleAdapter.notifyDataSetChanged();//here
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
OR even you can use in onPostExecute
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
titleAdapter.notifyDataSetChanged();//here
}
find the listview : ListView listView = (ListView) rootView.findViewById(R.id.listview_name); before calling
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
and put this line listView.setAdapter(titleAdapter); in your onPostExecute method.
Can anyone explain why AsyncTask comes with big delay and only in one case, and that is when I have wifi network but there is no internet connectivity on that network.
What could be the reason for that, and is there a way to make bigger priority on async task?
I have had that problem before, solved it by adding onPreExecute
in order to check if there is internet connection before attempting to execute the DoInBackground, check out the code below:
public class httpGetProduct extends AsyncTask<Void,Void,String> {
String result, rs;
JSONArray jArray;
String itemcode="",price,desc_ar,desc_en;
#Override
protected void onPreExecute() {
super.onPreExecute();
isOnline=ping(); // use ping if connecting to a certain local ip address
isOnline= hasInternetConnection();// use this if your connecting to internet
}
#Override
protected String doInBackground(Void... params) {
if(isOnline) // executes only if online
try {
String link = "http://"+ip+"/PriceCheckerWS.asmx/get_product_data?barcode="+barcode;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
// do somthing with the result if you need it
rs = "sucessful";
} catch (Exception e) {
rs = "Fail";
}
return rs;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
public boolean ping() {
String[] separated = ip.split(":");
String hostip=separated[0];
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 " + hostip);
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
public boolean hasInternetConnection() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo i = cm.getActiveNetworkInfo();
if (i != null) {
if (!i.isConnected())
return false;
if (!i.isAvailable())
return false;
}
if (i == null)
return false;
} else
return false;
}
catch (Exception e){
return false;
}
internet=true;
return true;
}