Bart Simons

android

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");

editor.apply();  
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!

// MainActivity.java

package me.bartsimons.helloworld

import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {  
    TextView helloText;

    @Override
    protected void onCreate(Bundle savedBundleInstance) {
        super.onCreate(savedbundleInstance);
        setContentView(R.layout.activity_main);

        helloText = (TextView) findViewById(R.id.textHelloWorld);

        SubModule moduleSub = new SubModule(this);
        moduleSub.testFunction();
    }
}
// SubModule.java

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!");
        });
    }
}