与getter和setter共享首选项

时间:2016-01-08 13:11:09

标签: android sharedpreferences

我正在使用SharedPreferences来处理会话。我的getter方法返回null,这是不应该的。

代码:

public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREFER_NAME = "MyPref";
public static final String KEY_CURRENT_ID = "current_id";
public final String KEY_HANDLING_ID = "handling_id";
public final String KEY_HAS_PROFILE = "profile_exists";


public SessionManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

public void setCurrentId(int id) {
    editor.putInt(KEY_CURRENT_ID, id);
    editor.commit();
}

public int getCurrentId() {
    return pref.getInt(KEY_CURRENT_ID, 0);
}

public int getHandlingId() {
    return pref.getInt(KEY_HANDLING_ID, 0);
}

public void setHandlingId(int id) {
    editor.putInt(KEY_HANDLING_ID, id);
    editor.commit();
}


public boolean getHasProfile() {
    return pref.getBoolean(KEY_HAS_PROFILE, false);
}

public void setHasProfile() {
    boolean f;
    if(AppController.getInstance().getProfile()!=null){
        f=true;
    }else {
        f=false;
    }
    editor.putBoolean(KEY_HAS_PROFILE, f);
    editor.commit();
}

public void GenerateAndSetId(int profile_id) {
    int id=0;
    if (AppController.getInstance().getProfile() != null) {
        for (int i = 0; i < AppController.getInstance().getProfile().size() && (AppController.getInstance().getProfile().get(i).getId() == profile_id); i++) {
            id=i;
            break;
        }
    }
    setHandlingId(id);
}

}

我在Activity中使用

 new SessionManager(getApplicationContext()).getHandlingId(); 

它返回NullPointerException。即使我设置

 new SessionManager(getApplicationContext()).setHandlingId(1);

然后getHandlingId()也会返回NullPointerException

但如果我在Activity类中定义SharedPreferences,则会显示存储的ID。

 SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);pref.edit().putInt("handling_id",1).commit();
        Log.d("Status new id " ,"  "+pref.getInt("handling_id",0));

是1。

我google了很多但无法解决这个问题。

logcat的:

E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.monitoryourweight.patriotic/com.monitoryourweight.patriotic.ManageProfileView}: java.lang.NullPointerException
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2247)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2297)
 at android.app.ActivityThread.access$700(ActivityThread.java:152)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
 at android.os.Handler.dispatchMessage(Handler.java:99)
 at android.os.Looper.loop(Looper.java:137)
 at android.app.ActivityThread.main(ActivityThread.java:5328)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:511)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
 at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
 at com.monitoryourweight.patriotic.ManageProfileView.setUpList(ManageProfileView.java:170)
 at com.monitoryourweight.patriotic.ManageProfileView.init(ManageProfileView.java:70)
 at com.monitoryourweight.patriotic.ManageProfileView.onCreate(ManageProfileView.java:65)
 at android.app.Activity.performCreate(Activity.java:5250)
 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2297) 
 at android.app.ActivityThread.access$700(ActivityThread.java:152) 
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282) 
 at android.os.Handler.dispatchMessage(Handler.java:99) 
 at android.os.Looper.loop(Looper.java:137) 
 at android.app.ActivityThread.main(ActivityThread.java:5328) 
 at java.lang.reflect.Method.invokeNative(Native Method) 
 at java.lang.reflect.Method.invoke(Method.java:511) 
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 
 at dalvik.system.NativeStart.main(Native Method) 

ManageProfileView.java

public class ManageProfileView extends FragmentActivity implements View.OnClickListener, DialogListener {


private SeparatedListAdapter adapter;
private List<Map<String, ?>> profile, weight, option;
private ListView profile_listview;
private Button back_btn, save_btn;
private TextView list_caption;
private Profile userProfile;
private boolean[] status;
private boolean statusName = true;
private int type;
private SessionManager session;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.manage_profile);
    init();
//other code
}

private void init() {
    setUpList(getIntent().getExtras().getInt("type"));
    session = new SessionManager(ManageProfileView.this);
    //other code
}

private void setUpList(int type) {
    profile_listview = (ListView) findViewById(R.id.profile_listview);
    adapter = new SeparatedListAdapter(this);

    this.type = type;

    if (type == 2 && statusName) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences("MonitorWeightPref", 0);
        pref.edit().putInt("handling_id", 1).commit();
        Log.d("Status new 2 ", "  " + pref.getInt("handling_id", 0));
        new SessionManager(getApplicationContext()).getHandlingId();
        session.setHandlingId(0);

        //ERROR IS HERE
        int x = session.getHandlingId();


        userProfile = AppController.getInstance().getProfile().get(x);

        final View footer = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_footer, null, false);
        footer.setOnClickListener(this);
        profile_listview.addFooterView(footer);
    } else {
        userProfile = new Profile();
    }

}

public static Map<String, ?> createItem(String paramString1, String paramString2) {
    HashMap localHashMap = new HashMap();
    localHashMap.put("title", paramString1);
    localHashMap.put("caption", paramString2);
    return localHashMap;
}

@Override
public void onClick(View v) {
//other code
}
}

1 个答案:

答案 0 :(得分:1)

<强>更新:

您执行方法// .aspx code <li><asp:LinkButton ID="LM_Show" runat="server" Text="Show list" OnClick="Action"/></li> <asp:PlaceHolder ID="infoTable" runat="server"></asp:PlaceHolder> //CreateTable function public void Clicked(object sender, EventArgs e){ table(); } public void table() { //Do stuff... //Screen variable is keeping track of which screen should be shown in .aspx infoTable.Controls.Add(CreateView.createTable<Employee>(screen, this.Context, table)); } //Create the actual table public static Table createTable<T>(Screen screen, HttpContext context, Action method) where T : new() { //New table and make it stretch Table tb = new Table(); tb.Width = Unit.Percentage(100); tb.Height = Unit.Percentage(100); //Gather list from session List<T> items = (List<T>)context.Session["list"]; //Create table content based on the list for (int i = 1; i <= items.Count(); i++) { TableRow tr = new TableRow(); //Foreach property create cells with content according to the property //Add these cells to the row tb.Rows.Add(tr); } //Create 1 final row which has a button to be able to add 1 row TableRow tr2 = new TableRow(); TableCell tc = new TableCell(); tr.Cells.Add(tc); //Create the Button Button button = new Button(); button.Text = "+"; //!!This is not getting triggered!!// button.Click += (s, e) => { List<T> tempItems = (List<T>)context.Session["list"]; tempItems.Add(new T()); context.Session["list"] = tempItems; //When a button is pressed, it gives a postback. //The table has to be rebuild over again with the newly added item method(); }; //!!This is not getting triggered!!// //Add the button tr2.Cells[0].Controls.Add(button); tb.Rows.Add(tr2); return tb; } ,该方法使用setUpList()变量,但仍未初始化。

开关:

session

setUpList(getIntent().getExtras().getInt("type"));
session = new SessionManager(ManageProfileView.this);

您只声明了session = new SessionManager(ManageProfileView.this); setUpList(getIntent().getExtras().getInt("type")); 变量,没有初始化,所以在线

session

您获得int x = session.getHandlingId(); 因为NullPointerException为空。

要修复它,请更改:

session

new SessionManager(getApplicationContext()).getHandlingId();