【问题标题】:Getting assets within fragements在片段中获取资产
【发布时间】:2011-06-07 07:36:21
【问题描述】:

我正在尝试在片段内的线程中解析 xml 文件。

我的代码的部分 sn-p 是:

public void onCreate(Bundle savedInstanceState)
    {
  mAdapter = new ListItemNearbyStoresAdapter(getActivity().getApplicationContext(), mStoresByKey);

         setListAdapter(mAdapter);

         // Load the list of stores from hard coded xml
         loadStoresByThread(getActivity().getApplicationContext());

    }

    private void loadStoresByThread(final Context ctx)
        {
            Thread t = new Thread()
            {

                public void run()
                {

                    try
                    {


                        Log.d(TAG, "In the thread");
                        String[] files = ctx.getResources().getStringArray(R.array.storefiles);
                       // String[] files={"s1.xml"};



                        for (int i = 0; i < files.length; i++)
                        {

                            try
                            {
                                InputStream stream = getActivity().getAssets().open(files[i]);

                                 NearbyItemDomFeedParser parser = new NearbyItemDomFeedParser(stream);
                                ArrayList<Store> stores = parser.parse();
                                Log.e("no of fioles read","asd :"+stores.size());
                                mStores.addAll(stores);
                                cache.setItems(mStores);
                            }
                            catch (Exception e)
                            {
                                Log.d(TAG, "Exception caught" + e);
                            }
                        }
}
}

注意整个类扩展了一个列表片段。

在片段中访问资产是否正确?

因为我无法读取文件。

没有引发异常,所以我无法找出确切的错误。

但最终在使用构建器解析后,我得到 0 个项目。

有什么建议吗?

【问题讨论】:

    标签: android xml android-fragments


    【解决方案1】:

    在片段中访问资产是否正确?

    使用Activity (getActivity()),而不是Application (getApplicationContext()),看看是否有帮助。除非您从知道他们在说什么的人那里得到非常具体的指示,否则切勿在您的应用中使用 getApplicationContext()

    【讨论】:

    • 它帮助我找到了问题的根源.. 谢谢
    • 它对我不起作用,但为什么从不使用getApplicationContext()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 2015-01-21
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多