Here’s my class:
public class JsoupParser
{
ArrayList<CompanyInfo> arr = new ArrayList<CompanyInfo>();
public static final String SITE = "http://www.example.com/";
public JsoupParser() {}
public ArrayList<CompanyInfo> parse(final String link)
throws InterruptedException, ExecutionException
{
new RealParser().execute(link).get();
return arr;
}
class RealParser extends AsyncTask<String, Void, Void>
{
@Override
protected Void doInBackground(String... params)
{
Document doc = null;
String link = params[0];
try
{
doc = Jsoup.connect(link).get();
}
catch (IOException e)
{
e.printStackTrace();
}
Elements a = doc.select("a.company_logo");
Elements img = a.select("img");
Iterator aIter = a.iterator();
int i = 0;
CompanyInfo info = new CompanyInfo();
while(aIter.hasNext())
{
aIter.next();
info.setCompanyName(a.get(i).attr("title"));
info.setCompanyListingLink(SITE+ a.get(i).attr("href"));
info.setCompanyLogoLink(SITE+ img.get(i).attr("src"));
arr.add(info);
++i;
}
return null;
}
}
}
I’m sure, that the parsing code works fine (tested in Java project).
The problem is, that all the elements of arr at the end become the same (all suddenly become equal to the first element inserted to arr). I debug and see, that each element differs from another.
Each time the info object is different, that means, that I add different elements to arr doing this arr.add(info);. Debugging in while loop everything is OK, but as soon as it quits the AsyncTask, the arr becomes an ArrayList with multiple of same objects.
How can I solve this? What am I doing wrong?
Yes because you keep re-using the same
CompanyInfoobject.You need to move
CompanyInfo info = new CompanyInfo();within thewhileloop.