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();
}
}
Related
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?
I am making the application in android studio, in my application i add the feature, if the user click on button second time, then the button is disable and save the state of button in sharedprefernce and if the user closed the app and again open the app then the save button state are shown(if the button is disabled then the disable button is show, else shows enable state ). I put many codes of sharedprefences in my code, but every time the null object reference occurs. My code is given below and I put the shared preferences code on this button but how?
java:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counrClick = counrClick + 1;
if (counrClick == 1) {
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("Url");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("" + "" + "");
request.setDescription("Downloading " + "" + "");
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/" + "filename");
refid = downloadManager.enqueue(request);
Log.e("OUT", "" + refid);
if (counrClick == 2) {
button.setEnabled(false);
}
}
}
});
Please refer the code below. and please remember you can use preference name ("MY_PREF") and key name ("DOWNLOAD_BUTTON_STATUS") to alter preference anywhere else in your application. You can even create a separate class for control all preferences in your application.
private SharedPreferences sharedPreferences;
private Button btn_download_one, btn_download_two, btn_download_three, btn_download_four;
private final String DOWNLOAD_BUTTON_STATUS_KEY_ONE = "DOWNLOAD_BUTTON_STATUS_ONE";
private final String DOWNLOAD_BUTTON_STATUS_KEY_TWO = "DOWNLOAD_BUTTON_STATUS_TWO";
private final String DOWNLOAD_BUTTON_STATUS_KEY_THREE = "DOWNLOAD_BUTTON_STATUS_THREE";
private final String DOWNLOAD_BUTTON_STATUS_KEY_FOUR = "DOWNLOAD_BUTTON_STATUS_FOUR";
private int clickCountOne = 0, clickCountTwo = 0, clickCountThree = 0, clickCountFour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_download_one = findViewById(R.id.button1);
btn_download_two = findViewById(R.id.button2);
btn_download_three = findViewById(R.id.button3);
btn_download_four = findViewById(R.id.button4);
sharedPreferences = getSharedPreferences("MY_PREF", 0);
btn_download_one.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_ONE));
btn_download_two.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_TWO));
btn_download_three.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_THREE));
btn_download_four.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_FOUR));
btn_download_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//... some code
clickCountOne++;
if (clickCountOne == 2)
changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_ONE, false);
}
});
btn_download_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//... some code
clickCountTwo++;
if (clickCountTwo == 2)
changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_TWO, false);
}
});
btn_download_three.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//... some code
clickCountThree++;
if (clickCountThree == 2)
changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_THREE, false);
}
});
btn_download_four.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//... some code
clickCountFour++;
if (clickCountFour == 2)
changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_FOUR, false);
}
});
}
private void changeDownloadButtonStatusPref(String key, boolean status) {
sharedPreferences.edit().putBoolean(key, status).apply();
switch (key) {
case DOWNLOAD_BUTTON_STATUS_KEY_ONE:
btn_download_one.setEnabled(status);
clickCountOne = 0;
break;
case DOWNLOAD_BUTTON_STATUS_KEY_TWO:
btn_download_two.setEnabled(status);
clickCountTwo = 0;
break;
case DOWNLOAD_BUTTON_STATUS_KEY_THREE:
btn_download_three.setEnabled(status);
clickCountThree = 0;
break;
case DOWNLOAD_BUTTON_STATUS_KEY_FOUR:
btn_download_four.setEnabled(status);
clickCountFour = 0;
break;
}
}
private boolean getDownloadButtonStatusPref(String key) {
return sharedPreferences.getBoolean(key, true);
}
//Add this code on button click
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString("enabled", "").apply();
//Add this code in OnCreate/OncreateView Method
String statusLocked1 = prefs.getString("enabled","");
if(statusLocked1.equals("enabled")){
//enable the button
}else{
//disbale the button
}
Try this it will disable button next time you run your activity if it was previously clicked twice;
Button button;
SharedPreferences preferences;
boolean firstclick = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
// SharePrefs
preferences = getSharedPreferences("yourprefsname", 0);
firstclick = preferences.getBoolean("countclick", false);
button = findViewById(R.id.yourbutton);
//disables if it is clicked twice
if (!firstclick){
button.setEnabled(false);
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (firstclick) {
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("Url");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("" + "" + "");
request.setDescription("Downloading " + "" + "");
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/" + "filename");
refid = downloadManager.enqueue(request);
Log.e("OUT", "" + refid);
else{
//edit prefs
preferences.edit().putBoolean("countclick",firstclick).apply();
button.setEnabled(false);
}
}
}
});
}
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.
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!
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();