Related: Save ArrayList to SharedPreferences
I have an edit text to enter a value, a button to add it to an ArrayList and save, a button to retrieve and display the value, and a button to reset the ArrayList. But the button to collect constantly displays 2.
public class test extends AppCompatActivity {
ArrayList arrayList = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Button button = findViewById(R.id.create);
Button button1 = findViewById(R.id.recup);
Button button2 = findViewById(R.id.reset);
final EditText editText = findViewById(R.id.editText);
final TextView textView = findViewById(R.id.textView);
//Initialize ArrayList
loadData();
//Button for add variable in arraylist and save
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nombre = editText.getText().toString();
arrayList.add(nombre);
saveData();
}
});
//Button for look arrayList.get(0)
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(String.valueOf(arrayList.get(0)));
}
});
//Button for reset
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferencs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("task list");
editor.commit();
}
});
}
//save data
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferencs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString("task list", json);
editor.apply();
}
//load data
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferencs", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList>() {
}.getType();
arrayList = gson.fromJson(json, type);
}
}
Related
**
I am trying to save the text variable using Sharedpreferences. I saved the variable by this code. But when I click the button the saved variable will go back to 0. I want to start counting from the saved value. please help me
**int counter = 0;
public static final String SHARED_PREF="shared";
public static final String TEXT="text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
counterView=findViewById(R.id.counterid);
Btn=findViewById(R.id.button1);
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
counterView.setText(Integer.toString(counter));
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(TEXT,counterView.getText().toString());
editor.commit();
}
});
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String tValue = sp.getString(TEXT,"");
counterView.setText(tValue);
}
}
Considering the informations you've provided I think you needed to give the counter the value stored in SharedPreferences, to continue the count from that, when the button was pressed again.
Try this:
int counter = 0;
Button adBtn;
TextView counterView;
public static final String SHARED_PREF="shared";
public static final String TEXT="text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counterView=findViewById(R.id.counterid);
adBtn=findViewById(R.id.button1);
adBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences counterSp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String correctCounterValue = counterSp.getString(TEXT,"");
counter = Integer.valueOf(correctCounterValue);
counter++;
counterView.setText(Integer.toString(counter));
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(TEXT,counterView.getText().toString());
editor.commit();
}
});
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String tValue = sp.getString(TEXT,"");
counterView.setText(tValue);
}
Im making a simple app, which counts the clicks of a button and saves the integer with a Shared Preferences. I tried it with the following code, but the app crashes all the time, if I try to open "Singleplayer"
public class Singleplayer extends AppCompatActivity {
private int sp1;
private int record;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singleplayer);
final Button button1 = (Button) findViewById(R.id.buttonspieler1);
final TextView lbl1 = (TextView)findViewById(R.id.lblspieler1);
final TextView lbl2 = (TextView)findViewById(R.id.lblrekord);
SharedPreferences data_record = getSharedPreferences("savegame", 0);
record = data_record.getInt("myKey1", 0);
lbl2.setText(String.valueOf(record));
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
if(sp1< record) {
sp1++;
lbl1.setText(String.valueOf(sp1));
}
else if(sp1>= record)
{
sp1++;
record++;
lbl1.setText(String.valueOf(sp1));
lbl2.setText(String.valueOf(record));
}
}
});
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences data_record = getSharedPreferences("savegame", 0);
SharedPreferences.Editor editor = data_record.edit();
editor.putString("myKey1", String.valueOf(record));
editor.commit();
}
}
you are using sharedPrefrence in your onStop() so you will face many issue here, i suggest to use it at the end of click method
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
if(sp1< record) {
sp1++;
lbl1.setText(String.valueOf(sp1));
}
else if(sp1>= record)
{
sp1++;
record++;
lbl1.setText(String.valueOf(sp1));
lbl2.setText(String.valueOf(record));
}
SharedPreferences data_record = getSharedPreferences("savegame", 0);
SharedPreferences.Editor editor = data_record.edit();
editor.putString("myKey1", String.valueOf(record));
editor.commit();
}
});
so why the app crash, because the sharedPref dosen't carry any value it's null
please check this
I'm new to android development and I'm trying to learn SharedPreferences.
How do I manipulate the value of X using buttons and then save it to SharedPreferences again using a button.
I have to declare SharedPreferences after OnCreate, but if I declare X after
OnCreate I have to set it Final so I can use it in my onClickListener, because it's inner class, but if I do then I'd get a complier error that reads:
"Error:(42, 17) error: cannot assign a value to final variable x"
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
final Editor editor = pref.edit();
int x = pref.getInt("Value", 0);
final TextView txt = (TextView) findViewById(R.id.textView);
final Button ButtonAdd = (Button) findViewById(R.id.buttonPlus);
final Button ButtonMinus = (Button) findViewById(R.id.buttonMinus);
final Button ButtonCommit = (Button) findViewById(R.id.buttonCommit);
final EditText EditText = (EditText) findViewById(R.id.editText);
txt.setText(Integer.toString(x));
ButtonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x = x + 1;
EditText.setText(Integer.toString(x));
}
});
ButtonMinus.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(x != 0){
x=x-1;}
EditText.setText(Integer.toString(x));
}
});
ButtonCommit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
txt.setText(Integer.toString(x));
editor.putInt("Value", x);
}
});
}
}
public class MainActivity extends AppCompatActivity {
private int x; //declare here
Now in your onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
final Editor editor = pref.edit();
x = pref.getInt("Value", 0); //assign values to global variable
//rest of the code
}
See this for different Types of variables and Their usage
declare x as a member field of your Actvity and it will be accessible in your inner class
here I have three buttons Yes no maybe for three buttons I have changed the colour when the button clicked and store the value of clicked button in shared preference for hold the colour when ever I back to the button
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.invitation, null);
eventNameTxtV = (TextView) convertView.findViewById(R.id.invitation_title);
eventPlaceTxtV = (TextView) convertView.findViewById(R.id.invitation_place);
eventNameTxtV.setText(eventMOs.get(position).getText());
eventPlaceTxtV.setText(eventMOs.get(position).getPlace());
convertView.setTag(position);
View v = convertView.findViewById(R.id.invitation_single);
final Button yesBtn = (Button) convertView.findViewById(R.id.yesbutton);
final Button noBtn = (Button) convertView.findViewById(R.id.nobutton);
final Button maybeBtn = (Button) convertView.findViewById(R.id.buttonmaybe);
final LinearLayout eventLayout = (LinearLayout) convertView.findViewById(R.id.invitation_single);
final LinearLayout responseLayout = (LinearLayout) convertView.findViewById(R.id.hidden);
//Based on the user click, response will be stored
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// highlight the button when clicked
yesBtn.setBackgroundColor(Color.YELLOW);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.BLUE);
responseLayout.setVisibility(View.GONE);
//If user clicks yes button in invitation response layout,response would be stored as 1 for event user
final int response = 1;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
//create shared preferences here
prefs =getActivity().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("buttonClicked","true");
editor.commit();
/*SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn", 1);
editor.commit();*/
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.YELLOW);
maybeBtn.setBackgroundColor(Color.BLUE);
responseLayout.setVisibility(View.GONE);
//If user clicks no button in invitation response layout,response would be stored as 0 for event user
final int response = 0;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn", 0);
editor.commit();
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
maybeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.YELLOW);
responseLayout.setVisibility(View.GONE);
//If user clicks maybe button in invitation response layout,response would be stored as for event user
final int response = 2;
userMO.setIsAttending(response);
final long eventId = eventMOs.get(position).getEventId();
SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn",2);
editor.commit();
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
here I have to hold the colour change of button whenever I return back to the app if I selected any of the button .so how to use and retrieve the shared preference value
this is the code for show the yes no maybe buttons together when I clicked the event
eventLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.invitation_single:
responseLayout.setVisibility(View.VISIBLE);
break;
}
}
});
SharedPreferences gives you the ability to store different kind of data, such as boolean or int.
To accomplish your task, you could store the color of each button in SharedPreferences; something like:
editor.putInt("button_one", R.color.buttone_one_selected);
Remember, when you'll retrieve that color, you have to resolve it with:
int buttonOneColor = sharedPrefs.getInt("button_one", default_value);
int colorBackground = getResources().getColor(buttonOneColor);
You can change color of your button using this...
In onCreate:
SharedPreferences prefs = getSharedPreferences("myPrefs",
Context.MODE_PRIVATE);
now check for the boolean value stored in the preferences :
boolean b1_pressed = prefs.getBoolean("button1_pressed",false);
if(b1_pressed){
//code to change color of button to pressed state
}
else{
//code to change color of button to normal state
}
Now in your button's onClick method:
if(b1_pressed){
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",false);
editor.commit();
}
else{
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",true);
editor.commit();
}
This is the write activity. In here I want to write a text and after clicking a button I want this text to appear in a new activity called read activity.
public class Write extends Activity implements OnClickListener
{
EditText text; TextView retrive1;
public static String filename="Mysharedstring" ;
SharedPreferences someData;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.write);
setupVariables();
someData = getSharedPreferences(filename, 0);
}
private void setupVariables()
{
Button sav= (Button) findViewById(R.id.save);
Button ret= (Button) findViewById(R.id.retrive);
text= (EditText) findViewById(R.id.txtText);
retrive1= (TextView) findViewById(R.id.textview);
ret.setOnClickListener(this);
sav.setOnClickListener(this);
}
public void onClick(View v)
{
String stringdata= text.getText().toString();
SharedPreferences.Editor editor = someData.edit();
editor.putString("sharedString", stringdata);
editor.commit();
}
}
I don't know what to write in the read activity.
public void onClick(View v)
{
//???
}
The most simple way that I can think of is this first Activity
Intent intent= new Intent(this, theOtherActivity.class);
intent.putExtra(Key, "Value");
startActivity(intent);
And on theOtherActivity
String receivedData=getIntent().getExtras().getKey(Key);
public void onClick(View v)
{
// get the shared string from the SharedPreference
SharedPreferences sp = getSharedPreferences("Mysharedstring",0);
String s = sp.getString("sharedString","Nothing found.");
// display the shared string
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
Sources for SharedPreferences:
How to save app settings?
How to keep information about an app in Android?
Shared Preferences | Android Developers