Save the changed language on app with Shared Preferences - java

I have this code, are two buttons, one for spanish and other for english, just i use another class which is "Language Helper", to change language, and when its done i reload the activity:
btn_es.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LanguageHelper a = new LanguageHelper();
a.cambiarInt(0);
b = 0;
SharedPreferences sp = getSharedPreferences("language", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("key", b);
editor.apply();
LanguageHelper.changeLocale(getResources(), b);
finish();
startActivity(getIntent());
Animatoo.animateShrink(CMF_Settings.this);
}
});
btn_en.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LanguageHelper a = new LanguageHelper();
a.cambiarInt(1);
b = 1;
SharedPreferences sp = getSharedPreferences("language", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("key", b);
editor.apply();
LanguageHelper.changeLocale(getResources(), b);
finish();
startActivity(getIntent());
Animatoo.animateFade(CMF_Settings.this);
}
});
Two buttons change the language, and this class:
public class LanguageHelper {
int key = 0;
public static void changeLocale(Resources res, int locale) {
Configuration config = new Configuration(res.getConfiguration());
switch (locale) {
case 0:
config.locale = new Locale("es");
break;
case 1:
config.locale = Locale.ENGLISH;
break;
}
res.updateConfiguration(config, res.getDisplayMetrics());
}
public void cambiarInt(int i){
key = i;
}
}
So with that i can change the language in all aplication, but when i close and started again, i use this code to load the saved language:
public void LoadInt() {
SharedPreferences sp = getSharedPreferences("language", Activity.MODE_PRIVATE);
int b2 = sp.getInt("key", b);
if(b2==0){
LanguageHelper a = new LanguageHelper();
a.cambiarInt(0);
LanguageHelper.changeLocale(getResources(), b2);
finish();
startActivity(getIntent());
Animatoo.animateFade(Settings.this);
}else{
LanguageHelper a = new LanguageHelper();
a.cambiarInt(1);
LanguageHelper.changeLocale(getResources(), b2);
finish();
startActivity(getIntent());
Animatoo.animateFade(Settings.this);
}
}
but doesn't load. So there's another easily way to change and save? or what i need more?

Related

Radio Button from another activity remains null?

In one activity I have my radio buttons. I'm able to save the selected state of the radio buttons throughout the application. In another activity I want to check which radio button is checked, but the radio buttons keep returning null.
Here's the first activity:
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
go_back_btn = (Button) findViewById(R.id.go_back_btn);
distancebtn_group = findViewById(R.id.distance_btn_group);
miles_btn = (RadioButton) findViewById(R.id.miles_btn);
kilometer_btn = (RadioButton) findViewById(R.id.kilometer_btn);
go_back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(MILESBTN, miles_btn.isChecked());
editor.putBoolean(KMBTN, kilometer_btn.isChecked());
editor.apply();
Intent intent = new Intent(settings.this, home.class);
intent.putExtra(MILESBTN, miles_btn.isChecked());
intent.putExtra(KMBTN, kilometer_btn.isChecked());
startActivity(intent);
}
});
kilometer_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(KMBTN, kilometer_btn.isChecked());
editor.apply();
}
});
miles_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(MILESBTN, miles_btn.isChecked());
editor.apply();
}
});
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
kilometer_btn.setChecked(sharedPreferences.getBoolean("kilometer_btn", true));
miles_btn.setChecked(sharedPreferences.getBoolean("miles_btn", false));
}
Here's my second activity:
distance_counter = (TextView) findViewById(R.id.distance_counter);
distancebtn_group = (RadioGroup) findViewById(R.id.distance_btn_group);
miles_btn = (RadioButton) findViewById(R.id.miles_btn);
kilometer_btn = (RadioButton) findViewById(R.id.kilometer_btn);
distancebtn_group = findViewById(R.id.distance_btn_group);
final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(settings.GetInfo, MODE_PRIVATE);
final Boolean milesbutton = sharedPreferences.getBoolean(MILESBTN, false);
final Boolean kilometerbutton = sharedPreferences.getBoolean(KMBTN, true);
Boolean milesbtn = getIntent().getBooleanExtra(MILESBTN, false);
Boolean kilometerbtn = getIntent().getBooleanExtra(KMBTN, true);
getIntent().getBooleanExtra(MILESBTN, false);
getIntent().getBooleanExtra(KMBTN, true);
}
}
});
}
#Override
public void onLocationChanged(Location location) {
curr_location = location;
if (start_location == null) {
start_location = curr_location;
end_location = curr_location;
} else
end_location = curr_location;
ChooseMetricUnits();
distance_counter.setText(new DecimalFormat("#.##").format(distance));
current_speed = location.getSpeed() * 2.236936;
SpdInmph.setText(new DecimalFormat("0.00").format(current_speed));
current_speed = location.getSpeed() * 3.6;
SpdInkmh.setText(new DecimalFormat("0.00").format(current_speed));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void distanceInMeters() {
distance = distance + (start_location.distanceTo(end_location));
start_location = end_location;
}
private void distanceInMiles() {
distance = distance + (start_location.distanceTo(end_location) * 0.00062137);
}
private void distanceInkilometers() {
distance = distance + (start_location.distanceTo(end_location) / 1000);
start_location = end_location;
}
public void ChooseMetricUnits() {
final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(settings.GetInfo, MODE_PRIVATE);
Boolean milesbutton = sharedPreferences.getBoolean(MILESBTN, false);
Boolean kilometerbutton = sharedPreferences.getBoolean(KMBTN, true);
Boolean milesbtn = getIntent().getBooleanExtra(MILESBTN, true);
Boolean kilometerbtn = getIntent().getBooleanExtra(KMBTN, true);
getIntent().getBooleanExtra(MILESBTN, false);
getIntent().getBooleanExtra(KMBTN, true);
if(miles_btn.equals(milesbutton)) {
distanceInMiles();
: Run
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Object.equals(java.lang.Object)' on a null object reference
at mobile.run_interface.ChooseMetricUnits(run_interface.java:325)
enter image description here
As you can see the problem is here:
if(miles_btn.equals(milesbutton)) {
I've used BOTH putBoolean and putExtra to see if something different would happen when I pull the values from either one. Same result. I've placed the code for retrieving values, under create AND also under my ChooseMetricsUnits void method. My buttons are still null.
What am I doing wrong?
Has the activities the same layout? If they are not the same checks the import of R.id.miles_btn
And here there is another problem:
if(miles_btn.equals(milesbutton))
miles_btn is the RadioButton and milesbutton is a Boolean, so you must to change the code by:
if(miles_btn.isChecked() == milesbutton)
Solved the problem:
Hopes this helps anyone else in the future...\
private void ChooseMetricUnits() {
final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
final Boolean MetricUnit = sharedPreferences.getBoolean(settings.KMBTN, true);
if(MetricUnit) {
distanceInkilometers();
} else
distanceInMiles();
}
}

Button image not changing in MainActivity.onCreate

I have a mute button that mutes my app via onclick. When I return to MainActivity (where the button is) I use the savedInstanceState method to keep muted or to unmute the app (depending on what was the configuration when the user exited the activity). If the button was clicked and the app is on mute I want (when I return to MainActivity) the button to be shown as muted (I have different images for mute and unmute).
My code:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
mutecounter= sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);} //this if is not working
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayerPool.mute = !MediaPlayerPool.mute;
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
}
}
});
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
editor.apply();
The solution code is
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
mutecounter= sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);
MediaPlayerPool.mute = true;
}
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
MediaPlayerPool.mute = true;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
MediaPlayerPool.mute = false;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
}
editor.apply();
}
});
The problem is that you're saving the muteCounter before the OnClickListener is called.
Your code will set the onClickListener, then immediately save the muteCounter to whatever value is held by mutecounter at that time, which in this case will be 0 every time.
What you need to do is this:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
int mutecounter = sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
ImageButton mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);
}
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayerPool.mute = !MediaPlayerPool.mute;
SharedPreferences.Editor editor = sharedPref.edit();
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
}
editor.apply();
}
});
We're setting the value to save to SharedPreferences inside the OnClickListener here, so that it will always be set when the button is tapped.
That way the next time the view is loaded, it will have the new value in SharedPreferences. The way you have it currently, you're always saving the default value to SharedPreferences, not updating it when the button is pressed.
This happens because the code inside the onClick method is executed only when the button is clicked. and the code outside the onClick method is executed immediately when the activity is created. so the changes made by onClick method will not be reflected in sharedPreference because the code for saving data in preference is not get executed when the onClick method is called.
Solution:
Put the "saving data to SharedPreferences" logic inside the onClick method like this.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
mutecounter= sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);} //this if is not working
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayerPool.mute = !MediaPlayerPool.mute;
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
}
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
editor.apply();
}
});
You can create a new class Data file like:
public class DataStoreTemporary {
////////////////////////////////// INSTANCE //////////////////////////////////
private static DataStoreTemporary instance = null;
public static DataStoreTemporary getInstance() {
if (null == instance) {
synchronized (DataStoreTemporary.class) {
if (null == instance) {
instance = new DataStoreTemporary();
}
}
}
return instance;
}
//Example//
private boolean isMute = false;
public boolean isMute() {
return isMute;
}
public void setMute(boolean mute) {
isMute = mute;
}
}
And for use in your code (in Activity):
boolean mute = DataStoreTemporary.getInstance.isMute; //get information
DaraStoreTemporary.getInstance.setMute(mute); //to save the state
If you don't close the app, this should work.

Select website and its language in AlertDialog and save it

I need to load and save a website and its language in sharedpreferences. When I exit and then open the app, saved website and language load. I have used various ways, but cant achieve it. There is String and int not compatible with each other. My simple code like this:
private SharedPreferences prefs;
private static final String SELECTED_ITEM = "SelectedItem";
private SharedPreferences.Editor sharedPrefEditor;
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
else if (id == R.id.web)
final CharSequence[] items={"English","Arabic","Russian"};
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle("Choose Website");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
});
builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
webView = (WebView) findViewById(R.id.webView);
int website=current_page;
if("English".equals(items[which]))
{
webView.loadUrl("https://english.com");
website=("https://english.com");
}
else if("Arabic".equals(items[which]))
{
webView.loadUrl("https://arabic.com");
website=("https://arabic.com");
}
else if("Russian".equals(items[which]))
{
webView.loadUrl("https://russian.com");
website=("https://russian.com");
}
saveSelectedItem(website);
}
});
builder.show();
}
private int getSelectedItem() {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
return prefs.getInt(SELECTED_ITEM, -1);
}
private void saveSelectedItem(int which) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt(SELECTED_ITEM, which);
sharedPrefEditor.commit();
}
Why are you setting a String to an int variable (website)
You should probably save the language as a preference (String). and then when you load up the app, read the language preference and determine the website from there.
something like below.
public String getWebsite(){
SharedPreferences prefs;
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
String language = prefs.getString("Language", "English");
String website = "";
switch(language){
case "Russian":
website = "russian.com";
break;
default:
website = "english.com";
}
return website;
}
private void saveSelectedItem(String language) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt("language", language);
sharedPrefEditor.commit();
}
when you call save selected item, just pass in items[which] instead of which
in saveSelectedItem(website);
You are passing a string and the method requires int
private void saveSelectedItem(int which) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt(SELECTED_ITEM, which);
sharedPrefEditor.commit();
For saving your data in shared preferences
i recommend to use GSON
i recommend to make a class for example
public class WebsiteData
{
#SerializedName("lang")
#Expose
private String lang ;
#SerializedName("website")
#Expose
private String website;
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang= lang;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website= website;
}
}
When user select language create new object and set the language with the chosen language and the set the website with its corresponding value
Then Turn object into String by Gson Like following :
Gson gson = new Gson();
String dataToSave = gson.toJson(WebsiteData);
String loadedString = getUserData(context);
WebsiteData loadedData = gson.fromJson(loadedString, WebsiteData.class);
to save and load data use the following methods :
public void saveUserData(Context context, String data) {
SharedPreferences sharedpreferences;
sharedpreferences = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(DATA_KEY, data);
editor.apply();
}
public String getUserData(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
return sharedpreferences.getString(DATA_KEY, null);
}

Cant find a way to delete an item from sharedPreferences

I am trying to delete an item from taskList which is connected to sharedPreferences.
I managed to remove all items but the problem is I cant find a way to connect a counter to delete an individual item from a list that has a switch and when this switch is on true I need to remove the item from list by index number.
public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
int pos;
//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
this.context = context;
this.userName = userName;
//go to user shared preferences and fill the list
getData();
notifyDataSetChanged();
}
//how many item to display
#Override
public int getCount() {
//return the myTasks size....
return myTasks.size();
}
//return a specific item by index
#Override
public Object getItem(int i) {
return myTasks.get(i);
}
//return index number
#Override
public long getItemId(int i) {
return i;
}
//create our view
#Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
//inflate the view inside view object -> viewInflated
final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
//set our inflated view behavior
//set pointer for our inflated view
//set pointer for task name....
final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
//set pointer for taskInfo
final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
//set pointer for task status....
final Switch swTask = (Switch) viewInflated.findViewById(taskDone);
//set task name, by the index of my myTasks collection
txtTaskName.setText(myTasks.get(index).taskName);
//set task info, by index of myTasks collection
txtTaskInfo.setText(myTasks.get(index).taskInfo);
//set task status , switch is getting true/false
swTask.setChecked(myTasks.get(index).taskStatus);
//show date and time dialog
final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
dtPicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder ad = new AlertDialog.Builder(context);
final AlertDialog aDialog = ad.create();
final LinearLayout adLayout = new LinearLayout(context);
adLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtTime = new TextView(context);
txtTime.setText("Choose time");
adLayout.addView(txtTime);
final TimePicker tp = new TimePicker(context);
adLayout.addView(tp);
final DatePicker dp = new DatePicker(context);
tp.setVisibility(View.GONE);
adLayout.addView(dp);
final Button btnNext = new Button(context);
btnNext.setText("Next>");
adLayout.addView(btnNext);
btnNext.setGravity(1);
Button btnCancel = new Button(context);
btnCancel.setText("Cancel");
adLayout.addView(btnCancel);
btnCancel.setGravity(1);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aDialog.cancel();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int hour = tp.getHour();
final int min = tp.getMinute();
final String myHour = String.valueOf(hour);
final String myMin = String.valueOf(min);
calendar.set(Calendar.MONTH, dp.getMonth());
calendar.set(Calendar.YEAR, dp.getYear());
calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
dp.setVisibility(View.GONE);
tp.setVisibility(View.VISIBLE);
btnNext.setText("Finish");
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
calendar.set(Calendar.MINUTE, tp.getMinute());
Intent my_intent = new Intent(context, RingtonePlayingService.class);
pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
if(hour > 12){
String myHour = String.valueOf(hour - 12);
}
if(min < 10)
{
String myMin = "0"+String.valueOf(min);
}
Toast.makeText(context, "Set for- "+tp.getHour()+":"+tp.getMinute() , Toast.LENGTH_LONG).show();
aDialog.cancel();
}
});
}
});
aDialog.setView(adLayout);
aDialog.show();
}
});
//create listener event, when switch is pressed
swTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//we using utlShared to update task status
//create instance of utlShared
utlShared myShared = new utlShared(context);
//calling method of task, and giving userName(shared preferences, taskName, taskStatus)
myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
//we sending a message to the user, and inform him/her about the change
Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();
}
});
//return the view with the behavior.....
return viewInflated;
}
private void getData() {
//go to specific shared preferences by user name.....
SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
//create instance of our myTasks list
myTasks = new ArrayList<>();
Map<String, ?> tasks = taskPref.getAll();
for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
//insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
for(int pos=0 ; pos<myTasks.size() ; pos++){
myTasks.get(pos);
}
String[] str = oneTask.getValue().toString().split(",");
myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
}
}
}
And my utlShared class is
public class utlShared {
//context to use later
Context context;
//declatrtion of shared preferences object
private SharedPreferences userPref;
//declaration of shared preferences editor
private SharedPreferences.Editor editor;
public utlShared() {}
public utlShared(Context context)
{
//get context to use it
this.context=context;
//declaretion of shared preferences with file name and file mode (private,public)
userPref=context.getSharedPreferences("users",Context.MODE_PRIVATE);
//declaration of editor
editor=userPref.edit();
}
//get user and password
public void addUser(String userName, String password)
{
//stores in the phone device under data\data\package name
//put in shared preferences user name and password
editor.putString(userName,password);
//commit (save/apply) the changes.
editor.commit();
}
public boolean checkUser(String userName)
{
//get name by key->userName
String checkString = userPref.getString(userName,"na");
//print to logcat a custom message.....
Log.e("checkUser", "checkUser: "+checkString );
//check if userName equals to responded data, if it's na, we don't have the user...
return !checkString.equals("na");
}
public boolean checkUserPassword(String userName, String userPassword)
{
String checkString = userPref.getString(userName,"na");
return checkString.equals(userPassword);
}
public void task(String userName,String taskName,String taskInfo, boolean taskDone)
{
//pointer to user task shared preferences
SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
//create editor to change the specific shared preferences
SharedPreferences.Editor taskEditor=taskPref.edit();
//add new task -> if true write 1 else write 0
if(!taskDone){
String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
taskEditor.putString(taskName,myData);
//apply the changes
taskEditor.commit();
}
}
public void clearTasks(String userName, String taskName, String taskInfo, boolean taskDone)
{
SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
SharedPreferences.Editor tskEditor=taskPref.edit();
tskEditor.clear();
tskEditor.commit();
}
}
This method is called from my Welcome class which is
public class Welcome extends AppCompatActivity {
String userName;
Context context;
utlShared myUtl;
ListView taskList;
String taskName;
String taskInfo;
boolean taskDone;
AlarmManager alarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
setPointer();
}
private void setPointer()
{
this.context=this;
userName=getIntent().getStringExtra("userName");
myUtl = new utlShared(context);
taskList=(ListView)findViewById(R.id.taskList);
setListData();
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Toast.makeText(Welcome.this, "welcome user:"+userName, Toast.LENGTH_SHORT).show();
Button btnBack = (Button)findViewById(R.id.btnBack);
FloatingActionButton btnDelete=(FloatingActionButton)findViewById(R.id.btnDelete);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myUtl.clearTasks(userName, taskName, taskInfo, taskDone);
setListData();
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
finish();
}
});
}
private void setListData() {
final TaskAdapter adapter = new TaskAdapter(context, userName);
taskList.setAdapter(adapter);
}
public void addCustomTask(View view)
{
//create builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
//set title
builder.setTitle("Add new task!");
//inflate view from layout ->custom layout,null,false as defualt values
View viewInflated= LayoutInflater.from(context).inflate(R.layout.dlg_new_task,null,false);
final EditText txtCustomLine = (EditText)viewInflated.findViewById(R.id.txtHLine);
final EditText txtCustomTask = (EditText)viewInflated.findViewById(R.id.txtTask);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setPositiveButton("Add task", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
String myTaskCustom = txtCustomTask.getText().toString();
String myTaskLine = txtCustomLine.getText().toString();
myUtl.task(userName, myTaskCustom, myTaskLine, false);
setListData();
}
});
//display our inflated view in screen
builder.setView(viewInflated);
//show the dialog
builder.show();
}
}
Sorry for the long code but I have spent so much time on that problem and didnt find a normal way to fix it...
Thanks in advance guys, much appreciated!
taskEditor.remove('item tag');
taskEditor.commit();
Guess my question wasnt clear enough but I have found a way to do that.
if(!taskDone){
String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
taskEditor.putString(taskName,myData);
//apply the changes
taskEditor.commit();
}
else
{
taskEditor.remove(taskName);
taskEditor.commit();
adapter.notifyDataSetChanged();
}
Eventhough its not perfect because I can refresh the view after I update the Editor and only after I restart the app my last deleted tasks disappear.
Cheers and thanks a lot guys!

sharedPreferences help. How do I save an int?

I can't for the life of me seem to figure out how to save an int. All I want to do is save leftCounter into a file and retrieve it whenever I reboot my code.
public class SalesTrack extends Activity {
byte leftCounter = 0;
byte centerCounter = 0;
byte rightCounter = 0;
int total;
int x, y, z;
public static final String PREFS = "data";
TextView counterAAL, counterUPG, counterNL, counterTotal;
private final String LEFTY = "6";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales_track);
counterAAL = (TextView) findViewById(R.id.left_number);
counterUPG = (TextView) findViewById(R.id.center_number);
counterNL = (TextView) findViewById(R.id.right_number);
counterTotal = (TextView) findViewById(R.id.total);
SharedPreferences sharedPref = this.getSharedPreferences(LEFTY, 0);
sharedPref.getInt("data", leftCounter);
counterAAL.setText(PREFS);
}
public void LeftInc(View v) {
leftCounter++;
counterAAL.setText("" + leftCounter);
Refresh();
}
public void LeftDec(View v) {
leftCounter--;
counterAAL.setText("" + leftCounter);
Refresh();
}
public void CenterInc(View v) {
centerCounter++;
counterUPG.setText("" + centerCounter);
Refresh();
}
public void CenterDec(View v) {
centerCounter--;
counterUPG.setText("" + centerCounter);
Refresh();
}
public void RightInc(View v) {
rightCounter++;
counterNL.setText("" + rightCounter);
Refresh();
}
public void RightDec(View v) {
rightCounter--;
counterNL.setText("" + rightCounter);
Refresh();
}
// Refresh Total after every click.
public void Refresh() {
x = leftCounter * 10;
y = centerCounter * 20;
z = rightCounter * 35;
total = x + y + z;
counterTotal.setText("" + total);
SharedPreferences sharedPref = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("data", leftCounter);
editor.commit();
}
}
You have a mistake in your code.
// SharedPreferences sharedPref = getSharedPreferences(PREFS, 0); (This line is wrong)
SharedPreferences sharedPref = getSharedPreferences(LEFTY, 0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("data", leftCounter);
editor.commit();
so you get the data from the file but it's detected as String ?
you can use the parse function to convert the String into Integer
int counter = Integer.parseInt(stringvalue);
You get the preferences with two different names LEFTY and PREFS. Given the names, I think you want to change the following line in your onCreate
SharedPreferences sharedPref = this.getSharedPreferences(LEFTY, 0);
to
SharedPreferences sharedPref = this.getSharedPreferences(PREFS, 0);
SharedPreferences sharedPref = getSharedPreferences(LEFTY, 0);
SharedPreferences.Editor editor = sharedPref .edit();
editor.putInt("data", leftCounter);
editor.commit();
You are saving your data inside preference named PREFS and fetching through preference nameLEFTY
Try to change your preference name from LEFTY to PREFS under onCreate().
protected void onCreate(Bundle savedInstanceState)
{
...
SharedPreferences sharedPref = this.getSharedPreferences(PREFS, 0);
}
Change like this
SharedPreferences sharedPref = = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("data", leftCounter);
editor.commit();

Categories