Create new SharedPreferences by onClick - android

I'm new to Android Studio, please anyone can assist me with this problem?
I want to create new sharedpref when user have done field in the required field.
When he click the confirm button, automatically will be create new with new Name that with automatically Incremental.
Edit :
Here is my code, dunno if it's true by logical programming or not.
Im using fragment to add the input the required field and back to mainactivity to show the the timer list by using recyclerview.
AddNewTimerFragment.java
private SharedPreferences mPreferences;
private String sharedPrefFile =
"com.mobprog.ius.dwasu";
int position = 1;
meditConfirm_button = rootView.findViewById(R.id.editConfirm_button);
meditConfirm_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String.valueOf(startHour);
String.valueOf(endHour);
String.valueOf(R.array.valueListTimer);
position++;
newSharedPref(startHour, endHour, R.array.valueListTimer, position);
new UploadAlarmDataToServer().execute();
}
});
public void newSharedPref(int toStoreStartHour, int toStoreEndHour, int toStoreInterval, int toStorePosition){
SharedPreferences alarmPref = getActivity().getSharedPreferences("alarmContainer", MODE_PRIVATE);
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.putInt("storedStartHour", toStoreStartHour);
preferencesEditor.putInt("storedEndHour", toStoreEndHour);
preferencesEditor.putInt("storedInterval", toStoreInterval);
preferencesEditor.putInt("storedPosition", toStorePosition);
preferencesEditor.apply();
preferencesEditor.commit();
}
MainActivity.java
int count = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences countpreferences = getApplicationContext().getSharedPreferences("Position", MODE_PRIVATE);
SharedPreferences.Editor countpreferencesEditor = countpreferences.edit();
// Create recycler view.
mRecyclerView = findViewById(R.id.recyclerView);
// Create an adapter and supply the data to be displayed.
mAdapter = new alarmListAdapter(this, mintervalTimeList);
// Connect the adapter with the recycler view.
mRecyclerView.setAdapter(mAdapter);
// Give the recycler view a default layout manager.
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
countpreferencesEditor.putInt("count", 0);
count = countpreferences.getInt("count", 0);
if(count > 0){
for(int i = 0; i < count; i++){
mintervalTimeList.addLast("Interval " + getSharedPreferences("alarmContainer",MODE_PRIVATE).contains("storedPosition"));
}
}
}
Logcat
Process: com.mobprog.ius.dwasu, PID: 4774
java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference
at com.mobprog.ius.dwasu.AddNewAlarmFragment.newSharedPref(AddNewAlarmFragment.java:266)
at com.mobprog.ius.dwasu.AddNewAlarmFragment$5.onClick(AddNewAlarmFragment.java:176)
The code I showed is only the important, not the full that aren't affected by the problem I faced

Related

Loading SharedPreferences in another activity

Here's the problem. In my second class, I'm trying to load the SharedPreferences. Below I'll also include my first class.
//set label for journal questions
public TextView journalQuestionLabel;
public int counter = 0;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_journal);
//TODO: Send saved preferences here
preferences = getSharedPreferences("grammarOption", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
}
When I test it, my debug log always prints -1. It won't load my shared preferences. What am I doing wrong?
I've tried the other answers on here and every tutorial, but they aren't working. Here is my code to set up and save my spinner preferences. I've checked this and it's working.
private void setupSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
final ArrayAdapter grammarSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.array_grammar_options,
android.R.layout.simple_spinner_dropdown_item);
// Specify dropdown layout style - simple list view with 1 item per line
grammarSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//Apply the adapter to the spinner
grammarChoiceSpinner.setAdapter(grammarSpinnerAdapter);
//Create shared preferences to store the spinner selection
SharedPreferences preferences = getApplicationContext().getSharedPreferences
("Selection", MODE_PRIVATE);
editor = preferences.edit();
// Create the intent to save the position
grammarChoiceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//receive the string of the option and store it
int grammarOptionPosition = grammarChoiceSpinner.getSelectedItemPosition();
//put the string in the editor
editor.putInt("grammarOption", grammarOptionPosition);
editor.commit();
//make a toast so the user knows if it's not "select"
if (grammarOptionPosition != 0) {
Toast.makeText(getApplicationContext(), "Choice saved.",
Toast.LENGTH_SHORT).show();
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mGrammar = 0;
}
});
}
Here it's called in onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening);
//find the spinner to read user input
grammarChoiceSpinner = (Spinner) findViewById(R.id.spinner);
setupSpinner();
You are passing wrong String in getSharedPreferences(String, int).
preferences = getSharedPreferences("Selection", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
Give this a try.
I hope it helps.
Make sure your SharedPreference key is same in both the class or even throughout the whole App.
While saving do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
preferences.edit().putInt("grammerOption", 1).apply();
While Getting data from prefs do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
int option = preference.getInt("grammerOption", -1);
PS,
Key for preference(which is MY_PREFS here) must be the same.

Saving and loading listview data using SharedPreferences

I am trying to save my listview items using SharedPreferences. I have somewhat managed to save and load items in the listview. I can add items to it, but when I load the listview after closing it, only the most recent added item is saved. Any help would be appreciated, thanks!
private EditText editTxt;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;
private String item;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editTxt = (EditText) findViewById(R.id.editText);
list = (ListView) findViewById(R.id.List);
arrayList = new ArrayList<String>();
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item, arrayList);
list.setAdapter(adapter);
//load data here
LoadPreferences();
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
FloatingActionButton add = (FloatingActionButton) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (editTxt.getText().toString().length() == 0) {
Toast.makeText(MainActivity.this, "Please enter something into the text box",
Toast.LENGTH_SHORT).show();
} else {
item = editTxt.getText().toString();
arrayList.add(item);
adapter.notifyDataSetChanged();
//save data here
SavePreferences("List", item);
editTxt.setText("");
}
}
});
}
//save listview data
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
//load listview data
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("List", "Add an item...");
adapter.add(dataSet);
adapter.notifyDataSetChanged();
}
You try to save all of clicked items in one SharedPreferences repository. try to change name when save value to SharedPreferences - for example SavePreferences(item.getName(), item); where item.getName method return unique name for this item. But is a bad way. Good way is store multiple data in database.
This is happening because each time the user selects an item from the list, the previous item stored in Preferences is being replaced by the new item since every item is being stored with the same key.
You can try something like this
//save listview data
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String s=data.getString(key,""); //to fetch previous stored values
s=s+"!"+value; //to add new value to previous one
data.edit().putString(key,s).commit();
}
//load listview data
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("List", "Add an item...");
if(dataSet.contains("!")){ //to check if previous items are there or not
String rows[]=dataSet.split("!"); //to get individual rows of list
for(int i=0;i<rows.length;i++){
adapter.add(rows[i); //to add each value to the list
adapter.notifyDataSetChanged();
}
} else{
adapter.add(dataSet);
adapter.notifyDataSetChanged();
}
}

android sharedPreferences to set and retrieve boolean value

I want to save boolean values and then compare them in an if-else block. but when run my application, nothing is displayed.
my Code is here:
prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = prefs.edit();
boolean init = false;
if (init) {
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor.putBoolean("init", true).commit();
}
});
} else {
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
So my question is why shared preferences is not working? please help me.
This is how you need to work with shared preferences.
The senerio I am about to show is to check if this particular activity is running for the first time or not.
Here is what you do in your on create method:
//SharePrefernces
SharedPreferences appIntro = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Check if the Application is Running for the First time
appIntro = getSharedPreferences("hasRunBefore_appIntro", 0); //load the preferences
Boolean hasRun = appIntro.getBoolean("hasRun_appIntro", false); //see if it's run before, default no
//If FirstTime
if (!hasRun) {
//code for if this is the first time the application is Running
//Display Activity
super.onCreate(savedInstanceState);
setContentView(R.layout.app_intro_activity);
//Button to send Confirmation back
Button btn_ok = (Button) findViewById(R.id.appintro_btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Save information that this application has run for the first time
SharedPreferences settings = getSharedPreferences("hasRunBefore_appIntro", 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean("hasRun_appIntro", true);
edit.commit(); //apply
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
});
}//End of if(firstTime)
else {
//code if the Application has run before
super.onCreate(savedInstanceState);
//Navigate Directly to MainActivity
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
}//End of OnCreate()
you are checking always false value of init and it does not enter into your if statement,So prefs will not updated.instead do it as
boolean init = prefs.getBoolean("init",false);
and check it as
if(!init)
i.e. change
boolean init = false;
if (init) {
to
boolean init = prefs.getBoolean("init",false);
if(!init)
You are not using SharedPreferences values in above code . You might need to do like this :
SharedPreferences prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
boolean prefValue = prefs.getBoolean("init", false);
if(!prefValue)
{
// add value in SharedPreferences
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor = prefs.edit();
editor.putBoolean("init", true).commit();
}
});
}
else{
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
The key is : You need to check the preference values first and accordingly code
You can also use SharedPreferences like this:
/* In your onCreate method */
SharedPreferences sp = getSharedPreferences(MyPrefs, Context.MODE_PRIVATE);
if (!sp.getBoolean("first", false)) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("first", true);
editor.apply();
Intent intent = new Intent(this, IntroActivity.class); // Call the one tie launch java class
startActivity(intent);
}

Passing data in a ordered way to another activity

I have a list of college careers, choosing one of the options takes me to a LinearLayout with multiple spinners, which contain class schedules. What is selected in the spinner, is sent to a "textview1" in the same activity.
My question is what would be the best way to put in another activity, in an ordered way, the information within the "textview1"? And of course be saved there.
I have some example code , using a clickable button that only sends the data, there is another button that allows me to start the another activity when you want to see it, but the problem is to organize the information in the second activity, do I really have to do so many strings? I hope you can help me to find a better way. I also want to say that this application is directed to the 2.1 api, if that matters.
Activity1=Administracion.java
public class Administracion extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.administracion);
final TextView lblMensaje = (TextView)findViewById(R.id.LblMensaje);
final Spinner cmbOpciones = (Spinner)findViewById(R.id.CmbOpciones);
final String[] datos =
new String[]{"0031711 Lab Biologia","Lun-Mar 9:30am prof. Marcarian","Elem3","Elem4","Elem5"};
ArrayAdapter<String> elefante =
new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, datos);
elefante.setDropDownViewResource(
R.layout.multiline_spinner_dropdown_item);
cmbOpciones.setAdapter(elefante);
cmbOpciones.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
android.view.View v, int position, long id) {
lblMensaje.setText("Seleccionado: " + datos[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
lblMensaje.setText("");
}
});
final TextView lblMensaje1 = (TextView)findViewById(R.id.LblMensaje1);
final Spinner cmbOpciones1 = (Spinner)findViewById(R.id.CmbOpciones1);
final String cuervo[] =
new String[] {"00311712 Biología I","Mar-Jue 7:00am Prof.Briceño","Elem3","Elem4","Elem5"};
ArrayAdapter<String> adaptador1 =
new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cuervo);
adaptador1.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
cmbOpciones1.setAdapter(adaptador1);
cmbOpciones1.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
android.view.View v, int position, long id) {
lblMensaje1.setText(cuervo[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
lblMensaje1.setText("");
}
});
Button BotonPasar1;
BotonPasar1 = (Button)findViewById(R.id.VB1);
BotonPasar1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String Aguila;
String Canario;
Aguila = lblMensaje.getText().toString();
Canario = lblMensaje1.getText().toString();
SharedPreferences mypreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mypreferences.edit();
editor.putString("Canario", Aguila);
editor.commit();
SharedPreferences mypreferences1 = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor1 = mypreferences1.edit();
editor1.putString("Canario", Aguila);
editor1.commit();
}
});
Button BotonPasar2;
BotonPasar2 = (Button)findViewById(R.id.VB2);
BotonPasar2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Intent pasarahorario = new Intent("com.reversiblelabs.unisvenecas.udobeta.HORARIO");
startActivity(pasarahorario);
}
});
}
}
Activity 2 = Horario.java
public class Horario extends Activity{
TextView llegada, llegada2, llegada3, llegada4;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.horario);
llegada = (TextView) findViewById(R.id.tv1);
llegada2 = (TextView) findViewById(R.id.tv2);
SharedPreferences mypreferences = getApplicationContext().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences mypreferences1 = getApplicationContext().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
String teamnamestring = mypreferences.getString("canario", "no_name");
String hola = mypreferences1.getString("Canario","no_name");
llegada.setText(teamnamestring);
llegada2.setText(hola);
Here is the first activity, the last botton send the data on the textwiews to the second activity, and the first button start the second activity.
1st Activity
Whatever you choose on your spinner, would be seen on its own textview.
Now here is the second activity, I want the data to get organized vertically by hours
7:00 9:00 math
9:00 11:00 chemestry
11:00 1:00 extra
2nd Activity
What I can do to acomplish this?
Here is the first activity, the last botton send the data on the
textwiews to the second activity, and the first button start the
second activity.
No need to do this. Only last button can send all the data and as well start the second activity.
Bundle bundle = new Bundle();
bundle.putString("some constant1", value1);
bundle.putString("some constant2", value2);
Intent intent = new Intent (this, newActvity.class);
intent.putExtra(bundle);
startActivity(intent);
Now here is the second activity, I want the data to get organized
vertically by hours
Use RelativeLayout, laydown view one below another and receive bundle in second activity and show them to user.

How can I save ints to be retained even when the application is not running?

When I click on an option I want a check sign to appear to show it has been purchased. I am using SharedPreferences and have made all the links; however, when I click back or exit and then re-enter the application, the check is gone and any history of anything I did before is gone. How do I save the data so that it is kept even when the application is off or I'm at another page in the game. This is my code so far:
ImageView tick1;
int mYellCheck, mYellCheck1;
public static String sharedPrefs = "MyData";
SharedPreferences data;
SharedPreferences.Editor editor;
int mYellAlpha;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.upgrades);
update();
coins = Replay.totalCoins + Replay4.totalCoins + Replay5.totalCoins
+ Replay6.totalCoins;
data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
tick1.setAlpha(mYellCheck);
}
public void update() {
TextView coinScore = (TextView) findViewById(R.id.tvScore);
coinScore.setText("You have " + coins + " coins");
tick1 = (ImageView) findViewById(R.id.ivtick1);
ImageView moreYellow = (ImageView) findViewById(R.id.ivMoreYellow);
ImageView back = (ImageView) findViewById (R.id.ivBack);
back.setOnClickListener(this);
moreYellow.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ivMoreYellow:
mYellAlpha = 255;
SharedPreferences.Editor editor = data.edit();
editor.putInt("MoreYellowUpgrade", mYellAlpha);
editor.commit();
data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
mYellCheck = data.getInt("MoreYellowUpgrade", 0);
tick1.setAlpha(mYellCheck);
break;
case R.id.ivBack:
Intent i = new Intent ("m.k.zaman.SpotActivity");
startActivity(i);
break;
}
}
EDIT
or Should i just use internal storage?
Try replacing your current onClick call to R.id.ivMoreYellow with this:
case R.id.ivMoreYellow:
mYellAlpha = 255;
mYellCheck = data.getInt("MoreYellowUpgrade", 0);
tick1.setAlpha(mYellCheck);
SharedPreferences.Editor editor = data.edit();
editor.putInt("MoreYellowUpgrade", mYellAlpha);
editor.commit();
break;
You were first overwriting all of the data in the SharedPreferences, and then calling to receive that data that you just overwrote, so I placed the getInt() call before the putInt(). Do you change mYellAplha to anything other than 255 though? If you don't you will never notice a change in SharedPreferences if you are always saving and getting 255.

Categories

Resources