Android: Problem populating listview with items from Shared Preferences
I have a simple application that v开发者_StackOverflow中文版iews comics and allows the user to mark some as "Favorites" which can be accessed later (it does more than that, but that's all that's relevant here). When the user marks a comic as Favorite, a String is put to shared preferences with the format key = "# of Comic" Value = "title of Comic". The SharedPreferences contains nothing but Key/Value pairs associated with Favorite comics. This functionality works fine. The problem arises with a menu button I implemented that I intended to show a ListView containing the Values of all of the Favorites stored in the SharedPreferences file. Here is the code for the actions performed when the user clicks on the Favorites button in the popup menu
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
Every time I run this, I get a Force Close. I never even see "Step 2" appear in the log. Ignoring the fact that this probably is not beautiful or efficient code, why do I get the Force Close error when the user clicks this button?
A force close is usually the result of a runtime exception somewhere in your app.
This exception should be visible in the logs. If you're using Eclipse/ADT, go to the DDMS perspective and look in the logcat view. (I assume you can reproduce the error easily).
You should see a stacktrace. Investigate the stacktrace and try to find where it went wrong. This could be anything from a NullPointerException to another RuntimeException.
Also, try putting a breakpoint at your "Step 1" breakpoint. Start your app in debug mode and step through the code. At some point in the stack, you'll see exactly when and why the application exits with a force close.
If you've never used the debugging features of Eclipse, see the following link : http://www.vogella.de/articles/EclipseDebugging/article.html
精彩评论