How to store a list of objects temporarily - java

I have a list of objects which need to persist should the user minimize the app. Is there any way to do this without using SharedPreferences or an SQLite database (seems like overkill for a single list)?

Have the object implement Parclable or Serializable
Then you can just put it in the Bundle
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(key, value);
}
And get it back in onCreate(),onRestoreInstanceState() depending on your needs.

Using a tutorial I found here, I implemented it using SharedPreferences, the main difference was that instead of using a key ,"MEM1", I use an Index. When my activity loads, I can check the size of the index using this code,
for(int x =0; ;x++) {
index = x;
if(sharedPreferences.contains(String.valueOf(x))){
temp = gson.fromJson(sharedPreferences.getString(String.valueOf(x), null), PointOfInterest.class);
pointList.add(temp);
}
else {
break;
}
}
Example:
public class AndroidSharedPreferencesEditor extends Activity {
EditText editText1, editText2;
TextView textSavedMem1, textSavedMem2;
Button buttonSaveMem1, buttonSaveMem2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textSavedMem1 = (TextView)findViewById(R.id.savedmem1);
textSavedMem2 = (TextView)findViewById(R.id.savedmem2);
editText1 = (EditText)findViewById(R.id.edittext1);
editText2 = (EditText)findViewById(R.id.edittext2);
buttonSaveMem1 = (Button)findViewById(R.id.save_mem1);
buttonSaveMem2 = (Button)findViewById(R.id.save_mem2);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
buttonSaveMem2.setOnClickListener(buttonSaveMem2OnClickListener);
LoadPreferences();
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
LoadPreferences();
}
};
Button.OnClickListener buttonSaveMem2OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM2", editText2.getText().toString());
LoadPreferences();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}

Related

How to save the value of the number of touches in a button Android Studio

I want to save the number value so that when close the app it continues to be saved and when open it the progress is maintained. I don't know why SharedPreferences don't work.
I have tried in many ways but either the app forces it to close or it just doesn't work
number = numero
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView contador;
int numero = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("valor", numero);
int data = mPrefs.getInt("valor", numero);
contador = findViewById(R.id.contador);
}
public void onClick(View v) {
numero++;
contador.setText(String.valueOf(numero));
SharedPreferences.Editor data = data.edit();
data.putInt("tag", numero).commit();
}
};
You should use the same sharedPreferences for retrieving the values.
also, get the values by the same key you saved them. below is an example you can follow.
SharedPreferences mPrefs = getSharedPreferences("valor",
Context.MODE_PRIVATE);
try{
int data = mPrefs.getInt("tag", numero);
}
catch(NullPointerException e){
e.printStackTrace()
}
public void onClick(View v) {
numero++;
contador.setText(String.valueOf(numero));
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt("tag", numero).commit();
}
};

How can I improve my use of Android SharedPreference?

I want to run another application whose package name is obtained from EditText in AlertDialog. My problem is that I want to display Dialog only when PackageName has not been specified in SharedPreference or when the application is not available.
Here is my code:
public static final String mypref="mypref";
public static final String packagename="text";
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gpref();
Button b=(Button)findViewById(R.id.btn);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View p1)
{
// TODO: Implement this method
String s=pref.getString(packagename);
if(s!=""){
Intent i=getPackageManager().getLaunchIntentForPackage(s);
if(i!=null){
startActivity(i);
} else{ sd();}
} else{
sd();
}
}
});
}
public void sd(){
final EditText et=new EditText(this);
AlertDialog ad=new AlertDialog.Builder(MainActivity.this).create();
ad.setView(et); ad.setButton(AlertDialog.BUTTON_POSITIVE,
"Set", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface p1, int p2)
{
// TODO: Implement this method
String s=et.getText().toString();
spref(s);
}
});
}
public void gpref(){
pref=getSharedPreferences(mypref,MODE_PRIVATE);
}
public void spref(String s){
gpref();
SharedPreferences.Editor spedit=pref.edit();
spedit.putString(packagename,s); spedit.apply();
}
but I did not find a way to ensure packagename at SharedPreference since packagename has not been set. Would anyone give me some ideas?
Please read official reference about getString
When specific preference does not set, the getString method would be return default value.
you could check against this default value.For example:
String s=pref.getString(packagename,"Default");
if(!s.equals("Default")){
//Do something
}

How to use shared preferences across multiple activities?

I am learning how to use shared preferences and I understand how to set it and get it with one class. However I want to be ale to use shared preferences across two classes. Let me explain.
So in the class below I am basically getting the total number of click counts for whenever the jokes, poems or funny stories button is clicked. This code is below (known as MainActivity):
public class MainActivity extends AppCompatActivity{
final Context context = this;
int clicksCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button jokesButton = findViewById(R.id.button_jokes);
Button poemsButton = findViewById(R.id.button_poems);
Button funnyStoriesButton = findViewById(R.id.button_funny_stories);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
storeClicks(clicksCount);
openContentPage("jokes");
}
});
poemsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
storeClicks(clicksCount);
openContentPage("poems");
}
});
funnyStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
storeClicks(clicksCount);
openContentPage("funnystories");
}
});
}
private void openContentPage(String v) {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intentContentPage.putExtra("keyPage", v);
startActivity(intentContentPage);
}
public void storeClicks(int count)
{
SharedPreferences mSharedPreferences = getSharedPreferences("numberOfClicks", MODE_PRIVATE);
SharedPreferences.Editor meditor = mSharedPreferences.edit();
meditor.putInt("numberOfClicks", count);
meditor.apply();
}
public int getNumberOfClicks(){
SharedPreferences mSharedPreferences = getSharedPreferences("numberOfClicks", MODE_PRIVATE);
int clicksNumber = mSharedPreferences.getInt("numberOfClicks", clicksCount);
return clicksNumber;
}
}
However I have another class known as 'Content' and basically this contains a button known as 'Select Another'. I want this to be included with the click count as well.
So that's the goal basically, no matter what page I am on it should keep track of the number of clicks combined for buttons jokes, poems, funny stories and select another. How can this be implemented?
Below is the code for Content:
public class Content extends AppCompatActivity{
Button selectAnotherButton;
TextView contentText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
selectAnotherButton = findViewById(R.id.button_select_another);
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContent();
}
});
}
You can use Singleton pattern to implement global access to the SharedPreferences. Something like this:
public class SharedPreferencesManager {
private static final String APP_PREFS = "AppPrefsFile";
private static final String KEY_FOR_SOMETHING = "KEY_FOR_SOMETHING";
private SharedPreferences sharedPrefs;
private static SharedPreferencesManager instance;
private SharedPreferencesManager(Context context) {
sharedPrefs =
context.getApplicationContext().getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
}
public static synchronized SharedPreferencesManager getInstance(Context context){
if(instance == null)
instance = new SharedPreferencesManager(context);
return instance;
}
public void setSomething(String something) {
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(KEY_FOR_SOMETHING, something);
editor.apply();
}
public String getSomeKey() {
String someValue = sharedPrefs.getString(KEY_FOR_SOMETHING, null);
return someValue;
}
}
You can have as much as you want methods for getting and setting various values to the SharedPreferences, and it will be accessible through the whole application, just do:
SharedPreferencesManager.getInstance(context).getSomeKey();
Shared Preference is just a common file that contains a set of Key Value Pairs.It would be accessible in any class from your App.
For your case , you can store it as a key value pair in one Class .
Then retrieve it using the same KeyName in another Class.It should retrieve the value you stored in the other class provided the flow is continous.
Please refer below existing stackoverflow answers for more info ::
Android Shared preferences example
Official Docs :
https://developer.android.com/training/data-storage/shared-preferences
Tutorial Example :
https://www.journaldev.com/9412/android-shared-preferences-example-tutorial

SharedPrefenrences not storing boolean value

Am trying save boolean FAVOURITE data in sharedPreferences. when phone is rotated or closed .It is not working it is taking default value. I don't know whats wrong with this code. i am unable to figure out whats the problem is can someone show me the problem with the code
//Context context =this;
String FAVOURITE = "selected";
boolean favourite = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!=null){
favourite = savedInstanceState.getBoolean(FAVOURITE,false);
Toast.makeText(this,""+favourite,Toast.LENGTH_SHORT).show();
}
final Bundle queryBundle = new Bundle();
movieObject=(CardsClass)getIntent().getSerializableExtra("movieObject");
setTitle(movieObject.getmTitle());
setContentView(R.layout.activity_details);
final ImageView fav = (ImageView)findViewById(R.id.fav);
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (favourite == false) {
favourite = true;
fav.setImageResource(R.drawable.fav_on);
Toast.makeText(DetailsActivity.this, favourite + " is added to favourites", Toast.LENGTH_SHORT).show();
queryBundle.putBoolean(FAVOURITE,favourite);
}
else if(favourite){
favourite=false;
fav.setImageResource(R.drawable.fav_off);
queryBundle.putBoolean(FAVOURITE,favourite);
Toast.makeText(DetailsActivity.this, movieObject.getmTitle() + " is removed from favourites", Toast.LENGTH_SHORT).show();
}
}
});
Actually, you're doing the wrong thing. You should do something like:
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(FAVOURITE, favorite); // then you can check the favorite value in onCreate as well.
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
this.favorite = savedInstanceState.getBoolean(FAVOURITE);
// do something here when restore.
super.onRestoreInstanceState(savedInstanceState);
}
To write or read in the SharedPreferences
Write:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(FAVORITE, favorite);
editor.commit();
Read:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Boolean favorite = sharedPref.getBoolean(FAVORITE, true);

Save Dialog Input

I have some buttons in my application, which open up a dialog when clicked on them.
In those dialogs a user can fill in his homework in an edittext.
Anyway i would like to save that user input, so that if I close the dialogs or the application I am able to recall that data and because I am new to eclipse and programming i don't know how to do it.
This is my MainActivity
public class MainActivity extends ActionBarActivity {
protected static final String TAG = null;
private Button bthomeWork;
private Button bthomeWork1;
private Button bthomeWork2;
private Button bthomeWork3;
private Button bthomeWork4;
private AlertDialog.Builder dialogbuilder;
private String strName="";
private void homeworkdialog(){
dialogbuilder = new AlertDialog.Builder(this);
final EditText txtinput = new EditText(this);
dialogbuilder.setTitle("Homework");
dialogbuilder.setMessage("Was sind deine Hausaufgaben?");
dialogbuilder.setView(txtinput);
dialogbuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#SuppressLint("ShowToast") #Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
strName+= txtinput;
Toast.makeText(getApplicationContext(), "Eingetragen", Toast.LENGTH_SHORT);
}
});
dialogbuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#SuppressLint("ShowToast") #Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Kein Eintrag", Toast.LENGTH_SHORT);
}
});
dialogbuilder.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
bthomeWork = (Button)findViewById(R.id.bthomeWork);
bthomeWork1= (Button)findViewById(R.id.bthomeWork1);
bthomeWork2= (Button)findViewById(R.id.bthomeWork2);
bthomeWork3= (Button)findViewById(R.id.bthomeWork3);
bthomeWork4= (Button)findViewById(R.id.bthomeWork4);
bthomeWork.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
homeworkdialog();
}
});
bthomeWork1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
homeworkdialog();
}
});
Hope you can help me:)
You can get the text and save the value of the editText into a String
String MyText = txtinput.getText().toString();
Then you can save the value either using sharedPreferences or into your Database depending on what you want to do
you can save the value in shared preferences like this
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("textvalue", txtInput.getText().toString());
sedt.commit();
Then you can retrieve the saved text in another activity or anywhere in your project like this
SharedPreferences sp = getSharedPreferences("key", 0);
String textValue = sp.getString("textvalue","");
for more information about using shared preferences check out this link http://www.tutorialspoint.com/android/android_shared_preferences.htm
And also note that sharedpreferences are stored as simple xml values...so anyone with a rooted android phone can easily have accesss to the saved value...so if you want to keep the data safe you can check out ways of keeping data safe in android programming http://www.androidsnippets.com/encryptdecrypt-strings

Categories

Resources