javaandroidsystem-preferences

How to figure out why app is crashing when trying to access SystemPreferences data


I am trying to maintain a userID and username throughout my app. I created a class called Session that places and receives data to SharedPreferences and setting it works just fine. The problem I am getting is when I go to retrieve it in another activity.

The Session Class Constructor

 public Session(Context cntx) {
        // TODO Auto-generated constructor stub
        prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
    }

The Session Class method to add a userID and the method to retrieve it

 public void setUserID(int userID) {
        prefs.edit().putInt("userID", userID).apply();
    }

public int getID() {
        int userID;

        return userID = prefs.getInt("userID",0);

    }

Setting the ID on login

 StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        builder.setTitle("Server Response");
                        builder.setMessage("Response :"+response);

                        session = new Session(getApplicationContext());
                        int responseInt = Integer.parseInt(response.trim());
                        session.setUserID(responseInt);

                        Intent myIntent = new Intent(LoginActivity.this, navActivity.class);
                        startActivity(myIntent);
                        finish();

Trying to retrieve that ID and putting into an editText

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_jars);
        session = new Session(getApplicationContext());
        userID = (EditText) findViewById(R.id.userID);
        builder = new AlertDialog.Builder(MyJars.this);
        userID.setText(session.getID());

I wanted to be able to pull that data and send it to my server where I can run my PHP scripts as I have with other activities but this isn't cooperating.


Solution

  • In this line:

    userID.setText(session.getID());
    

    session.getID() is an integer and it is interpreted as an integer resource id and not as the string text that you want to set in userID.
    Change to this:

    userID.setText("" + session.getID());
    

    or

    userID.setText(String.valueOf(session.getID()));