Shared Preferences not working in Fragment - android

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.

Related

How to get the text entered in an edittext?

I want to get the data entered in an edittext of android fragment in that same fragment of android.
I want that input details and send to a ble device.
Code is here:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
setCancelable(false);
View view = inflater.inflate(R.layout.verification, null);
verify=(EditText)view.findViewById(R.id.verify);
Next =(Button) view.findViewById(R.id.next);
Cancel=(Button) view.findViewById(R.id.cancel);
Next.setOnClickListener(this);
Cancel.setOnClickListener(this);
appContext = AppContext.getContext();
mContext=getActivity();
appContext = AppContext.getContext();
mOnDataSendListener = appContext.getOnDataSendListener();
timer();
Time=(TextView) view.findViewById(R.id.time);
return view;
}
#Override
public void onClick(View view) {
if(view.getId()==R.id.next){
factoryReset();
}
else {
dismiss();
}
}
Get verify data when you call method factoryReset() & send data as a parameter. Use below line to getText from editText:
verify.getText().toString()
Try with below code :
#Override
public void onClick(View view) {
if(view.getId()==R.id.next){
factoryReset(verify.getText().toString());
}
else {
dismiss();
}
public void factoryReset(String str1){
Log.e("VERIFY_DATA",""+str1);
}

Selected Value of Spinner not displayed at textview after going back to the same page again

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.

Calling fragment after recieved retrofit response (textview and button are null inside fragment)

I am learning Android and came across very strange behavior. I am using Retrofit2 as REST library in android (using asynchronous calls). I want to send authCode and TokenId as Google advise it on my server. When I check if user has set password I do a response. If I return code 206 means that user has not yet set password on my back-end server.
So I want to start a fragment that user will enter password (I am also say that I defined LoginFragment and RegistrationFragment that both work on this Activity). But here is the trick, Fragment get called and when my onCreateView is executed there but TextView and Button has null value why is that? I assume that there is a problem since this is run on background thread but I may be mistaken. Is there a better way to achieve what I want?
My Retrofit call:
private void sendTokenToServer(String idToken, String authCode, String email){
Log.d("APP", authCode);
GoogleTokenRequest googleTokenRequest = new GoogleTokenRequest();
googleTokenRequest.setTokenId(idToken);
googleTokenRequest.setAuthCode(authCode);
googleTokenRequest.setEmail(email);
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<GoogleTokenRequest> call = apiService.sendTokenToBackend(googleTokenRequest);
Log.d("APP", call.toString());
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
call.enqueue(new Callback<GoogleTokenRequest>() {
//execute za sinhroni klic, enqueue za asinhroni
#Override
public void onResponse(Call<GoogleTokenRequest> call, Response<GoogleTokenRequest> response) {
String access_token = response.headers().get("Authorization");
Log.d("APP", access_token);
prefs.edit().putString("access_token",access_token).commit();
int statusCode = response.code();
if (statusCode == 206) {
SetPasswordFragment registerFragment = new SetPasswordFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_login_container, registerFragment);
fragmentTransaction.commit();
}
else{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
This is my fragment code:
public class SetPasswordFragment extends Fragment {
private OnSetPasswordListener onSetPasswordListener;
public SetPasswordFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnSetPasswordListener) {
onSetPasswordListener = (OnSetPasswordListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreate(savedInstanceState);
LayoutInflater lf = getActivity().getLayoutInflater();
View rootView = lf.inflate(R.layout.fragment_set_password, container, false);
Button setPasswordButton = (Button) rootView.findViewById(R.id.btn_set_password_ok);
TextView textView = (TextView) rootView.findViewById(R.id.set_password_message);
Log.d("APP",rootView.toString());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String username = prefs.getString("username", "User");
textView.setText(String.format(getString(R.string.set_password_message), username));
setPasswordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setPasswordValidate();
}
});
return rootView;
}
this is the logcat:
This should probably fix it :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_set_password, container, false);
return rootView;
}
#Override
public void onViewCreated(View view){
Button setPasswordButton = (Button) view.findViewById(R.id.btn_set_password_ok);
TextView textView = (TextView) view.findViewById(R.id.set_password_message);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String username = prefs.getString("username", "User");
textView.setText(String.format(getString(R.string.set_password_message), username));
setPasswordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setPasswordValidate();
}
});
}
Note : I dont rexactly remember the exact parameters for the onViewCreated method but view is definitely there. So I guess this should work.
I know my problem description does not point to the real problem that I found but still I will post it since maybe it will help someone. I my case it was problem in xml file I just removed android:fillViewport="true" or set it to false and it works.

Android Landscape Orientation on Fragment Resetting Shared Preferences

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.

Saving an EditText (textfield) value in fragment

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();
}
}

Categories

Resources