Data not saved in shared preferences on Commit - android

I am trying to save the data received by the fragment into a shared preference so that I can reuse the data stored in shared preference when the same fragment is recreated. But somehow the data is not getting saved and the default value of preference is returned to my fragment.
Below is the code.
Fragment implementing SharePreference
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class StreamFragment extends Fragment {
public String streamUrl=null;
TextView textView;
public static final String playerData="pData";
SharedPreferences playerSettings;
public StreamFragment(){};
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
SharedPreferences playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString(streamUrl,"No Link Found");
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stream, container, false);
playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString("streamLink","No Link Found");
//getData();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
return view;
}
public void getUrl(String data)
{
streamUrl=data;
playerSettings = this.getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = playerSettings.edit();
editor.putString("streamLink", streamUrl);
editor.commit();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
}
}
Thanks in advance!

Instead of streamUrl = playerSettings.getString(streamUrl,"No Link Found");
You should use
streamUrl = playerSettings.getString("streamLink","No Link Found");
And also use apply instead of commit

I try to explain the point here:
Refer to this image:
As you can see, the onCreate is fired before the onCreateview.
Lets analyze your code:
public class StreamFragment extends Fragment {
public String streamUrl=null;
TextView textView;
public static final String playerData="pData";
SharedPreferences playerSettings;
public StreamFragment(){};
Here, your streamUrl is null.
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
/*SharedPreferences -- no needed*/playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString(/*streamUrl -- replace with a key value*/,"No Link Found");
}
That's the first method fired. here you are trying to get a String from sharedPref which should be named null. This point is wrong. the first parameter on getString should be a key, and should be unique everywhere for the same value.
Another thing is that you are istantiating another istance of SharedPreferences with the same name, so remove the cast in the istantiation.
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stream, container, false);
//playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE); -- they are already istantiated
streamUrl = playerSettings.getString(/*streamUrl -- replace with a key value*/,"No Link Found");
//getData();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
return view;
}
Now you are setting streamUrl to the sharedPreferences's value named with the same variable streamUrl.this means:
streamUrl /*which is currently null*/ = playerSettings.getString(null, "No Link Found");
You should still replace the key from streamUrl to a static unique field.
public void getUrl(String data)
{
streamUrl=data;
//playerSettings = this.getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE); -- already done above
SharedPreferences.Editor editor = playerSettings.edit();
editor.putString("streamLink", streamUrl);
//editor.commit(); --replace with apply
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
}
}
This should be the point where you save the value, so the "streamLink" should be the key used above.
Replace commit with apply and remove the istantiation because it's already done
Now.. said that this is how it should look like:
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class StreamFragment extends Fragment {
public String streamUrl=null;
TextView textView;
public static final String playerData="pData";
public static final String valueKey="streamLink";
SharedPreferences playerSettings;
public StreamFragment(){};
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString(valueKey,"No Link Found");
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stream, container, false);
streamUrl = playerSettings.getString(valueKey,"No Link Found");
//getData();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
return view;
}
public void getUrl(String data)
{
streamUrl=data;
SharedPreferences.Editor editor = playerSettings.edit();
editor.putString(valueKey, streamUrl);
editor.apply();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
}
}
Hope this can help you.

Your key to the preference value is not correct. Note the below line.
streamUrl = playerSettings.getString(streamUrl,"No Link Found");
Use some constant value as key.
private static final String STREAM_URL = "stream_url";
and the use the constant as key as mentioned below.
streamUrl = playerSettings.getString(STREAM_URL,"No Link Found");

Your getUrl(String) method not called. So your Shared preference value not stored, called it before playerSettings.getString(streamUrl,"No Link Found");
Also you create instance of "SharedPreferences" two times, remove from onCreateView.Use editor.apply() instead of editor.commit().

you are using two SharedPreferences playerSettings; one globally and one in onCreate and you are using upper one which is not initialized
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class StreamFragment extends Fragment {
public String streamUrl=null;
TextView textView;
public static final String playerData="pData";
SharedPreferences playerSettings;
public StreamFragment(){};
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString("streamLink","No Link Found");
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stream, container, false);
playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString("streamLink","No Link Found");
//getData();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
return view;
}
public void getUrl(String data)
{
streamUrl=data;
playerSettings = this.getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = playerSettings.edit();
editor.putString("streamLink", streamUrl);
editor.commit();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
}
}

Related

Update fragment on all activities

I created a fragment which is basically a counter. When pressed, it updates the number of water glasses you've drunk. This data is stored in SharedPreferences. I also update this number once a day as well.
So i inserted fragment in xml of two activities: Main and the Timer.
It's perfectly work on the Main, when i start the TimerActivity it's also work, but when i go back to Main from Timer i see the last number i've reached in MainActivity, it's not updating and ignore my clicks from TimerActivity.
I think the trouble in "this.getActivity", but i don't know how to fix it. Thanks
Fragment code:
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.example.fitapp.R;
import java.util.Calendar;
public class WaterBottleFragment extends Fragment {
LinearLayout waterBottle;
TextView iconName;
SharedPreferences sPref;
int counter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_water_bottle, container, false);
// Update once a day
Calendar calendar = Calendar.getInstance();
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
sPref = this.getActivity().getSharedPreferences("startApp", Context.MODE_PRIVATE);
int lastDay = sPref.getInt("day", 0);
if(lastDay != currentDay){
SharedPreferences.Editor ed = sPref.edit();
ed.putInt("day", currentDay);
ed.commit();
counter = 0;
} else {
counter = (int) loadText();
}
waterBottle = (LinearLayout) view.findViewById(R.id.ll_water_bottle);
iconName = (TextView) view.findViewById(R.id.tv_icon_water);
iconName.setText(counter + " glasses");
waterBottle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
iconName.setText(counter + " glasses");
saveText();
}
});
return view;
}
// Save number of glasses
private void saveText() {
sPref = this.getActivity().getSharedPreferences("water_counter", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putInt("num_of_glasses", counter);
ed.commit();
Toast.makeText(this.getActivity(), "updated", Toast.LENGTH_SHORT).show();
}
// Load number of glasses
private int loadText() {
sPref = this.getActivity().getSharedPreferences("water_counter", Context.MODE_PRIVATE);
int savedCounter = sPref.getInt("num_of_glasses", 2);
return savedCounter;
}
}
its not a big deal just create an interface like:
Public interface WaterBottleEventListener{
void onBottleClick();
}
create an object of your interface inside your fragment:
WaterBottleEventListener listener;
Then call it inside your waterBottle.setonclicklistener:
waterBottle.setonclicklistener(){
#override
onclick(View v){
listener.onbottleclick();
}
}
Then make both of your activities implement this interface and inside each implementation put your update glass code like this:
Activity1 implement waterBottleEventListener{
#override
onBottleclick(){
counter++;
IconName.setText(...)
...
}
}

How to pass sharedpreferences from one activity to another activity?

I have two activities in my project one activity is MainActivity and another is
Main2activity, In Main2activity I'm taking input from the user and storing it in SharedPreference, Now I want to pass this data to MainActivity and display that data to the user.
The code for Main2activity is
package com.example.to_doapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import java.io.Serializable;
import java.util.ArrayList;
public class Main2Activity extends AppCompatActivity {
public void BackMain ( View view )
{
Intent intent = new Intent( getApplicationContext() ,MainActivity.class ) ;
SharedPreferences sharedPreferences = this.getSharedPreferences( "com.example.to_doapp;", Context.MODE_PRIVATE);
EditText editText = ( EditText) findViewById( R.id.editText3) ;
String s = editText.getText().toString();
sharedPreferences.edit().putString("task" , s ) .apply();
//intent.putStringArrayListExtra("key",arr);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
code foe Mainactivity is
package com.example.to_doapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.Serializable;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public void onclick (View view){
Intent intent = new Intent(getApplicationContext(), Main2Activity.class );
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Intent intent = getIntent();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I want to know how to pass sharedpreferences and how to display that data to user in listview.
Thank you for help in advance.
You can use SharedPreferences getString() method in your second activity.
Here is the documentation: https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String,%20java.lang.String)
SharedPreferences sharedPreferences = this.getSharedPreferences( "com.example.to_doapp;", Context.MODE_PRIVATE);
sharedPreferences.getString("task", "");
You can use the above code to get the data from shared preference any time until it is cleared.
But i would suggest you create a class for the same and carry out all the Preference related task in the same
The simplest way is:
Set SharedPref:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
Editor editor = prefs.edit();
editor.putString(PREF_NAME, "someValue");
editor.commit();
Get SharedPref:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
String yourValue = prefs.getString(PREF_NAME, "");
No need to pass SharedPreferences . you get any activity or fragment on SharedPreferences value..
SharedPreferences shared = getSharedPreferences("Your SharedPreferences name", MODE_PRIVATE);
String data= shared.getString("key", "");
Note : key should be same as edit or save data time used. also SharedPreferences name
same.
When you add a shared preference for the app, it can be accessed from anywhere within the app.
SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(getContext());
String data= shared.getString("nameOfValue", "");
I am sharing you easiest way to set and get sharedpreference data :
First make a class for Shared Preference like that :
public class MySharedPreferences {
private static String MY_PREFS = "MyPrefs";
private static String IS_LOGGED_IN = "is_logged_in";
private static String USERNAME_ID = "username"
public static MySharedPreferences instance;
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public static MySharedPreferences getInstance(Context context) {
if (instance == null)
instance = new MySharedPreferences(context);
return instance;
}
private MySharedPreferences(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void deleteAllSharePrefs(Context context){
this.context = context;
sharedPreferences = context.getSharedPreferences(MY_PREFS,Context.MODE_PRIVATE);
editor.clear().commit();
}
public Boolean getIsLoggedIn(boolean b) {
return sharedPreferences.getBoolean(IS_LOGGED_IN, false);
}
public void setIsLoggedIn(Boolean isLoggedIn) {
editor.putBoolean(IS_LOGGED_IN, isLoggedIn);
editor.commit();
}
public String getUsername() {
return sharedPreferences.getString(USERNAME_ID, "");
}
public void setUsername(String username) {
editor.putString(USERNAME_ID, username);
editor.commit();
}
then where you want to set SharedPreference :
public void BackMain ( View view ){
EditText editText = ( EditText) findViewById( R.id.editText3) ;
MySharedPreferences.getInstance(Main2Activity.this).setUsername(editText.getText().toString());
Intent intent = new Intent( getApplicationContext() ,MainActivity.class )
startActivity(intent);
}
Now, get SharedPreference in your Second Activity:
MySharedPreferences.getInstance(ACTIVITYNAME.this).getUsername();
or in Fragment :
MySharedPreferences.getInstance(getActivity()).getUsername();
or in Adapter :
MySharedPreferences.getInstance(context).getUsername();

How to open a Fragment on click from a fragment in Android

Firstly I'm new to android and sorry for my english.
I have an application where I display images, in it I use a grid with image gallery.
Now I need to make a gallery of images with Gif, so I found this project. LINK
My project uses Fragmets I am trying to convert this project above in mine, however I am having problems in the call Activity.
The initial project activity looks like this:
package com.tenor.android.demo.search.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.tenor.android.core.constant.StringConstant;
import com.tenor.android.core.model.impl.Tag;
import com.tenor.android.core.response.BaseError;
import com.tenor.android.core.util.AbstractUIUtils;
import com.tenor.android.core.widget.adapter.AbstractRVItem;
import com.tenor.android.demo.search.R;
import com.tenor.android.demo.search.adapter.TagsAdapter;
import com.tenor.android.demo.search.adapter.decorations.MainTagsItemDecoration;
import com.tenor.android.demo.search.adapter.rvitem.TagRVItem;
import com.tenor.android.demo.search.adapter.view.IMainView;
import com.tenor.android.demo.search.presenter.IMainPresenter;
import com.tenor.android.demo.search.presenter.impl.MainPresenter;
import com.tenor.android.demo.search.widget.TenorStaggeredGridLayoutManager;
import java.util.ArrayList;
import java.util.List;
/**
* For the MainActivity, we will display a search bar followed by a stream of Tags pulled from the Tenor API.
* Either by clicking on a tag or entering a search, SearchActivity will open.
*/
public class MainActivity extends AppCompatActivity implements IMainView{
// Number of columns for the RecyclerView
private static final int STAGGERED_GRID_LAYOUT_COLUMN_NUMBER = 2;
// Minimum length a search term can be
private static final int TEXT_QUERY_MIN_LENGTH = 2;
// A search box for entering a search term
public EditText mEditText;
// RecyclerView to display the stream of Tags
public RecyclerView mRecyclerView;
// Api calls for MainActivity performed here
private IMainPresenter mPresenter;
// Adapter containing the tag items/view holders
private TagsAdapter mTagsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText) findViewById(R.id.am_et_search);
mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
final String query = textView.getText().toString().trim();
if (query.length() < TEXT_QUERY_MIN_LENGTH) {
Toast.makeText(MainActivity.this, getString(R.string.search_error), Toast.LENGTH_LONG).show();
return true;
}
// The keyboard enter will perform the search
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
startSearch(query);
return true;
}
return false;
}
});
mRecyclerView = (RecyclerView) findViewById(R.id.am_rv_tags);
mRecyclerView.addItemDecoration(new MainTagsItemDecoration(getContext(), AbstractUIUtils.dpToPx(this, 2)));
// Two column, vertical display
final TenorStaggeredGridLayoutManager layoutManager = new TenorStaggeredGridLayoutManager(STAGGERED_GRID_LAYOUT_COLUMN_NUMBER,
StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
mTagsAdapter = new TagsAdapter<>(this);
mRecyclerView.setAdapter(mTagsAdapter);
mPresenter = new MainPresenter(this);
mPresenter.getTags(getContext(), null);
}
private void startSearch(#Nullable final CharSequence text) {
final String query = !TextUtils.isEmpty(text) ? text.toString().trim() : StringConstant.EMPTY;
Intent intent = new Intent(this, SearchActivity.class);
intent.putExtra(SearchActivity.KEY_QUERY, query);
startActivity(intent);
}
#Override
public Context getContext() {
return getBaseContext();
}
#Override
public void onReceiveReactionsSucceeded(List<Tag> tags) {
// Map the tags into a list of TagRVItem for the mTagsAdapter
List<AbstractRVItem> list = new ArrayList<>();
for (Tag tag : tags) {
list.add(new TagRVItem(TagsAdapter.TYPE_REACTION_ITEM, tag));
}
mTagsAdapter.insert(list, false);
}
#Override
public void onReceiveReactionsFailed(BaseError error) {
// For now, we will just display nothing if the tags fail to return
}
}
Here my first change:
Note that I changed the class name to not conflict with my MainActivity
public class MainActivityGif extends Fragment implements IMainView {
And here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setContentView(R.layout.activity_main_gif);
View view = inflater.inflate(R.layout.activity_main_gif, container, false);
How can I call a fragment within another fragment?
private void startSearch(#Nullable final CharSequence text) {
final String query = !TextUtils.isEmpty(text) ? text.toString().trim() : StringConstant.EMPTY;
Intent intent = new Intent(getActivity(), SearchActivity.class);
intent.putExtra(SearchActivity.KEY_QUERY, query);
MainActivityGif.this.startActivity(intent);
}
If I miss the way to ask, I'm sorry, let me understand where I went wrong.
private FragmentManager mFragmentManager;
private FragmentTransaction mFragmentTransaction;
and inside your onCreate
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
and on click call :
FragmentB fragment = new FragmentB ();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.contentFragment, fragment );
mFragmentTransaction.commit();

How to retain variable values in a fragment so when the fragment is launched again the value persists?

I'm making a step counting app that uses navigationview to navigate between different parts of the application and I'm using a fragment for each view, I've setup the Sensor code with a fragment and I store the value in a variable but every time I navigate to another fragment the value of step count is lost and starts from zero. I want the value to remain when I navigate between the different fragments.
import android.app.Fragment;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class HomeFragment extends Fragment implements SensorEventListener {
SensorManager sensorManager;
TextView tv_steps;
boolean running = false;
View myView;
int initialStepCount = 0;
int stepCount = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.home_layout, container, false);
// null pointer exception
// la fragmenta chon view agarrenitawa and make sure null nia
RelativeLayout rl = (RelativeLayout) inflater.inflate(R.layout.home_layout, container, false);
tv_steps = (TextView) rl.findViewById(R.id.tv_steps);
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
return rl;
}
#Override
public void onResume() {
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_FASTEST);
} else {
}
}
#Override
public void onPause() {
super.onPause();
running = false;
// unregister
//sensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (initialStepCount == 0) {
initialStepCount = (int) event.values[0];
}
stepCount = (int)event.values[0] - initialStepCount;
if (running) {
tv_steps.setText(String.valueOf(stepCount));
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
Simple solution:
Declare step count variables as static.
Efficient solution:
Use onSaveInstanceState(Bundle) method to save the value and retrieve it in onCreate(Bundle) method next time.
You can use saveInstance for restoring variable value ,and if you are setting that value to any TextView ,
TextView can save its state by using freezesText attribute:
<TextView
...
android:freezesText="true"/>
For documentation about freezesText : https://developer.android.com/reference/android/widget/TextView.html#attr_android:freezesText
save your values like this:
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(SOME_KEY, someIntValue);
super.onSaveInstanceState(outState);
}
and restore them like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
someIntValue = savedInstanceState.getInt(SOME_KEY)
You can use shared preference to store values.
SharedPreferences sharedpreferences=context.getSharedPreferences("MyPrefs", context.MODE_PRIVATE);
public String getPreference(String name){
Map<String, ?> reader = sharedpreferences.getAll();
if(reader.get(name).toString()!= null){
return reader.get(name).toString();
}
return null;
}
public void setPreference(String name,String value){
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.remove(name);
editor.putString(name,value);
editor.commit();
}

Not saving String value in sharedPreferences

I am trying to save a string in sharedPreferences. I don't know what I did wrong but it doesn't save the String value.
this is the code
here I am saving String value "phone". notice its Fragment page
package com.world.bolandian.watchme;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;
public class LoginFragment extends Fragment implements Listen {
Button loginBtn;
ServerRequest ser;
Connector c;
LoginCommunicationThread loginT;
private LoginUser logUser;
EditText phone,password;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_login, container, false);
}
public void setInterface(Connector c){
this.c=c;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ser=new ServerRequest();
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOGIN_SERVLET);
ser.setResponse(this);
loginT = new LoginCommunicationThread(ser);
phone = (EditText)getActivity().findViewById(R.id.userTxt);
password = (EditText)getActivity().findViewById(R.id.passwordTxt);
loginBtn = (Button) getActivity().findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//save phone number in sharedpreferences
SharedPreferences pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putString("PHONE",String.valueOf(phone.getText()));
edt.commit();
Context context = getActivity();
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("PHONE", String.valueOf(phone.getText()));
logUser = new LoginUser(phone.getText().toString(),password.getText().toString());
if (phone.getText().toString() == null)
{
Toast.makeText(getActivity(),"Please enter phone number", Toast.LENGTH_LONG).show();
}
if(password.getText().toString() == null)
{
Toast.makeText(getActivity(),"Please enter password", Toast.LENGTH_LONG).show();
}
else {
Gson g = new Gson();
String ans = g.toJson(logUser, LoginUser.class);
login(logUser);
}
}
});
}
public void login (LoginUser user)
{
LoginCommunicationThread con;
ServerRequest ser = new ServerRequest();
ser.setResponse(this);
Gson gson = new Gson();
String send = gson.toJson(user,LoginUser.class);
ser.addParamaters(Params.USER,send);
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOGIN_SERVLET);
con = new LoginCommunicationThread(ser);
con.start();
}
#Override
public void good() {
Toast.makeText(getActivity(), "Welcome", Toast.LENGTH_LONG).show();
Intent i = new Intent(getActivity(),MainActivity.class);
startActivity(i);
}
#Override
public void notGood() {
Toast.makeText(getActivity(),"Wrong password or phone",Toast.LENGTH_LONG).show();
}
#Override
public void notGoodServerEroorr() {
Toast.makeText(getActivity(), "Connection Error please try again", Toast.LENGTH_LONG);
}
}
Here i extract the value "PHONE" but i keep getting null. for some reason it doesnt get the value and the default is null (This page is Activity)
package com.world.bolandian.watchme;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
import com.google.gson.Gson;
public class MainActivity extends Activity implements Listen {
private LockAndUnLock sendnotf;
TextView status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (TextView)findViewById(R.id.status);
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabspec = tabHost.newTabSpec("main");
tabspec.setContent(R.id.main);
tabspec.setIndicator("Main");
tabHost.addTab(tabspec);
tabspec = tabHost.newTabSpec("gps");
tabspec.setContent(R.id.GPS);
tabspec.setIndicator("GPS");
tabHost.addTab(tabspec);
tabspec = tabHost.newTabSpec("info");
tabspec.setContent(R.id.INFO);
tabspec.setIndicator("Info");
tabHost.addTab(tabspec);
}
public void Lock (View view)
{
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this);
String phone = sharedPreferences.getString("PHONE", null);
PreferenceManager.getDefaultSharedPreferences(this).getString("PHONE",
null);
sendnotf = new LockAndUnLock(phone,1); // 1 = true = lock
Gson g = new Gson();
String ans=g.toJson(sendnotf, LockAndUnLock.class);
sendLockAndUnlock(sendnotf);
if (status.getVisibility() != View.VISIBLE) {
status.setVisibility(View.VISIBLE);
}
status.setText("LOCKED");
status.setTextColor(Color.RED);
}
public void UnLock (View view)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String phone = sharedPreferences.getString("PHONE",null);
sendnotf = new LockAndUnLock(phone,0); // 0 = false = unlock
Gson g = new Gson();
String ans=g.toJson(sendnotf, LockAndUnLock.class);
sendLockAndUnlock(sendnotf);
if (status.getVisibility() != View.VISIBLE) {
status.setVisibility(View.VISIBLE);
}
status.setText("OPEN");
status.setTextColor(Color.GREEN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void good() {
}
#Override
public void notGood() {
}
#Override
public void notGoodServerEroorr() {
}
public void sendLockAndUnlock(LockAndUnLock sendnotf){
RegisterCommunicationThread con;
ServerRequest ser = new ServerRequest();
ser.setResponse(this);
Gson gson = new Gson();
String send = gson.toJson(sendnotf, LockAndUnLock.class);
ser.addParamaters(Params.LOCKANDUNLOCK,send);
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOCKANDUNLOCK_SERVLET);
con = new RegisterCommunicationThread(ser);
con.start();
}
}
Problem is with different shared preferences objects. According to official documentation:
getPreferences (int mode)
Added in API level 1 Retrieve a SharedPreferences object for accessing
preferences that are private to this activity. This simply calls the
underlying getSharedPreferences(String, int) method by passing in this
activity's class name as the preferences name.
My suggestion is to use special entity for handling shared preferences. In your case it may look like following code
public class SharedPreferencesManager {
private static final String PREFERENCES_NAME = "your_name";//name for xml file
private final SharedPreferences sharedPreferences;
public SharedPreferencesManager(Context context) {
sharedPreferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
}
public String getPhone() {
return sharedPreferences.getString("PHONE", null);
}
public void savePhone(#NonNull String phone) {
sharedPreferences.edit().putString("PHONE", phone).apply(); //or commit for blocking save
}
}
Then replace all your direct call to SharedPreferences in Activity, Fragment with above object.

Categories

Resources