Ryan Cocuzzo
Ryan Cocuzzo

Reputation: 3219

Using android SharedPreferences to save and reuse values on separate activities (Very basic app)

I made a quick tester app for my larger question of how to share variables between activities using SharedPreferences. As for having researched the subject, I have been using SharedPreferences for a little while now and have looked into this exact question but it went into a bunch of "dead ends" (where the code was not applicable and/or did not make sense for my situation). The app here is a very basic, 2-view application with only (on both pages) a button that adds 1 to the score and updates the TextView properly, a button that goes onto the second activity (which has the same options), and the actual TextView displaying the score. Any and all help is very much appreciated.

Also, there is no actual error. The problem at hand is that the score resets every time the activity changes.

MainActivity (Java):

package com.exampleryancocuzzo.ryan.testsharedpref;

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

SharedPreferences pref;
SharedPreferences.Editor editor;
int count;      // I referenced this as the score
TextView textView;

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

     pref = getApplicationContext().getSharedPreferences("MY_PREFS",MODE_PRIVATE);
    editor = pref.edit();
    count = pref.getInt("count", -1);
    if (count==-1){
        count = 0;
    }
    editor.commit();

    textView = (TextView) findViewById(R.id.count);
    textView.setText(count+"");
}

public void act2(View view){  // goes to Activity 2
    editor.putInt("count",count);

    Intent intent = new Intent(MainActivity.this,Main2Activity.class);
    startActivity(intent);
}

public void addC(View view){ // adds to the count variable
    count++;
    textView.setText(count+"");
}

}

Main2Activity (Java):

package com.exampleryancocuzzo.ryan.testsharedpref;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class Main2Activity extends AppCompatActivity {

SharedPreferences pref;
SharedPreferences.Editor editor;
int count;
TextView textView2;

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

    pref = getSharedPreferences("MY_PREFS",MODE_PRIVATE);
    editor = pref.edit();
    editor.commit();

    count = pref.getInt("count", -1);
    if (count==-1){
        count=0;
    }
    textView2 = (TextView) findViewById(R.id.count2);
    textView2.setText(count+"");
}

public void act1(View view){
    editor.putInt("count",count);
    Intent intent = new Intent(Main2Activity.this,MainActivity.class);
    startActivity(intent);
}

public void addC2(View view){
    count++;
    textView2.setText(count + "");
}
}

MainActivity (XML):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.exampleryancocuzzo.ryan.testsharedpref.MainActivity">

<TextView
    android:id="@+id/count"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:textSize="60sp"
    android:layout_centerHorizontal="true"/>
<Button
    android:id="@+id/add"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="ADD TO COUNT"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:onClick="addC"
    />
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="next"
    android:onClick="act2"
    android:layout_above="@id/add"
    android:layout_centerHorizontal="true"/>
</RelativeLayout>

Main2Activity (XML):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.exampleryancocuzzo.ryan.testsharedpref.Main2Activity">
<TextView
    android:id="@+id/count2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:textSize="60sp"
    android:layout_centerHorizontal="true"/>
<Button
    android:id="@+id/add2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="ADD TO COUNT"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:onClick="addC2"
    />
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="next"
    android:layout_above="@id/add2"
    android:layout_centerHorizontal="true"
    android:onClick="act1"
    />
</RelativeLayout>

Upvotes: 0

Views: 321

Answers (2)

Viral Patel
Viral Patel

Reputation: 33408

Use this library, which simplifies the use of SharedPreferences and will make life simpler for you.

Android-SharedPreferences-Helper simplifies usage of the default Android SharedPreferences Class. The developer can do in a few lines of code which otherwise would have required several. Simple to understand as compared to the default class and easy to use.

Upvotes: 0

drulabs
drulabs

Reputation: 3121

you must apply commit after putting count value in preferences like this:

editor.commit();

or

editor.apply();

then use it in second activity

Upvotes: 2

Related Questions