Reputation: 8383
In an Android app that I am developing I have a Fragment that starts a Thread that gets an image from a specific URL and after that shows that image on a ImageView in the Fragment. The problem that I have is that my app does not wait for the thread to finish as I was expecting.
In AdvertisementFragment.java :
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Obtain the advertisement controller.
controller = new AdvertisementController();
// Shows a spinner while fetching the advertisement image.
progressDialog = ProgressDialog.show(getActivity(), "", getString(R.string.fetchingAdvImage));
controller.showAvertisementImage2();
// Destroy the spinner
progressDialog.dismiss();
return inflater.inflate(R.layout.fragment_advertisement, container, false);
}
The controller has this method:
public void showAvertisementImage2() {
GetAdvertisementImageThread advertisementImageThread = new GetAdvertisementImageThread("Advertisement image thread", advertisementData);
try {
advertisementImageThread.t.join();
Log.v("Thread", "Se pone en espera.");
} catch (InterruptedException e) {
Log.v("Thread", "Se llanza la exception.");
e.printStackTrace();
}
}
And in the GetAdvertisementImageThread class:
GetAdvertisementImageThread(String threadname, AdvertisementData advertisementDataPassed) { name = threadname; advertisementData = advertisementDataPassed;
advertisementData = new AdvertisementData();
t = new Thread(this, name);
Log.v("Thread", "New thread: " + t);
t.start();
}
public void run() {
try {
// Connect to the url.
in = openHttpConnection(url);
// If the connection was no successful finish the execution.
if (in == null) return;
// Read the InputStream character by character and add it to the pageSourceCode String variable.
InputStreamReader isr = new InputStreamReader(in);
int charRead;
pageSourceCode = "";
char[] inputBuffer = new char[BUFFER_SIZE];
.....
}
}
I was expecting for the Fragment to wait for the Thread to finish but it does not and instead it destroys the
ProgressDialog before the image is fetched and get the image afterwards.
I thought that the .join will make it wait for the Thread to finish but it seems it does not.
What am I doing wrong?
Upvotes: 0
Views: 452
Reputation: 33
Waiting for the thread to finish a URL data fetching will be so lagy especially with low speed internet connection. I suggest instead of waiting it to finish, let it take its time and display a message of fetching data; to keep it user friendly.
Upvotes: 1