2011-06-07 94 views
3

我想解析一个片段内的线程中的XML文件。获取资产范围内

我的代码部分片段是:

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个项目。

有什么建议吗?

回答

14

正在访问片段中正确的资产吗?

使用ActivitygetActivity()),而不是ApplicationgetApplicationContext()),看看有没有什么帮助。除非你知道他们在说什么,否则不要在你的应用中使用getApplicationContext()

+0

它帮助我找到问题的根源。谢谢 – 2011-06-08 04:08:43

+0

它不适合我,但为什么不使用'getApplicationContext()'? – Si8 2013-12-03 16:49:04

+0

@ SiKni8:见http://www.doubleencore.com/2013/06/context/ – CommonsWare 2013-12-03 17:11:48