get dynamic url with json in listview - java

im new programmer in android, i write program to get image url and show the image in list view, my program work correct and can show me the images but when i want to show image i should use static url, but i want to use static link to get all image url with json and show it in list view.
i have json class to get image url but i dont know how to use it in
private String imageUrls[] to get image dynamic url from my static link.
***string url is static link in mainactivity to get image url with json.
my mainactivity class:
public class MainActivity extends Activity {
private final String url="http://192.168.1.4:81/upload/images.php";
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
adapter = new LazyAdapter(this, imageUrls);
list.setAdapter(adapter);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
private String imageUrls[] = {
"http://www.technotalkative.com/wp-content/uploads/2012/09/tt_listview1-171x300.png",
"http://www.technotalkative.com/wp-content/uploads/2012/11/f-DayDream-Example-Landscape.png",
};
}
and json class:
class get url extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("login");
pd.show();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> parms=new ArrayList<>();
JSONObject json=jParser.makeHTTPRequest(url,"GET");
try {
int t=json.getInt("t");
if(t==1){
s=json.getJSONArray("travel");
for(int i=0;i<s.length();i++){
String url_image=c.getString("url_image");
HashMap<String,String>map=new HashMap<String,String>();
map.put("url_image",url_image);
P.add(map);
}
}else {
Toast.makeText(MainActivity.this,"No Data Found",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

It is much more convenient to use Gson library gor parsing json response to java objects instead of extracting fields manually. It is also a good practice ( more convenient) to use Retrofit library instead of asynctasks - see https://stackoverflow.com/a/38002999/6175778 post

Related

Blinking screen when using AsyncTask

Hey guys I know this is a common problem, Im using a AsyncTaskActivity to have a JSON parser parse some json behind the scences of a app and pump a listview with an arrayadapter. This is my code code in my mainActivity.java. My screen flickers whenever I get to the belwo activity.
setContentView(R.layout.activity_see_schedule_activity);
this.setTitle("Activity Schedule");
//Log.e("ID see schedule#",getIntent().getExtras().getString("id#"));
RequestQueue queue = Volley.newRequestQueue(see_schedule_activity.this);
StringRequest request = new StringRequest(Request.Method.POST, httpUpdateRoutines, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(see_schedule_activity.this, "" + response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(see_schedule_activity.this, "Data Not Fetched " + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
//Log.e("ID see schedule#",getIntent().getExtras().getString("id#"));
map.put("residentid", getIntent().getExtras().getString("id#"));
return map;
}
};
queue.add(request);
new AsyncTaskParseJson(this).execute();
ArrayList<String> schedulelist = getIntent().getExtras().getStringArrayList("tasks_filled");
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, schedulelist);
ListView listView = (ListView) findViewById(R.id.schedulelist);
listView.setAdapter(adapter);
My AsyncTaskparseJson.java
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
private Context c;
String schedule;
String activityid;
String routine;
String[] tasks;
ArrayList<String> schedulelist = new ArrayList<String>();
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://www.wirelesshealth.wayne.edu/nhcheckup/getData(justin).php";
// contacts JSONArray
JSONArray dataJsonArr = null;
public AsyncTaskParseJson(Context applicationContext) {
this.c=applicationContext;
}
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
HashMap<Integer, String> hm = new HashMap<Integer, String>();
-----------------------some hash -----------------
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("schedule");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
Log.e("doInBackground","YOU GOT HERE");
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
activityid = c.getString("activityid");
-------------------------------Pasres object c --------------
}
Intent intent = new Intent(c,see_schedule_activity.class);
-- passes back arraylist -------------- intent.putStringArrayListExtra("tasks_filled",schedulelist);
this.c.startActivity(intent);
((Activity)c).finish();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
// Intent intent = new Intent(see_schedule_activity.this,see_schedule_activity.class);
// intent.putExtra("tasks_filled",tasks);
// this.c.startActivity(intent);
// ((Activity)c).finish();
}
}
I did a bit of troubleshotting and found out the error has to do with the placement of the intent that's passed a array list. But here's the problem, if I put it in the doinBackground() the screen flashes rapidly (which is prolly becuase it keeeps calling the (setContentView(R.layout.activity_see_schedule_activity);) but if I keep it in onPostExcute nothing happens (hte arraylist isnt pumping the listview). So im a bit stumped, any help would be appreciated thanks!
As I said in my comment, you enter a recursive call between the activity and the AsyncTask as you start the same activity again with an Intent. Instead, as you already pass the activity instance to the AsyncTask, simply create an update method in the activity and use that from the AsyncTask:
// field in see_schedule_activity
private ArrayAdapter<String> adapter;
// which you'll initialize in onCreate()
// with an empty list, as you don't yet have the data
...
adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, new ArrayList<>());
ListView listView = (ListView) findViewById(R.id.schedulelist);
listView.setAdapter(adapter);
... rest of onCreate()
public void update(List<String> results) {
adapter.clear();
adapter.addAll(results);
}
Then implement correctly the AsyncTask:
public class AsyncTaskParseJson extends AsyncTask<String, Void, List<String>> {
private see_schedule_activity activity;
//... the rest
public AsyncTaskParseJson(see_schedule_activity activity) {
this.activity = activity;
}
#Override
protected List<String> doInBackground(String... arg0) {
// create scheduleList
return scheduleList;
}
#Override
protected void onPostExecute(List<String> results) {
activity.update(results);
}
//...
This is not a good implementation of the AsyncTask but should get you going.

passing String to AsyncTask class

I have the below class
public class Faculty extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "name";
static String DESIGNATION = "designation";
//static String POPULATION = "population";
static String FAC_IMG = "fac_img";
static String url;
#Override
public void onCreate(Bundle savedInstantState){
super.onCreate(savedInstantState);
// Get the view from listview_main.xml
setContentView(R.layout.faculty_list);
String data = getIntent().getStringExtra("Dpmt");
if(data.equals("DOCScience")){
url="Department%20Of%20Computer%20Science";
}
if(data.equals("DOIT")){
url="Department%20Of%20Information%20%26%20Technology";
}
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute(url);
//String url="http://192.168.170.89/bbau_faculty.php?dept="+Dept;
}
private class DownloadJSON extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Faculty.this);
// Set progressdialog title
//mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(String... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String url1=params[0];
// Retrieve JSON Objects from the given URL address
System.out.println(url1);
jsonobject = JSONfunctions.getJSONfromURL("http://192.168.170.89/bbau_faculty.php?dept="+url1);
I am calling the DownloadJSON class
using the line
new DownloadJSON().execute(url);
In the DownloadJSON class the method
doInBackground(String... params) I want to receive the url passed in execute(url)
String url1=params[0];
But url1 is printing as null.
But url1 is printing as null.
you are doing in the correct way. If you are receinving null as value it means, in your case, that
String data = getIntent().getStringExtra("Dpmt");
is not neither DOCScience nor DOIT, and url remains initialized with with the default value (null for String declared as class member)
probably because data never equals DOCScience nor DOIT. Make sure you are getting and setting data with the correct key. Data might also be "" when setting.
Try to check url value before pass it to AsyncTask :
if(url !=null && url.trim().length()>0){
new DownloadJSON().execute(url);
}
Also use else-if leader instead of multiple if in case of check data value which either DOCScience or DOIT :
if(data.equals("DOCScience")){
url="Department%20Of%20Computer%20Science";
}else if(data.equals("DOIT")){
url="Department%20Of%20Information%20%26%20Technology";
}else{
// no match
}

Networking with Volley

Please could you help me with a network request I am trying here.
I have 2 Classes Network.class and MainActivity.class. I have a TextView in the MainActivity Class that I would like to be replaced with the text I get from the Network call in the Network Class. Problem I am currently having is I cant initiate the network call in the Network Class when the MainActivity Class is loaded when the application starts?
Below is the Code to MainActivity:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.text);
String test = Network.userName;
tv.setText(test);
}
}
and below is the network class that I would like to do the network call and the response will need to replace the text in the TextView in the MainActivity Class.
Network Class:
public class Network extends Activity{
public static String userName;
private String jsonResponse;
String url_home = "http://www.someurl.com";
private void postData(final TextView tv) {
final RequestQueue request = Volley.newRequestQueue(this);
JsonObjectRequest postReq = new JsonObjectRequest(Request.Method.GET, url_home, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
jsonResponse = "";
for(int i = 0; i< response.length(); i++) {
String userName = response.getString("DOTWBannerHD");
System.out.println("++++++++++++++++++++++++++++++++++++++++++++userName = " + userName);
jsonResponse += userName;
System.out.println("++++++++++++++++++++++++++++++++++++++++++++JsonResponse = " + jsonResponse);
}
tv.setText(jsonResponse);
} catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error [" + error + "]");
}
}) {
#Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("Accept", "application/json");
System.out.println(headers);
return headers;
}
};
request.add(postReq);
}
}
I am very new to Android and am battling to call the postData method from the second activity, in the MainActivity? The issue I get is that the TextView has text hard coded in the XML but when I run the Application it is blank? It's like, either the response is blank, but I doubt its that because the code I put in the Network Class (System.out.println("++++++++++++++++++++++++++++++++++++++++++++userName = " + userName);) isn't showing up in the Terminal which makes me think that its not running the postData method at all or the response is not working but it just sets the TextView to blank?
You cannot change the GUI from an async-task.
As JsonObjectRequest works asynchronous you should run tv.setText(jsonResponse); on the main thread using:
runOnUiThread(new Runnable() {
public void run() {
tv.setText(jsonResponse);
}
});
Following up on my comment, the reason your are not seeing anything in the terminal is because you're not calling you postData method so it's never executed.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.text);
Network network = new Network();
network.postData(tv);
}
}
and make Network a normal class not an Activity.
public class Network{
////The variables and your postData method here
}

Error in connect to website jsoup project(The method connect(String) is undefined for the type Jsoup)

i want to fetch data from website to my android app ,so i used jsoup.
Document document = Jsoup.connect(url).get();
error in this line of my project.i use above line three time as my requirement but all the three time where this above line is use and all three line shows error message.
Help how to remove this error ..
if anyone knows any other easy method/way to get(fetch) data from dynamic website data to android app kindly also mention that way..
public class Jsoup extends Activity{
// URL Address
String url = "http://www.vogella.com/tutorials/Android/article.html";
ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Locate the Buttons in activity_main.xml
Button titlebutton = (Button) findViewById(R.id.titlebutton);
Button descbutton = (Button) findViewById(R.id.descbutton);
Button logobutton = (Button) findViewById(R.id.logobutton);
// Capture button click
titlebutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Execute Title AsyncTask
new Title().execute();
}
});
// Capture button click
descbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Execute Description AsyncTask
new Description().execute();
}
});
// Capture button click
logobutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Execute Logo AsyncTask
new Logo().execute();
}
});
}
// Title AsyncTask
private class Title extends AsyncTask<Void, Void, Void> {
String title;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Jsoup.this);
mProgressDialog.setTitle("Android Basic JSoup Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
// Connect to the web site
Document document = Jsoup.connect(url).get();
// Get the html document title
title = document.title();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set title into TextView
TextView txttitle = (TextView) findViewById(R.id.titletxt);
txttitle.setText(title);
mProgressDialog.dismiss();
}
}
// Description AsyncTask
private class Description extends AsyncTask<Void, Void, Void> {
String desc;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Jsoup.this);
mProgressDialog.setTitle("Android Basic JSoup Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
// Connect to the web site
Document document = Jsoup.connect(url).get();
// Using Elements to get the Meta data
Elements description = document
.select("meta[name=description]");
// Locate the content attribute
desc = description.attr("content");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set description into TextView
TextView txtdesc = (TextView) findViewById(R.id.desctxt);
txtdesc.setText(desc);
mProgressDialog.dismiss();
}
}
// Logo AsyncTask
private class Logo extends AsyncTask<Void, Void, Void> {
Bitmap bitmap;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Jsoup.this);
mProgressDialog.setTitle("Android Basic JSoup Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
// Connect to the web site
Document document = Jsoup.connect(url).get();
// Using Elements to get the class data
Elements img = document.select("a[class=brand brand-image] img[src]");
// Locate the src attribute
String imgSrc = img.attr("src");
// Download image from URL
InputStream input = new java.net.URL(imgSrc).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set downloaded image into ImageView
ImageView logoimg = (ImageView) findViewById(R.id.logo);
logoimg.setImageBitmap(bitmap);
mProgressDialog.dismiss();
}
}
}
You shouldn't name your class same way as already existing classes because compiler will connect each call of simplified name to current class, not to the class from imports. For instance
class String {
public static void main(String[] args) {
System.out.println(String.valueOf("1"));
}
}
will not compile because String.valueOf will not try to invoke valueOf from java.lang.String but from your class, and since there is no such method there you are seeing error saying that such method is undefined.
So change name of your class
public class Jsoup extends Activity{
...{
Document document = Jsoup.connect(url).get();
}
}
to something more like
public class JsoupActivity extends Activity{
// ^^^^^^^^^^^^^
...{
Document document = Jsoup.connect(url).get();
}
}

Progress Bar during the loading of a ListView

So, I want to display a spinning loading indicator while my ListView is being populated. I successfully have implemented the progress bar, BUT for some reason it disappears BEFORE all of the listings are displayed. What I want is the progressbar to be present during the TOTAL load time of the listings. Basically, what it seems like, each listing is being displayed one at a time, not all at once when they are all loaded.
What I'm doing is
1. Creating a new custom adapter class
2. Populating the ListView in an AsyncTask using this adapter class
3. Setting the ListView to this adapter
This works properly, the progress bar just disappears before all of the listings are displayed. Does anyone have any ideas?
Activity class:
public class MainActivity extends ActionBarActivity {
ArrayList<Location> arrayOfLocations;
LocationAdapter adapter;
// public static Bitmap bitmap;
Button refresh;
ProgressBar progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress=(ProgressBar)findViewById(R.id.progressbar_loading);
// Construct the data source
arrayOfLocations = new ArrayList<Location>();
// Create the adapter to convert the array to views
adapter = new LocationAdapter(this, arrayOfLocations);
FillLocations myFill = new FillLocations();
myFill.execute();
refresh = (Button) findViewById(R.id.refresh);
refresh.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
startActivity(getIntent());
}
});
}
private class FillLocations extends AsyncTask<Integer, Void, String> {
String msg = "Done";
protected void onPreExecute() {
progress.setVisibility(View.VISIBLE);
}
// Decode image in background.
#Override
protected String doInBackground(Integer... params) {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://afs.spotcontent.com/"); // YOUR
// PHP
// SCRIPT
// ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
// resultView.setText("connected");
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
try {
BitmapWorkerTask myTask = new BitmapWorkerTask(
json.getInt("ID"), json);
myTask.execute();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data " + e.toString());
}
return msg;
}
protected void onPostExecute(String msg) {
// Attach the adapter to a ListView
ListView listView = (ListView) findViewById(R.id.listView1);
// View header = (View) getLayoutInflater().inflate(
// R.layout.listview_header, null);
// listView.addHeaderView(header);
listView.setAdapter(adapter);
progress.setVisibility(View.GONE);
}
}
}
Adapter class:
public class LocationAdapter extends ArrayAdapter<Location> {
public LocationAdapter(Context context, ArrayList<Location> locations) {
super(context, R.layout.item_location, locations);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Location location = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_location, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvDetails = (TextView) convertView.findViewById(R.id.tvDetails);
TextView tvDistance = (TextView) convertView.findViewById(R.id.tvDistance);
TextView tvHours = (TextView) convertView.findViewById(R.id.tvHours);
ImageView ivIcon = (ImageView) convertView.findViewById(R.id.imgIcon);
// Populate the data into the template view using the data object
tvName.setText(location.name);
tvDetails.setText(location.details);
tvDistance.setText(location.distance);
tvHours.setText(location.hours);
ivIcon.setImageBitmap(location.icon);
// Return the completed view to render on screen
return convertView;
}
}
The reason for that behavior is that you are starting multiple threads.
FillLocations preExecute --> SHOW ProgressBar
BitmapWorkerTask_1 --> new thread
BitmapWorkerTask_2 --> new thread
...
BitmapWorkerTask_N --> new thread
FillLocations postExecute --> HIDE ProgressBar
BitmapWorkerTask_K --> continue execution
BitmapWorkerTask_K+1 --> continue execution
etc.
If you want the list to be displayed until it's all loaded, Simply make BitmapWorker's processing synchronous. If you still want to display the list right away but keep the spinner until it's all finished, then keep a counter in your activity and increase it in preexecute and decrease it in postExecute of BitmapWorker via a setter. Once the counter hits 0, remove hide the progressBar.
In activity:
private int asynchCounter = 0;
private void updateCounter(int delta){
asynchCounter+=delta;
if(asynchCounter<=0){
progress.setVisibility(View.GONE);
}else{
progress.setVisibility(View.VISIBLE);
}
}
And instead of BitmapWorkerTask use
class CountedBitmapWorkerTask extends BitmapWorkerTask {
protected void onPreExecute() {
super.onPreExecute();
updateCounter(1);
}
protected void onPostExecute(String msg) {
super.onPostExecute();
updateCounter(-1);
}
}
I had this exact problem, to solve it I had to write AsyncTask complete listener. Which sends a notification to UI thread, that data was loaded and it has to change something, in this case hide the ProgressBar.
This is the basic example of how this should look like. I am not sure this will work for you after you copy it to your project, but complete listener is what you need, so after studying this case you should be able to find a solution.
AsyncTaskCompleteListener.java - listener interface.
public interface AsyncTaskCompleteListener {
public void onTaskComplete();
}
LoadDataTask.java
class LoadDataTask extends AsyncTask<Object, Object, Object> {
/* Your object types according to your task. */
private AsyncTaskCompleteListener callback; // Callback field
public LoadDataTask(AsyncTaskCompleteListener cb){
this.callback = cb;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Object doInBackground(String... urls) {
/* Your task here */
return result;
}
#Override
protected void onPostExecute(Object o) {
callback.onTaskComplete(); // Set the Callback
}
}
MainActivity.java
public class MainActivity implements AsyncTaskCompleteListener{
/* ...Other methods and fields... */
/* onTaskComplete method which fires after your data is loaded. */
#Override
public void onTaskComplete(){
// Hide ProgressBar
}
}
Self Plug: https://github.com/horvste/EasyWebPageDownloadForAndroid
This would separate the threading from the implementation and solve your problem. This is very similar to what Tony suggested except it's already implemented for you.
Github Readme:
Good for connecting to REST API's, HTML parsing, and many other uses. Using this library is meant to be easy:
Create a class which implements OnProgressUpdate
public class SampleClass implements OnProgressUpdate {
#Override
public void onUpdate(Integer percentProgress) {
}
#Override
public void onUpdateFailure() {
}
#Override
public void onSuccess(StringBuilder result) {
}
#Override
public void onFailure() {
}
}
}
Instantiate DownloadWebPage object
DownloadWebPage webPage = new DownloadWebPage(new SampleClass(), myUrl);
Call .downloadHtml() from the DownloadWebPage
webPage.downloadHtml();
Also if the asynchtask is updating properly and the amount of items is to large look here:
listing a listview is taking too much time and memory in android
Another option would be to only list a certain amount of items then have a next page button or gesture to deal with the ListView loading too slow.

Categories