Bart Simons


A 2 post collection

Android - Save and load data using SharedPreferences

 •  Filed under java, android, sharedpreferences, save data, load data

Want to store data inside your Android app? No problem! The Android SDK and Java has got you covered. One of the many options to save and load data is to use SharedPreferences. It's also good to know that it is one of the easiest (and in my opinion most integrated) methods to implement! Please mind that SharedPreferences are probably not suitable for intensive, repetitive and/or low-latency I/O usage (SQL storage might be better for those tasks).

How do I use it?

Simple! I have made two working code samples for you.

Saving stuff
SharedPreferences sharedPref = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);  
SharedPreferences.Editor editor = sharedPref.edit();

editor.putString("username", "randomusername4238");  
editor.putString("passwordhash", "somerandompasswordhash");

Loading stuff
SharedPreferences sharedPref = getSharedPreferences("preferences", Context.MODE_PRIVATE);

String saved_username = sharedPref.getString("username", "");  
String saved_passwordhash = sharedPref.getString("passwordhash", "");  

That should get the job done! As you can see, this method of saving data is great for saving and loading important data for your app. Enjoy!

Android - Call UI-code from a class

 •  Filed under android, ui code, class, tutorial, example

Java and the Android SDK go perfectly well together, but just like any other 'good' programming language you sometimes have to get over some rough edges. As an example, it took me almost a day to figure out how to interact with the UI thread from a class! So, I'm sharing with you this handy little Java snippet that just works. Enjoy it and stay productive!


package me.bartsimons.helloworld

import android.os.Bundle;  
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {  
    TextView helloText;

    protected void onCreate(Bundle savedBundleInstance) {

        helloText = (TextView) findViewById(;

        SubModule moduleSub = new SubModule(this);

package me.bartsimons.helloworld

public class SubModule {  
    protected MainActivity context;

    public SubModule(MainActivity _context) {
        context = _context;

    public void testFunction() {
        context.runOnUiThread(new Runnable() {
            context.helloText.setText("Hello world!");