getString из нескольких файлов SharedPreferences и создать listView - PullRequest
1 голос
/ 16 февраля 2012

Сначала - извините за мой английский;) Я пишу менеджер профилей для Android и хочу получить getString из файла SharedPreferences и создать listView.Это часть моего кода:

private static final String PN = "profile_name";
private EditTextPreference editText;
private SharedPreferences preferences;

public class Profile_Preferences extends PreferenceActivity {

...

private void SavePreferences() {

    String text= editText.getText().toString();
    preferences = getSharedPreferences("Profile_" + text, Activity.MODE_PRIVATE);  //Here we created SharedPreferences file with name "Profile_"+ this what user write in editText

    SharedPreferences.Editor preferencesEditor = preferences.edit();
    preferencesEditor.putString(PN, editText.getText());
    preferencesEditor.commit();

Хорошо.Пользователь делал несколько профилей, поэтому у нас есть файл, например: Profile_home.xml, Profile_work.xml, Profile_something.xml.Теперь я не хочу создавать listView с именем профиля из этого файла.Это мое следующее задание:

public class Tab_profiles extends ListActivity {

ArrayList<String> listItems = new ArrayList<String>();  
ArrayAdapter<String> adapter; 

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);

    adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, listItems);
    setListAdapter(adapter);
 ...

public void LoadList() {        

 //It's a good idea to getString "profile_name" form every xml file with name "Profile_" + "" ? 
    preferences = getSharedPreferences("Profile_"+ "", Activity.MODE_PRIVATE);

    String take_profile_name = preferences.getString("profile_name", null);
    listItems.add(take_profile_name );
    adapter.notifyDataSetChanged();

}

Но это не работает ... logcat log:

FATAL EXCEPTION: MAIN 
java.land.Null.PointerException
at android.widget.ArrayAdaper.createViewFromResource(ArrayAdapter.java:355)
...

Теперь я не знаю, что это не так ...

Пожалуйста, помогите мне :) Спасибо за любые ответы и извините за мои ошибки в написании и коде;)

1 Ответ

2 голосов
/ 16 февраля 2012

В вашем коде есть несколько проблем:

String text = editText.getText().toString();
preferences = getSharedPreferences("Profile_" + text, Activity.MODE_PRIVATE);

SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.putString(PN, editText.getText());

Если пользователь вводит «home» в EditText, вы создаете файл настроек с именем «Profile_home» и сохраняете его имя в том же файле?Вам нужно сохранить сгенерированные пользователем имена файлов в другом файле, имя которого вы знаете, чтобы вы могли получить к нему доступ в своем коде.

Вторая проблема:

preferences = getSharedPreferences("Profile_" + "", Activity.MODE_PRIVATE);
String take_profile_name = preferences.getString("profile_name", null);

Выпытаюсь открыть настройки "Profile_".Этот файл не существует(?).Второй параметр getString не должен быть нулевым, иначе вы добавите нулевую ссылку в ваш список строк, что приведет к ошибке.Замените его пустой строкой "".

Редактировать: Вот небольшой обходной путь, чтобы получить все пользовательские именованные предпочтения:

private void SavePreferences() {
    String text = editText.getText().toString();
    preferences = getSharedPreferences("ProfileNames", Activity.MODE_PRIVATE);
    SharedPreferences.Editor preferencesEditor = preferences.edit();
    // increment index by 1
    preferencesEditor.putInt("profile_count", preferences.getInt("profile_count", 0) + 1);
    // save new name in ProfileNames.xml with key "name[index]"
    preferencesEditor.putString("name" + (preferences.getInt("profile_count", 0) + 1), editText.getText());
    preferencesEditor.commit();
}

public void LoadList() {        
    preferences = getSharedPreferences("ProfileNames", Activity.MODE_PRIVATE);
    List<String> profileNames = new LinkedList<String>();
    int profileCount = preferences.getInt("profile_count", 0);
    for (int i = 1; i <= profileCount; i++) {
        profileNames.add(preferences.getString(name + i, ""));
    }
    listItems.addAll(profileNames);
    adapter.notifyDataSetChanged();
}
...