0

I tried to show string type from sharedpref and success, but if I try to show data integer type from sharedpref cannot showing. I show my code in below.

This is some code in LoginAct.java

try {
     JSONObject jsonObject = new JSONObject(response.body().string());

     if (jsonObject.getString("status").equals("true")) {

         Toast.makeText(context, "Login Success", Toast.LENGTH_SHORT).show();

         Integer no_id = jsonObject.getJSONObject("data").getInt("no_id");

         prefManager.saveSPInt(SharedPrefManager.SP_NO_ID, no_id);

         prefManager.saveSPBoolean(SharedPrefManager.SP_LOGGED, true);

         startActivity(new Intent(context, MainAct.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
         finish();}
}

This is my SharedPref.java

public class SharedPrefManager {
    public static final String SP_APPS_APP = "spAppsApp";

    public static final String SP_NO_ID = "spNoID";

    public static final String SP_LOGGED = "spLogged";

    SharedPreferences sp;
    SharedPreferences.Editor spEditor;

    public SharedPrefManager(Context context){
        sp = context.getSharedPreferences(SP_APPS_APP, Context.MODE_PRIVATE);
        spEditor = sp.edit();
    }

    public void saveSPInt(String keySP, Integer value){
        spEditor.putInt(keySP, value);
        spEditor.commit();
    }

    public Integer getSpNoId() {
    return sp.getInt(SP_NO_ID, -1);
    }
}

This is some code from MainAct.java to showing NO_ID

    SharedPrefManager prefManager;
        @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                prefManager = new SharedPrefManager(this);

                tNoID = findViewById(R.id.txtNoID);
                tNoID.setText(prefManager.getSpNoID());
}

I still working it and still confused to fix it, I wish you helped me for my case it. Thank you guys for your help.

  • I assume you mean it's crashing. If so, the issue is that you cannot call `setText()` with an arbitrary integer value. You need to convert it to a `String` first; e.g., `tNoID.setText(String.valueOf(prefManager.getSpNoID()))`. – Mike M. Dec 16 '19 at 03:37
  • I add that you example and got error like this java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer – Mas'ud Al Hafiz Dec 16 '19 at 04:15
  • That's nothing to do with the example I gave. That can happen, though, if you've previously saved a preference as a `String`, and are now trying to retrieve it as an `int`. If you're still just testing, you can clear the `SharedPreferences` completely and start over, by selecting the "Clear data" option on your app's Storage page in the device Settings. If that's not it, I'd need to see the complete stack trace to be able to determine what the issue is. – Mike M. Dec 16 '19 at 04:20

0 Answers0