0

I am trying to retrieve some image URLs and image texts by scraping a website when my app starts up. I then want to use arrays I've created of imageTexts and imageURLs to create a ViewPager so I can display the images as a scrollable gallery.

I execute the network task of fetching the webpage and parsing the HTML as an AsyncTask (downloadTask() in the code below).

My problem is that as this happens in the background it doesn't have time to fetch and parse the data before the code tries to display the images. I get a null pointer error when the code hits

new ViewPagerAdapter(this, getimageText(), getimageURLS())

I can deduce that the array that should eventually store the image URLs and the image Texts hasn't been created yet. This is at the point my app crashes.

Here's my code. I'm new to both Android and Java so clearly I could do with a lot of help!

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from viewpager_main.xml
        setContentView(R.layout.viewpager_main);

        // Fetch the list of URLs using a background network task
        new downloadTask().execute(BASE_URL);

        // Locate the ViewPager in viewpager_main.xml
        viewPager = (ViewPager) findViewById(R.id.pager);

        // Pass results to ViewPagerAdapter Class
        adapter = new ViewPagerAdapter(this, getimageText(), getimageURLS());

        // Binds the Adapter to the ViewPager
        viewPager.setAdapter(adapter);

    }
4

1 回答 1

2

您最初可以设置默认图像,并且可以修改 asyncTask 以采用回调方法。此回调方法将是初始化您的 ViewPager 的方法。在您的 AsyncTask 中,您将获取图像并覆盖 onPostExecute() 方法以调用该回调方法。

例子

class PictureGrabber extends AsyncTask<URL, VOID, VOID>{
IPicCallBack callBack;
PictureGrabber(IPicCallBack callback)
{
    this.callback = callback;
}

protected Void doInBackGround(URL... urls){
}

protected void onPostExecute(VOID result)
{
    callback.Init();
}

public interface IPicCallBack{
    public void Init();
}

然后在您的代码中,您需要实现该 IPicCallback 并将其设置在 asyncTask 上,当任务完成时,它将调用该方法

于 2013-07-14T22:10:31.420 回答