In other words. I'd like to create editable textfield in fragment, wich after close or stop of app would be saved. But there's something wrong in line with return notatki; I already have this:
public class DetailFragment2 extends Fragment {
private EditText notatki;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#SuppressLint("SimpleDateFormat")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details2, parent, false);
EditText notatki = (EditText) view.findViewById(R.id.editText1);
SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
notatki.setText(settings.getString("value", ""));
return notatki;
}
#Override
public void onStop( ){
super.onStop();
if(notatki.getText() != null) {
SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("value", notatki.getText().toString());
editor.commit();
}
}
}
When I change return notatki; to return view; it works till the stop of app, when I wanted to save content of editText but it isnt saving anything.
Probably you are setting null to your EditText notatki at:
notatki.setText(settings.getString("value", "raz dwa trzy"));
And thus you have a NPE at onStop() with:
notatki.getText().toString()
To solve this change your onStop() method to:
public void onStop( ){
super.onStop();
if(notatki.getText() != null) {
SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("value", notatki.getText().toString());
editor.commit();
}
}
Related
I faced the issue of not having the textview retaining the value that is selected from the spinner values list. After navigating to the same page, it just keep going back to the same value instead of the value the user has selected.
Here is the code that i have written. Thank You.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifications);
final Switch mySwitch = (Switch) findViewById(R.id.switchNot);
final Spinner mySpin = (Spinner) findViewById(R.id.spinNot);
final TextView tvNot = (TextView) findViewById(R.id.tvTime);
mySwitch.setOnClickListener(new View.OnClickListener() {
SharedPreferences.Editor editor = getSharedPreferences("mapp.com.sg.sadtrial", MODE_PRIVATE).edit();
#Override
public void onClick(View v) {
if (mySwitch.isChecked()) {
editor.putBoolean("Switch", true);
editor.commit();
editor.putBoolean("Spinner",true);
editor.commit();
mySpin.setEnabled(true);
} else {
editor.putBoolean("Switch", false);
editor.commit();
editor.putBoolean("Spinner",false);
editor.commit();
mySpin.setEnabled(false);
}
}
});
final SharedPreferences sharedPrefs =
getSharedPreferences("mapp.com.sg.sadtrial", MODE_PRIVATE);
mySwitch.setChecked(sharedPrefs.getBoolean("Switch", false));
mySpin.setEnabled(sharedPrefs.getBoolean("Spinner",false));
mySpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
SharedPreferences.Editor editor = getSharedPreferences("mapp.com.sg.sadtrial", MODE_PRIVATE).edit();
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
tvNot.setText(mySpin.getSelectedItem().toString());
editor.putString("Option", mySpin.getSelectedItem().toString());
editor.commit();
break;
case 1:
tvNot.setText(mySpin.getSelectedItem().toString());
editor.putString("Option", mySpin.getSelectedItem().toString());
editor.commit();
break;
case 2:
tvNot.setText(mySpin.getSelectedItem().toString());
editor.putString("Option", mySpin.getSelectedItem().toString());
editor.commit();
break;
case 3:
tvNot.setText(mySpin.getSelectedItem().toString());
editor.putString("Option", mySpin.getSelectedItem().toString());
editor.commit();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent){
}
});
tvNot.setText(sharedPrefs.getString("Option", mySpin.getSelectedItem().toString()));
}
The picture of the left is the value displayed in the textview after user has selected from spinner.
The picture on the right shows the value at textview returning to default and is not retaining user's choice
You are trying to set in textView but every time when you come it will try to set the default value 0 in spinner, So we should get the value and we can try to set that like below
Instead of the below line
tvNot.setText(sharedPrefs.getString("Option", mySpin.getSelectedItem().toString()));
Change like this.
String selectedValue = sharedPrefs.getString("Option",
mySpin.getSelectedItem().toString());
if (!TextUtils.isEmpty(selectedValue)) {
for (int i = 0; i < mySpin.getAdapter().getCount(); i++) {
String value = (String) mySpin.getAdapter().getItem(i);
if (selectedValue.equalsIgnoreCase(value)) {
mySpin.setSelection(i);
break;
}
}
}
You have to implement onPause() and onResume() callbacks on wherever (Activity or Fragment) you have Spinner.
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
Now, when you go back to the previous Screen, your Spinner is already saved on what you changed before; you will see the updated spinner.
I have this App where I'm trying to store a button clicked state in a Fragment. But no matter how much I try, nothing seems to be getting stored. My code definitely seems alright.
public class ClubHome extends Fragment {
ImageView bell,bellring;
TextView beltext,belringtext;
SharedPreferences saved_values;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.club_home, container, false);
Bundle args = getArguments();
final String index = args.getString("club", "Party");
saved_values = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
bell= (ImageView) view.findViewById(R.id.bell);
bellring= (ImageView) view.findViewById(R.id.bellring);
beltext= (TextView) view.findViewById(R.id.bellmsg);
belringtext= (TextView) view.findViewById(R.id.bellringmsg);
bell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
belringtext.setVisibility(View.VISIBLE);
bellring.setVisibility(View.VISIBLE);
bell.setVisibility(View.INVISIBLE);
beltext.setVisibility(View.INVISIBLE);
SharedPreferences.Editor editor=saved_values.edit();
editor.putBoolean(index,true);
editor.apply();
editor.commit();
}
});
bellring.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
belringtext.setVisibility(View.INVISIBLE);
bellring.setVisibility(View.INVISIBLE);
bell.setVisibility(View.VISIBLE);
beltext.setVisibility(View.VISIBLE);
SharedPreferences.Editor editor=saved_values.edit();
editor.putBoolean(index,false);
editor.apply();
editor.commit();
}
});
boolean stat = saved_values.getBoolean(index,false);
if (stat){
belringtext.setVisibility(View.INVISIBLE);
bellring.setVisibility(View.INVISIBLE);
bell.setVisibility(View.VISIBLE);
beltext.setVisibility(View.VISIBLE);
} else {
belringtext.setVisibility(View.VISIBLE);
bellring.setVisibility(View.VISIBLE);
bell.setVisibility(View.INVISIBLE);
beltext.setVisibility(View.INVISIBLE);
}
}
}
Your implementation of saving data in SharedPreference is wrong.
You need to get your preference attribute first.
SharedPreference pref = getActivity().getSharedPreferences("MY_PREFERENCES", Activity.MODE_PRIVATE);
Now in the onClickListener of your buttons do something like this to save the desired value.
bell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// .. Set visibility of items.
pref.edit().putBoolean("INDEX", true).apply();
}
});
To get the stored value of INDEX from SharedPreference you need to do something like this
boolean indexStatus = pref.getBoolean("INDEX", false); // false is the default value if nothing is returned.
I am using shared preferences to keep track of a Admin code that is saved on the device, I have noticed that when I go this particular fragment that has a landscape orientation the preference gets called twice and on the second time it resets to its initial null value. this is the only fragment it happens on and i have been able to narrow it down to the line
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
is there a particular correct method to have shared preferences working with a landscape orientation
Here is the Code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final Activity activity = getActivity();
SharedPreferences sharedpreferences = activity.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Boolean Admin_Mode = sharedpreferences.getBoolean("AdminCode", false);
String IPaddress = sharedpreferences.getString("IP Address", "");
System.out.println(IPaddress);
System.out.println(Admin_Mode);
View rootView = inflater.inflate(R.layout.augmented_reality_view, container, false);
ActionBar actionBar = ((ActionBarActivity)activity).getSupportActionBar();
actionBar.hide();
System.out.println("here");
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mSensorManager = (SensorManager)getActivity().getSystemService(Context.SENSOR_SERVICE);
mRotationVectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
mMagneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(this, mRotationVectorSensor, 10000);
mSensorManager.registerListener(this, mMagneticSensor, 10000);
HeadTracker = (ToggleButton) rootView.findViewById(R.id.HeadTracker);
return rootView;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (HeadTracker.isChecked() == true) {
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
SensorManager.getRotationMatrixFromVector(
mRotationMatrix, event.values);
if (mRotationMatrix[2] >= 0.6 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2){
Left = true;
Right = false;
}
else if (mRotationMatrix[2] <= -0.8 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2){
Left = false;
Right = true;
}
else{
Left = false;
Right = false;;
}
}
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
if(event.values[2] >= 390){
MagnetButtonPressed = true;
}
else{
MagnetButtonPressed = false;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onPause()
{
super.onPause();
mSensorManager.unregisterListener(this);
}
Any Advice would be Epic :)
Cheers
Steve
///...... EDIT .........\\\
added in settings fragment code
public class Settings extends PreferenceFragment {
public SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
String IPaddress;
int PortNumber;
Boolean Admin_Mode;
public Settings() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.settings, container, false);
getActivity().setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final SharedPreferences sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
IPaddress = sharedpreferences.getString("IP Address","");
PortNumber = sharedpreferences.getInt("Port Numner", 1);
Admin_Mode = sharedpreferences.getBoolean("AdminCode", false);
final EditText mEdit = (EditText)rootView.findViewById(R.id.ipaddress);
final EditText mEdit2 = (EditText)rootView.findViewById(R.id.portnumber);
final EditText AdminCommandBox = (EditText)rootView.findViewById(R.id.AdminCommandBox);
mEdit.setText(IPaddress);
String strI = Integer.toString(PortNumber);
mEdit2.setText(strI);
Button clickButton = (Button) rootView.findViewById(R.id.Update_Settings);
clickButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("IP Address", mEdit.getText().toString());
editor.putInt("Port Numner", Integer.parseInt(mEdit2.getText().toString()));
editor.commit();
Toast.makeText(getActivity(),"Port and Ip Updated!",Toast.LENGTH_SHORT).show();
}
});
final Button Authorise = (Button) rootView.findViewById(R.id.Authorise_Button);
if (Admin_Mode == false){Authorise.setText("Authorise");}
else if (Admin_Mode == true){Authorise.setText("Deactivate");}
Authorise.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Admin_Mode == false){
if (AdminCommandBox.getText().toString().equals("FerasQUT123")) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("AdminCode", true);
editor.commit();
Toast.makeText(getActivity(),"Code Authorised",Toast.LENGTH_SHORT).show();
Authorise.setText("Deactivate");
}
else{
Toast.makeText(getActivity(),"Please Enter the Correct Code",Toast.LENGTH_SHORT).show();
}
}
else if (Admin_Mode == true){
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("AdminCode", false);
editor.commit();
Toast.makeText(getActivity()," Deactivated",Toast.LENGTH_SHORT).show();
Authorise.setText("Authorise");
}
}
});
return rootView;
}
public void onDestroy() {
super.onDestroy();
}}
In the shared preference i get the state of the admin mode at the beginning of the on create, i set it in the main activity to false and then update it in the settings fragment if the correct code is entered.
Your issue is that you are setting admin mode to false in the activity's onCreate method. When the screen orientation changes, the activity will be destroyed and recreated--so onCreate will be called again, which is setting your admin mode preference to false.
How can I save state of activity that setBackgroundResource and setTextColor I have set up in if sentence remains changed when I start activity again?
if (cases == 1) {
TextView layout = (TextView) findViewById(R.id.textView1);
layout.setBackgroundResource(R.drawable.izbrano);
layout.setTextColor(Color.parseColor("#d7a308"));
ImageView image = (ImageView) findViewById(R.id.imageOdprto);
image.setImageResource(R.drawable.o1);
String strIi = formatter.format(cases);
text.setText(strIi + "€");
}
It seems that you need to store settings instead of the Activity's state. In this case I would suggest using SharedPreferences.
Maybe it is more easy just to remember your cases value (assumed it is global):
#Override
public void onPause(){
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("cases", cases);
editor.commit();
super.onPause();
}
#Override
public void onResume(){
super.onResume();
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
cases = sharedPref.getInt("cases", 0);
if ( cases == 0 ){
// do stuff
} else {
// do more stuff
}
}
Using preferences is not much more preferred.
Here is a nice tutorial for how to save activity states. Check this Link
it suggests,
int someVar;
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("someVar", someVar);
outState.putString(“text”, tv1.getText().toString());
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
someVar = savedInstanceState.getInt("someVar", 0);
tv1.setText(savedInstanceState.getString(“text”));
}
Hey guys I want to make my checkbox stay in the same state every time I open my app.. I get this with the 'ja/nein' string, the string states when i close and open again my application... but my checkbox.setchecked(true/false) doesnt work.. please help
public void changeVisitStatus(){
SharedPreferences visitStatus = mData.getVisitStatus();
SharedPreferences.Editor editor = visitStatus.edit();
if(visitStatus.getString(mData.getVisitKey(), "nein").equals("nein")){
editor.putString(mData.mVisitKey, "ja");
editor.commit();
mGUI.mBtnVisit.setChecked(true);
}
else{
editor.putString(mData.mVisitKey, "nein");
editor.commit();
mGUI.mBtnVisit.setChecked(false);
}
mGUI.getVisitStatus().setText(visitStatus.getString(mData.mVisitKey, "Nein"));
}
EDIT: I tried it another way.. I thought it would be better but doesnt work as well..
public void changeVisitStatus(){
SharedPreferences visitStatus = mData.getVisitStatus();
SharedPreferences.Editor editor = visitStatus.edit();
if(visitStatus.getString(mData.getVisitKey(), "nein").equals("nein")){
editor.putString(mData.mVisitKey, "ja");
editor.putBoolean("isChecked", true);
editor.commit();
}
else{
editor.putString(mData.mVisitKey, "nein");
editor.putBoolean("isChecked", false);
editor.commit();
}
mGUI.getVisitStatus().setText(visitStatus.getString(mData.mVisitKey, "Nein"));
}
and put this one into my onCreate(Bundle savedInstanceState) in my Activity
mGUI.mBtnVisit.setChecked(mData.getVisitStatus().getBoolean("isChecked", false));
Try like this:
public void putBooleanInPreferences(boolean isChecked,String key){
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.commit();
}
public boolean getBooleanFromPreferences(String key){
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
Boolean isChecked = sharedPreferences.getBoolean(key, false);
return isChecked;
}
and in onCreate()
CheckBox checkBox = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkBox = (CheckBox) findViewById(R.id.my_check_box);
boolean isChecked = getBooleanFromPreferences("isChecked");
Log.i("start",""+isChecked);
checkBox.setChecked(isChecked);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
Log.i("boolean",""+isChecked);
TestActivity.this.putBooleanInPreferences(isChecked,"isChecked");
}
});
}
Hope this may help you!
You're showing us only the code for changing the status, probably called from OnClick listener for the check box.
You should also add code that only reads status from SharedPreferences and sets check box state according to that (could be same code, but the if condition negated).
You need to call that code from OnCreate event.
public void setVisitStatus(){
SharedPreferences visitStatus = mData.getVisitStatus();
mGUI.getVisitStatus().setText(visitStatus.getString(mData.mVisitKey, "Nein"));
}