I am doing lazy loading and almost done with it. But would like to implement a progress dialog with it because it takes about 10seconds between starting the activity and finishing displaying the contents. Once I click on a button to start, it stays at the current page(Main.java) for about 4 second before moving to the next page(Activity.java). Then it takes about 2-4 seconds to display contents.
Tried the examples available here and on the net but they aren’t working well (able to display the dialog but unable to do a proper dismiss after content are all downloaded).
Question is, how can I implement a progress indicator immediately once the user clicks on the button?
Activity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, mStrings, dStrings );
list.setAdapter(adapter);
}
private String[] mStrings = {};
private String[] dStrings = {};
public Activity()
{
String imageC = "";
String textC = "";
try {
// Get the URL from text box and make the URL object
URL url = new URL(targetURL);
// Make the connection
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = reader.readLine();
Pattern sChar = Pattern.compile("&.*?;");
Matcher msChar = sChar.matcher(line);
while (msChar.find()) line = msChar.replaceAll("");
while (line != null) {
if(line.contains("../../"))
{
int startIndex = line.indexOf("../../") + 6;
int endIndex = line.indexOf(">", startIndex + 1);
String abc = "http://www.petschannel.com/";
String imageSrc = line.substring(startIndex,endIndex);
//complete full url
String xyz = abc +imageSrc;
xyz = xyz.substring(0,xyz.indexOf('"'));
xyz = xyz +";";
imageC += xyz;
mStrings = imageC.split(";");
line = reader.readLine();
}
if(line.contains("../../") == false)
{
line = reader.readLine();
}
if (line.contains("Gnametag"))
{
int startIndex = line.indexOf("Gnametag") + 10;
int endIndex = line.indexOf("<", startIndex + 1);
String gname = line.substring(startIndex,endIndex);
textC += "Name: "+gname+ "\n";
}
if (line.contains("Last Update"))
{
reader.close();
}
}
// Close the reader
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Firstly, you are doing your network call on the main thread, this is a classic no-no for performance reasons, amongst others. Never do any operation that may be time consuming on the main (ui) thread.
I would suggest using AsyncTask, which ensures in this case, that your network call would be done in a worker thread, and the result posted back to the main thread.
AsyncTask has methods to manage progress bars,
onProgressUpdateandpublishProgressthat will help you solve your stated problem. There are many good articles about this, here is one.