Home Ask Login Register

Developers Planet

Your answer is one click away!

Wyhx February 2016

What exactly is causing this NullPointerException?

I'm pretty new to Android development and am currently working on an app which is supposed to save the current time and date when a button is pressed, store it to SharedPreferences and then present the String when a different button is pressed. I got it working but did some tinkering today and now I'm getting a NullPointerException that I can't solve, even after having spent about 45 minutes on Google and Stackoverflow trying different code fragments. Can anyone who is better at this than me tell me what I'm missing?

Here is the relevant code:

public class GetTimeStamp extends AppCompatActivity {

    private String date;
    public void setDate (View view){
        DateFormat df = new SimpleDateFormat("dd.MM.yyy 'om' HH:mm");
        date = df.format(Calendar.getInstance().getTime());
    public String getDate(){
        return date;
        SharedPreferences prefs = this.getSharedPreferences("SharedPrefs",       Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    protected void onCreate(Bundle savedInstanceState) {

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabSaveTimeStamp);
        fab.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                editor.putString("storedDate", date);
                Toast.makeText(getBaseContext(), "blablabla", Toast.LENGTH_SHORT).show();
FloatingActionButton fab3 = (FloatingActionButton) findViewById(R.id.fabShowTimeStamp);
        fab3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {


George Mulligan February 2016

You are trying to initialize the following class field before you are allowed to:

SharedPreferences prefs = this.getSharedPreferences("SharedPrefs",       Context.MODE_PRIVATE);

Only declare the field:

SharedPreferences prefs;

and then assign it in your onCreate() method:

protected void onCreate(Bundle savedInstanceState) {
    prefs = getSharedPreferences("SharedPrefs", Context.MODE_PRIVATE);

Post Status

Asked in February 2016
Viewed 1,439 times
Voted 10
Answered 1 times


Leave an answer

Quote of the day: live life