Android - SharedPreferences - Adjusting Code based on Preference Value? - android

Implementing the User's chosen Preferences into my Code is a new conquest for me.
I've successfully implemented a portion of the Preferences to Code, but could use advice.
I have chosen to use the Preferences-API and a PreferenceFragment for my App Settings.
So far I have my SettingsActivity set up, working, and updating new values correctly.
However, some assistance is needed now that I'm implementing Preference values to Code.
There are 2 Preferences which I am struggling to implement into Code.
However, for now, I'll discuss just 1 of them.. The details are as follows :
Preference = Notification Type( key = pref_notificationType ) - ( constant String = PREF_NOTIFICATION_TYPE )
Values :
Sound and Vibration
Sound only
Vibration only
Silent
( NOTE : These are the exact value names for this Preference ).
I want to do something along these lines, except correctly, and efficiently:
public void notificationType() {
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
final String notifType =
getPrefs.getString(PREF_NOTIFICATION_TYPE, "Sound and Vibration");
switch (notifType) {
case ("Sound and Vibration"):
// Create Notification with SOUND (AND) VIBRATION
break;
case ("Sound only"):
// Create Notification with SOUND (only)
break;
case ("Vibrate only"):
// Create Notification with VIBRATION (only)
break;
case ("Silent"):
// Create Notification SILENTLY
break;
default:
// The default is "Sound and Vibration"
break;
}
}
If anybody could please provide some advice on how to go about this, I would greatly appreciate it!
Thanks in advance!

I think in this case the best way create Enum and compare this in swithc.
enum NotificationType {
SOUND_AND_VIBRATE, SOUND_ONLY, VIBRATE_ONLY, SILENT
}
//and
switch (NotificationType) {
case SOUND_AND_VIBRATE:
case SOUND_ONLY:
case VIBRATE_ONLY:
case SILENT:
}

Related

How to open a dialog from Quick settings Tile?

I am developing an app for Quick settings Tile. I want to open a layout or a custom dialog when user click on the tile, whichever is a good option. Assume this as a custom dialog. I tried many examples, but I got no luck!
Thank you in advance.
You just have to #Override method of Tile service.
#Override
public void onClick() {
super.onClick();
Tile tile = getQsTile();
switch (tile.getState()) {
case Tile.STATE_INACTIVE:
// write code for start service or open activity according to your prefrrance
StaticUtils.closeNotificationTopPanel(this);
tile.setLabel(getString(R.string.service_running));
updateTileState(Tile.STATE_ACTIVE);
break;
case Tile.STATE_ACTIVE:
updateTileState(Tile.STATE_INACTIVE);
break;
default:
updateTileState(Tile.STATE_INACTIVE);
break;
}
}
when you Click of tile service button you have to close the notification panel below code will help for that.
public static void closeNotificationTopPanel(Context context) {
Intent closeIntent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(closeIntent);
}
below method will help you to change the tile state and name of a button according to state.
private void updateTileState(int state) {
Tile tile = getQsTile();
if (tile != null) {
tile.setState(state);
Icon icon = tile.getIcon();
switch (state) {
case Tile.STATE_ACTIVE:
icon.setTint(Color.WHITE);
break;
case Tile.STATE_INACTIVE:
case Tile.STATE_UNAVAILABLE:
default:
icon.setTint(Color.GRAY);
break;
}
tile.updateTile();
}
}
Try to use this link: http://wintechtutorials.com/blog/android-customize-quick-setting-tiles-7-0-nougat/
Here in this link they use default Alert dialog. Try to create custom dialog as per need. Hope this will work for you.

how to validate the edittext fields using switch case instead of if-else condition in android?

Previously i am using if else condition for checking the edit text field its working but i need to change into switch case.I am not getting to implement switch case inside my code.please tell me how to implement that in switch case.
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
/**
* Validation
*/
if(tvStartLocation.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter start location", Toast.LENGTH_SHORT).show();
}
else if(tvEndLocation.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter end location", Toast.LENGTH_SHORT).show();
}
else if(etStartOdometer.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter Trip Start Odometer reading", Toast.LENGTH_SHORT).show();
}
else
{
gotonextfraggment();
}
You cannot use a switch-case construct in your case. In a switch-case, only one argument is matched with the case labels and if there is a match, that label is executed.
switch(arg) {
case "label1":
case "label2":
.
.
.
default:
}
arg is tested with label1, label2 and so on.
In your case, in every else-if, you are trying to test the equality of the text in different EditTexts with "". So your arg changes in every else-if. Even if you try to implement switch-case, the arg of your switch-case will change continuously and you'll not be able to go any further. You cannot even do this:
switch("") {
case edittext1.getText():
case edittext2.getText();
.
.
.
default:
}
Because the case labels must be literals not variable values.
So it is impossible to implement switch-case for the problem that you are facing
In fact what you've done right now is the perfect way to do it.

How to use datetime in android?

I have android app as I call html files one of these files page for play sound as user can
manage when the sound play as:
Saturday on
Sunday off
Monday on
and so on. I did my code well, but when I manage select input
option values to on and off it return back to its default when I close
the app or go to another page. So the question is how can keep with
select options values for first time as user selected? Also, if I want
to play sound in specific time as:
Saturday on
5.30am how can I do it?
<play sound method>
public class WebAppInterface {
Context mContext;
public MediaPlayer mp = null;
public static boolean checked = false;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
mp = MediaPlayer.create(mContext,R.raw.sound);
}
#JavascriptInterface
public void playsound(String value ) {
if (value.equals("on")){
checked = true;
mp.setLooping(true);
mp.start();
}
else
{
checked = false;
mp.stop();
}
}
}
HTML code:
<html>
<form >
<select name="flip-1" id="flip-1" data-role="slider" onchange="getAzan(this)" >
<option value="off" >play</option>
<option value="on">off</option>
</select>
</form>
<script type="text/javascript">
function getAzan(sel) {
var value = sel.options[sel.selectedIndex].value;
Android.playsound(value);
}
</script>
Note: I did play sound when user select on value at the code up
I'd say it would be better to save those things into SharedPrefences instead of storing it on a file.
To use SharedPreferences it's pretty simple. When you get the value (i.e.: on or off), just open the SharedPreferences, and put those values in it.
private void editPlayMonday(boolean shouldIPlay) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putBoolean("PlayMonday", shouldIPlay).commit();
}
Once your values are in place, if you want to know if you have to play a song, just check the SharedPreferences, and look what's in it that way:
private void playSong() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean shouldIPlay = prefs.getBoolean("PlayMonday", false);//false being the default value
if(shouldIPlay) {
//play song or whatever
}
}
Now, you can have a boolean in your preferences for each days, and just check if these values or on or off for today's date.
I hope it helps!
EDIT:
So, up there I gave you the keys to manage your player, and when the sound needs to be played. The editPlayMonday function let you register on your application when you need to play your sound, and playSong lets you check the preferences to know if you have to play your song.
Now, in your application, you need to use those functions and link them to the javascript. I'll let you do it, I'm pretty sure there is a lot of tutorials and help about that (i.e.: http://developer.android.com/guide/webapps/webview.html)
The part that I didn't give the details //play song or whatever, in the playSong functions would be a bit more trickier and you should detail a bit more what you want to do with it. What I would advise you to do is to check out the AlarmManager class. It lets you schedule events from your app easily. See the doc for more information or this tutorial on how to implement it.
So to summarize, what you need to do with your application:
Link your HTML switch to the Android editPlay... function so that you can register when you need to play a song.
When you open your webview, check if the SharedPreference corresponding to each days is true or false. This way you can modify the different HTML switch to be on "on" or "off".
In the editPlay... function, and using the AlarmManager, you should schedule an alarm for the next day scheduled, which will link to your song. Remember to check in the SharedPreference if the boolean for the given day is still true. You don't want to play a song the wrong day...
Why don't you keep these values in a database? Or if it's only a few settings you want to remember then just save a file locally and read from it upon starting the application every time.
With regards to your timing question, I think this post should help you Binding MediaPlayer to be played at a specific time .
EDIT
PrintWriter writer = new PrintWriter("nameTheFile.txt", "UTF-8");
writer.println(name);
writer.println(value);
writer.close();
Should write in the file.
Read using:
String name;
Boolean value;
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
name=line;
value=Boolean.Parse(line);
}
As described by #MagicMicky you can use SharedPreferences to store the values in onPause() method
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putBoolean("Monday", true).commit();
and then retrieve the values in onResume().
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean check_monday=prefs.getBoolean("Monday",false); //false being default value
Now your data will be saved even if a user exits the app or move to new activity. As far as Alarm is concerned use AlarmManager different example here to schedule an alarm by checking SharedPreferences for any need for alarm i.e schedule alarm if check_monday==true.

How can I listen for when a notification occurs for my app and calendar app?

I want to be able to listen (BroadcastReceiver?) for whenever a notification occurs for my app and for the calendar app, even if the user doesn't interact with it and even if the screen is off.
I also want to be able to know when a user swipes away the notification.
I know that AccessibilityEvent can enable doing the first thing (listening for notifications) but it can't do the second one (Cannot listen for notification dismissal). Is there another way?
How would I do this? Can I at least have my app/listener called when my own notifications occur (they're for calendar events) and know that the notification is still in the notification tray?
You can listen all the calendar notification info. How you say, you should use an AccessibilityService and switch the notification type. Then you get the package name an compare if it's from google calendar.
public void onAccessibilityEvent(AccessibilityEvent event) {
try {
switch (event.getEventType()) {
case AccessibilityEvent.TYPE_VIEW_CLICKED:
Log.d(LOG_SERVICE, "Click");
break;
case AccessibilityEvent.TYPE_VIEW_FOCUSED:
Log.d(LOG_SERVICE, "Focused");
break;
case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
Log.d(LOG_SERVICE, "Ihas been received a not" + type);
String pack = (String) event.getPackageName();
if (pack.equalsIgnoreCase("com.google.android.calendar")) {
//The event information.
}
break;
default:
type = "otro";
Log.d(LOG_SERVICE, "otro");
break;
}
AccessibilityNodeInfo notinfo = event.getSource();
if (notinfo != null) {
doSomethingWithNodeInfo(notinfo);
}
} catch (Exception e) {
e.printStackTrace();
}
If the Android device is with ICS or more. You can use AccessibilityNodeInfo if the app developer design their notifications with accessibility.

Android: Set Chat State Notifications in Beem App

I am currently using Beem's source code to do developments. I would like to implement the chat state notifications. I have look through the codes and found that there is a setState() method, but I believe it has not been implemented and I have no clues about how to do it. If I use Adium to type a message to the Beem user, the Beem user is able to see that the Adium user is composing a message. But if both users are using Beem, then it does not display if the user is composing a message. Therefore, I would like to try to implement the chat state notification. How do I go about doing it? Is there any guides out there? Can someone help me? Thanks!
Add this code to setState method in ChatAdapter.java file.
org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message();
ChatStateExtension extension = null;
switch (state) {
case "composing":
extension = new ChatStateExtension(ChatState.composing);
break;
case "active":
extension = new ChatStateExtension(ChatState.active);
break;
case "inactive":
extension = new ChatStateExtension(ChatState.inactive);
break;
case "gone":
extension = new ChatStateExtension(ChatState.gone);
break;
case "paused":
extension = new ChatStateExtension(ChatState.paused);
break;
}
message.addExtension(extension);
try {
mAdaptee.sendMessage(message);
} catch (XMPPException e) {
e.printStackTrace();
}

Categories

Resources