1

我有一个活动,它在不操作共享偏好的情况下工作。添加后,点击按钮后出现空指针错误。

我认为我使用共享偏好的方式不正确。任何人都可以帮助指出是什么问题?在使用之前我应该​​ new() 吗?

public class BanknameActivity extends Activity {

String [] bank_name;
String selected_bank_config; 
SharedPreferences prefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bankname);
    // Show the Up button in the action bar.
    // setupActionBar();

    bank_name = getResources().getStringArray(R.array.bankname);

    ListView lv1 = (ListView) findViewById(R.id.bankname_listview);
    lv1.setChoiceMode(1); // CHOICE_MODE_SINGLE

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, bank_name);
    lv1.setAdapter(adapter);
    lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
                public void onItemClick(AdapterView<?> adapter, View view, int position, long arg)   {
                      //selected_bank_config = "Citi";
                      prefs.edit().putString(selected_bank_config, "citi").commit();                  
                      return_to_config(view);                                                  
                }
    });

}

以下是我的部分代码:

    public void return_to_config(View view){
       Intent intent = new Intent(this, ConfigActivity.class);
       startActivity(intent);
       this.finish();
}
4

1 回答 1

1
**you need to initialize your shared Preferences. Without initialization it will always be null.**

yo need to do following stuff:

//  mPrefs=getSharedPreferences("Preferences Name",mode);

 mPrefs=getSharedPreferences("FBPref",0);
              Editor edit=mPrefs.edit();
              edit.putString("UserName", "");
              edit.putString("UserId","");
              edit.putString("EmailId","");
              edit.commit();

这段代码工作正常。我希望你会欣赏它。

于 2013-08-04T16:31:05.280 回答