Android:使用共享首选项中的项目填充listview时出现问题

时间:2011-01-02 18:06:34

标签: android listview layout menu sharedpreferences

我有一个简单的应用程序,可以查看漫画,并允许用户将某些标记为“收藏夹”,以后可以访问它(它不仅仅是这样,但这就是所有相关的)。当用户将漫画标记为收藏夹时,将字符串放置到共享首选项,格式为key =“#of Comic”Value =“title of Comic”。 SharedPreferences只包含与“收藏夹”漫画相关联的键/值对。此功能正常。问题出现在我实现的菜单按钮上,我打算显示一个ListView,其中包含存储在SharedPreferences文件中的所有收藏夹的值。以下是用户单击弹出菜单中的“收藏夹”按钮时执行的操作的代码

case R.id.favorites:
        Log.i("Step 1", "Favorites");
        favVector.clear(); //Clears string Vector that I want to use to hold the titles

        Map<String, ?> allprefs = xkfav.getAll(); //gets map of all Shared Preferences
        for (Map.Entry<String, ?> entry : allprefs.entrySet()) {
            favVector.add((String) entry.getValue());
        }
        Log.i("Step 2", "Favorites");
        setContentView(R.layout.favlist); //loads Layout with ListView (and nothing else)
        Log.i("Step 3", "Favorites");
        ListView menuList;
        menuList = (ListView) findViewById(R.id.FavListView);
        String[] items = new String[favVector.size()]; //creates array with size of Vector
        favVector.copyInto(items); //Copies Vector into array
        ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, R.layout.fav_item, items);
        menuList.setAdapter(adapt); //Puts array contents into list

每次我跑这个,我都会收到一个强制关闭。我甚至从未在日志中看到“第2步”。忽略这可能不是美观或高效的代码这一事实,为什么当用户点击此按钮时我会收到强制关闭错误?

1 个答案:

答案 0 :(得分:2)

强制关闭通常是应用程序中某处运行时异常的结果。

此异常应在日志中可见。如果您正在使用Eclipse / ADT,请转到DDMS透视图并查看logcat视图。 (我假设您可以轻松地重现错误)。

你应该看到一个堆栈跟踪。调查堆栈跟踪并尝试找出它出错的地方。这可以是从NullPointerException到另一个RuntimeException的任何内容。

另外,尝试在“Step 1”断点处设置断点。以调试模式启动应用程序并逐步执行代码。在堆栈中的某个点上,您将看到应用程序在强制关闭时退出的确切时间和原因。

如果您从未使用过Eclipse的调试功能,请参阅以下链接: http://www.vogella.de/articles/EclipseDebugging/article.html

相关问题