I currently have a Pollen class which is a class I wrote which uses the JSoup library to parse HTML. Also shown here is my PlaceholderFragment
class.
public static class PlaceholderFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
final Button button = (Button) rootView.findViewById(R.id.button1);
final TextView textview = (TextView) rootView.findViewById(R.id.textview1);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Pollen pollenObject = new Pollen(19104);
textview.setText(pollenObject.getCity());
}
});
return rootView;
}
}
Here is my Pollen class.
public static class Pollen
{
@SuppressLint("SimpleDateFormat")
public Pollen(int zipcode)
{
this.zipcode = zipcode;
Document doc;
try
{
// pass address to
doc = Jsoup.connect("http://www.wunderground.com/DisplayPollen.asp?Zipcode=" + this.zipcode).get();
// get "location" from XML
Element location = doc.select("div.columns").first();
this.location = location.text();
// get "pollen type" from XML
Element pollenType = doc.select("div.panel h3").first();
this.pollenType = pollenType.text();
SimpleDateFormat format = new SimpleDateFormat("EEE MMMM dd, yyyy");
// add the four items of pollen and dates
// to its respective list
for(int i = 0; i < 4; i++)
{
Element dates = doc.select("td.text-center.even-four").get(i);
Element levels = doc.select("td.levels").get(i);
try
{
pollenMap.put(format.parse(dates.text()), levels.text());
}
catch (ParseException e)
{
e.printStackTrace();
}
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I learned a lot while failing every attempt. I discovered that, in my use of calling my Pollen
class within onClick
, I am doing an expensive task. Thus, I should put it in a separate thread. To add, since I am calling my Pollen
class within my main/UI thread, it causes my app to crash.
I consulted this Stackoverflow question in aiding my attempt to solve my issue: How to fix android.os.NetworkOnMainThreadException?
I discovered my error and solution via this error log from logcat, specifically, NetworkOnMainThread
where Android explicitly prevents me from doing anything network on my UI thread.
My question is - how do I allocate my Pollen
class into a separate thread that is not in my UI class?
Continuing my tutorial on that Stackoverflow thread, I have added this class. I have no idea what I am doing.. But I will try my best to continue:
abstract class RetrievePollenTask extends AsyncTask<Integer, Void, Pollen>
{
protected Pollen doInBackground(String... params)
{
// TODO Auto-generated method stub
return null;
}
}