Search Results

Search found 79 results on 4 pages for 'sharedpreferences'.

Page 1/4 | 1 2 3 4  | Next Page >

  • Need help with android.os.Build.VERSION.SDK_INT and SharedPreferences

    - by Fenderf4i
    I have a main activity where I call VersionSettings vs = new VersionSettings(this); if (vs.firstRun2()) vs.versionCheckbox(); What I'm trying to do is set a checkbox (checkboxVideoType) to an unchecked state if the Android version is 1.6-2.1 I only want to do this the very first time the app is ever run, it never needs to run again. I think I'm running into the problem when the main activity calls versionCheckbox(), I get a force close if it attempts to run the code inside that is going to set the checkbox to false. I'm very new to programming and would really appreciate some help with this. I think I'm close, but need a push. Thanks in advance! Main Activity import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageView; public class Nasatv extends Activity implements OnClickListener { boolean checkboxIsChecked; SharedPreferences nasaTV_Prefs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title); nasaTV_Prefs = getSharedPreferences("nasaTV_Prefs", 0); ChangeLog cl = new ChangeLog(this); if (cl.firstRun()) cl.getLogDialog().show(); VersionSettings vs = new VersionSettings(this); if (vs.firstRun2()) vs.versionCheckbox(); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(this); Button button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(Nasatv.this, LaunchCalendar.class); startActivity(i); } }); Button button3 = (Button) findViewById(R.id.button3); button3.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(Nasatv.this, PhotoInfo.class); startActivity(i); } }); CheckConnectivity check = new CheckConnectivity(); Boolean conn = check.checkNow(this.getApplicationContext()); if(conn == true){ ImageView updateImage = (ImageView) findViewById(R.id.updateImage); ImageDownloader downloader = new ImageDownloader(updateImage); downloader.execute("http://www.url.com/trl/ubox.jpg"); } else { ImageView updateImage = (ImageView) findViewById(R.id.updateImage); updateImage.setImageResource(R.drawable.uboxerror); } } public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.setting_title: Intent settingsActivity =new Intent(getBaseContext(), Settings.class); startActivity(settingsActivity); return true; case R.id.photo_archive: Intent archive = new Intent(Nasatv.this, PhotoArchive.class); startActivity(archive); return true; case R.id.n_web: Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.nasa.gov/")); startActivity(intent); return true; case R.id.exit_title: finish(); return true; default: return super.onOptionsItemSelected(item); } } public void onResume() { super.onResume(); checkboxIsChecked = nasaTV_Prefs.getBoolean("checkboxVideoType", true); } @Override public void onClick(View v) { if (checkboxIsChecked) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.nasa.gov/multimedia/nasatv/nasatv_android_flash.html")); startActivity(intent); } else { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("rtsp://nasadln.qt.llnwd.net/nasa101.sdp")); startActivity(intent); } } } One-time run class import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import android.widget.CheckBox; public class VersionSettings { private final Context context; private String notRun, hasRun; private SharedPreferences run; private CheckBox checkboxVideoType; private SharedPreferences nasaTV_Prefs; private static final String HAS_RUN = "PREFS_HAS_RUN"; int currentapiVersion = android.os.Build.VERSION.SDK_INT; /** * Constructor * * Retrieves whether the app has been run or not and saves to * SharedPreferences */ public VersionSettings(Context context) { this.context = context; this.run = PreferenceManager.getDefaultSharedPreferences(context); // get run/not run string number, which is "1" this.notRun = run.getString(HAS_RUN, ""); Log.d(TAG, "notRun: " + notRun); this.hasRun = context.getResources().getString(R.string.has_run_string); Log.d(TAG, "hasRun: " + hasRun); // save new number to preferences, which will be the same number, // so this is run only the very first time the app is run SharedPreferences.Editor editor = run.edit(); editor.putString(HAS_RUN, hasRun); editor.commit(); } /** * @return true if this version of your app is started for the first * time */ public boolean firstRun2() { return ! notRun.equals(hasRun); } /** * @return Change the checkboxVideoType to "unchecked" (false) * */ public void versionCheckbox() { // this.context = context; if (currentapiVersion < android.os.Build.VERSION_CODES.FROYO){ this.nasaTV_Prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = nasaTV_Prefs.edit(); editor.putBoolean("checkboxVideoType", false); editor.commit(); } } private static final String TAG = "VersionSettings"; } Preferences Activity import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; public class Settings extends Activity implements OnCheckedChangeListener { private CheckBox checkboxVideoType; private SharedPreferences nasaTV_Prefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.preferences); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title); checkboxVideoType = (CheckBox) findViewById(R.id.checkboxVideoType); checkboxVideoType.setOnCheckedChangeListener(this); nasaTV_Prefs = getSharedPreferences("nasaTV_Prefs", 0); checkboxVideoType.setChecked(nasaTV_Prefs.getBoolean("checkboxVideoType", true)); Button clbutton = (Button) findViewById(R.id.clbutton); clbutton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ChangeLog cl = new ChangeLog(Settings.this); cl.getFullLogDialog().show(); } }); } public void onCheckedChanged(CompoundButton cb, boolean isChecked) { if (cb == checkboxVideoType){ SharedPreferences.Editor editor = nasaTV_Prefs.edit(); editor.putBoolean("checkboxVideoType", isChecked); editor.commit(); // Commit the edit, i.e., save the state of the flag! } } }

    Read the article

  • Saving to SharedPreferences from custom DialogPreference

    - by Ronnie
    I've currently got a preferences screen, and I've created a custom class that extends DialogPreference and is called from within my Preferences. My preferences data seems store/retrieve from SharedPreferences without an issue, but I'm trying to add 2 more sets of settings from the DialogPreference. Basically I have two issues that I have not been able to find. Every site I've seen gives me the same standard info to save/restore data and I'm still having problems. Firstly I'm trying to save a username and password to my SharedPreferences (visible in the last block of code) and if possibly I'd like to be able to do it in the onClick(). My preferences XML that calls my DialogPreference: <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory> <com.rone.optusmon.AccDialog android:key="AccSettings" android:title="Account Settings" android:negativeButtonText="Cancel" android:positiveButtonText="Save" /> </PreferenceCategory> </PreferenceScreen> My Preference Activity Class: package com.rone.optusmon; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.view.KeyEvent; public class EditPreferences extends PreferenceActivity { Context context = this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } My Custom DialogPreference Class file: package com.rone.optusmon; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.preference.DialogPreference; import android.preference.PreferenceManager; import android.text.method.PasswordTransformationMethod; import android.util.AttributeSet; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class AccDialog extends DialogPreference implements DialogInterface.OnClickListener { private TextView mUsername, mPassword; private EditText mUserbox, mPassbox; CharSequence mPassboxdata, mUserboxdata; private CheckBox mShowchar; private Context mContext; private int mWhichButtonClicked; public AccDialog(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } @Override protected View onCreateDialogView() { @SuppressWarnings("unused") LinearLayout.LayoutParams params; LinearLayout layout = new LinearLayout(mContext); layout.setOrientation(LinearLayout.VERTICAL); layout.setPadding(10, 10, 10, 10); layout.setBackgroundColor(0xFF000000); mUsername = new TextView(mContext); mUsername.setText("Username:"); mUsername.setTextColor(0xFFFFFFFF); mUsername.setPadding(0, 8, 0, 3); mUserbox = new EditText(mContext); mUserbox.setSingleLine(true); mUserbox.setSelectAllOnFocus(true); mPassword = new TextView(mContext); mPassword.setText("Password:"); mPassword.setTextColor(0xFFFFFFFF); mPassbox = new EditText(mContext); mPassbox.setSingleLine(true); mPassbox.setSelectAllOnFocus(true); mShowchar = new CheckBox(mContext); mShowchar.setOnCheckedChangeListener(mShowchar_listener); mShowchar.setText("Show Characters"); mShowchar.setTextColor(0xFFFFFFFF); mShowchar.setChecked(false); if(!mShowchar.isChecked()) { mPassbox.setTransformationMethod(new PasswordTransformationMethod()); } layout.addView(mUsername); layout.addView(mUserbox); layout.addView(mPassword); layout.addView(mPassbox); layout.addView(mShowchar); return layout; // Access default SharedPreferences SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); } public void onClick(DialogInterface dialog, int which) { mWhichButtonClicked = which; // if statement to set save/cancel button roles if (mWhichButtonClicked == -1) { Toast.makeText(mContext, "Save was clicked", Toast.LENGTH_SHORT).show(); mUserboxdata = mUserbox.getText(); mPassboxdata = mPassbox.getText(); // Save user preferences SharedPreferences settings = getDefaultSharedPreferences(this); SharedPreferences.Editor editor = settings.edit(); editor.putString("usernamekey", (String) mUserboxdata); editor.putString("passwordkey", (String) mPassboxdata); } else { Toast.makeText(mContext, "Cancel was clicked", Toast.LENGTH_SHORT).show(); } } } In my SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); line, Eclipse says "The method getDefaultSharedPreferences(AccDialog) is undefined for the type AccDialog". I've attempted to change the context to my preferences class, use a blank context and I've also tried naming my SharedPrefs and using "getSharedPreferences()" as well. I'm just not sure exactly what I'm doing here. As I'm quite new to Java/Android/coding in general, could you please be as detailed as possible with any help, eg. which of my files I need to write the code in and whereabouts in that file should I write it (i.e. onCreate(), onClick(), etc) Edit: I will need to the preferences to be Application-wide accessible, not activity-wide. Thanks

    Read the article

  • Problem with SharedPreferences

    - by user547995
    Code for restore: final SharedPreferences settings = getSharedPreferences("pref", 0); settings.getString("user", ""); settings.getString("pw", ""); Code for store: SharedPreferences.Editor editor = settings.edit(); editor.putString("user", etuser.getText().toString()); editor.putString("pw", etpw.getText().toString()); editor.commit(); This code don't work, and no error occur

    Read the article

  • BroadcastReceiver not reading stored value from SharedPreferences

    - by bobby123
    In my app I have a broadcast receiver that turns on GPS upon receiving a set string of text. In the onLocationChanged method, I want to pass the GPS data and a value from my shared preferences to a thread in a string. I have the thread writing to log and can see all the GPS values in the string but the last value from my shared preferences is just showing up as 'prefPhoneNum' which I initialised the string to at the beginning of the receiver class. I have the same code to read the prefPhoneNum from shared preferences in the main class and it works there, can anyone see what I might be doing wrong? public class SmsReceiver extends BroadcastReceiver implements LocationListener { LocationManager lm; LocationListener loc; public SharedPreferences sharedpreferences; public static final String US = "usersettings"; public String prefPhoneNum = "prefPhoneNum"; @Override public void onReceive(Context context, Intent intent) { sharedpreferences = context.getSharedPreferences(US, Context.MODE_PRIVATE); prefPhoneNum = sharedpreferences.getString("prefPhoneNum" , ""); lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); loc = new SmsReceiver(); //---get the SMS message passed in--- Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str = ""; if (bundle != null) { //---retrieve the SMS message received--- Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i=0; i<msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); str += msgs[i].getMessageBody().toString() + "\n"; } Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); //Display SMS if ((msgs[0].getMessageBody().toString().equals("Enable")) || (msgs[0].getMessageBody().toString().equals("enable"))) { enableGPS(); } else { /* Do Nothing*/ } } } public void enableGPS() { //new CountDownTimer(10000, 1000) { //10 seconds new CountDownTimer(300000, 1000) { //300 secs = 5 mins public void onTick(long millisUntilFinished) { lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loc); } public void onFinish() { lm.removeUpdates(loc); } }.start(); } @Override public void onLocationChanged(Location location) { String s = ""; s += location.getLatitude() + "\n"; s += location.getLongitude() + "\n"; s += location.getAltitude() + "\n"; s += location.getAccuracy() + "\n" + prefPhoneNum; Thread cThread = new Thread(new SocketsClient(s)); cThread.start(); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } } Here is the logcat for when the application shuts - D/LocationManager( 3912): requestLocationUpdates: provider = gps, listener = accel.working.TrackGPS@4628bce0 D/GpsLocationProvider( 96): setMinTime 0 D/GpsLocationProvider( 96): startNavigating D/GpsLocationProvider( 96): TTFF: 3227 D/AndroidRuntime( 3912): Shutting down VM W/dalvikvm( 3912): threadid=1: thread exiting with uncaught exception (group=0x400259f8) E/AndroidRuntime( 3912): FATAL EXCEPTION: main E/AndroidRuntime( 3912): java.lang.NullPointerException E/AndroidRuntime( 3912): at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146) E/AndroidRuntime( 3912): at accel.working.TrackGPS.onLocationChanged(TrackGPS.java:63) E/AndroidRuntime( 3912): at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:191) E/AndroidRuntime( 3912): at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:124) E/AndroidRuntime( 3912): at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:140) E/AndroidRuntime( 3912): at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime( 3912): at android.os.Looper.loop(Looper.java:144) E/AndroidRuntime( 3912): at android.app.ActivityThread.main(ActivityThread.java:4937) E/AndroidRuntime( 3912): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime( 3912): at java.lang.reflect.Method.invoke(Method.java:521) E/AndroidRuntime( 3912): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) E/AndroidRuntime( 3912): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) E/AndroidRuntime( 3912): at dalvik.system.NativeStart.main(Native Method)

    Read the article

  • User not being saved, SharedPreferences

    - by Lars
    Hi i have a inlogscreen (inlogdialog.xml), which includes 2 EditText (username, passwd) and i have a CheckBox (saveuser) with which the user can decide weather to save the username or not. On the mainform (main.xml) i have a listner for these 3 values: private class OnReadyListener implements MyCustomForm.ReadyListener { public void ready(String user, String pass, boolean save) { username = user; password = pass; } } Now i first want to save the username through SharedPreferences but it doesn`t get saved, can someone help me please? If i check with system.out.println, the username is present in String username. SharedPreferenes code in main.xml: public static final String USERNM = ""; private SharedPreferences mPrefs; ....... @Override protected void onPause() { Editor e = mPrefs.edit(); e.putString(USERNM, username); <---- e.commit(); Toast.makeText(this, "Items saved.", Toast.LENGTH_SHORT).show(); super.onPause(); }

    Read the article

  • Question about SharedPreferences

    - by chobo2
    I am looking an android Shared Preferences and I am wondering is there a way to just check if the preferences file exists. SharedPreferences mySharedPreferences ; mySharedPreferences=getSharedPreferences(“Name_of_your_preference”,mode); This above code leads me to believe that "Name_of_Your_preferene" is stored as a file or some sort of container that will contain your preferences. I am wondering is there away to check if this exists or not. When a user loads up an activity I want to save all the settings into this file with some default values(off for all settings). However I only want to do this if they are going to the page for the first time. Otherwise if I would do something like this every time the page loads up SharedPreferences.Editor editor= mySharedPreferences.edit(); /* now store your primitive type values. In this case it is true, 1f and Hello! World */ editor.putBolean(“myBoolean”,true); editor.putFloat(“myFloat”,1f); editor.putString(“myString”,” Hello! World”); I am guessing it would override all settings even ones they set.

    Read the article

  • retrieving and restoring textview information from sharedpreferences

    - by user1742524
    I have an activity that allows user to enter notes and store them in dynamically created textviews. However, when the use leaves the activity and returns, all the created textviews disappear. How can i store store or retrieve all of these created textviews, whenever i return to the activity? Also, i think that my sharedpreferences will be overwriting each time a new textview is added. Any suggestions? public class DocNoteActivity extends Activity { private LinearLayout nLayout; private EditText etDocNote; private Button btnAdd1; public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.adddocnote); etDocNote = (EditText) findViewById(R.id.editDocNote); btnAdd1 = (Button) findViewById(R.id.btnAdd1); nLayout = (LinearLayout) findViewById(R.id.linearLayout); TextView tvNote = new TextView(this); tvNote.setText(""); btnAdd1.setOnClickListener(onClick()); } private OnClickListener onClick() { // TODO Auto-generated method stub return new OnClickListener(){ public void onClick(View v) { // TODO Auto-generated method stub String newDocNote = etDocNote.getText().toString(); nLayout.addView(createNewTextView(newDocNote)); getSharedPreferences("myprefs", 0).edit().putString("etDocNote", newDocNote).commit(); } }; } private TextView createNewTextView(String newText) { // TODO Auto-generated method stub LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); TextView tvNote = new TextView(this); tvNote.setLayoutParams(lparams); tvNote.setText(newText); return tvNote; } }

    Read the article

  • Android SharedPreferences set True or False - Clear on App Exit

    - by KickingLettuce
    I want a notification to pop up when an app opens. But once User dismisses, I don't want it to come back again, even if they go back to the same activity. But when the app exits, and they come back later, I want same dialog notification to pop up (prompting user to login). So basically... boolean b = true; if (b == true) { // show dialog b = false; } I simply want var b to save state but clear on exit.

    Read the article

  • Read SharedPreferences when you haven't set the name of the file.

    - by Pentium10
    When you createa a PreferenceScreen on Android, your application creates a default SharedPreferences file for the settings. I want to read this name, or get a reference without specifing the name. Currently I use: SharedPreferences prefs = ctx.getSharedPreferences("prefs", 0); SharedPreferences.Editor ed=prefs.edit(); But this returns another copy of the preference. When I checked the folder in /data/data/myapk/shared_prefs I see two files, one named prefs.xml and the other is my [package name]_preferences.xml (this was created by the PreferenceActivity); How do I get an instance of the shared preference with the usage of the default file name, so I should not mention a name for it?

    Read the article

  • How do I get the SharedPreferences from a PreferenceActivity in Android?

    - by Dave
    Hi, I am using a PreferenceActivity to show some settings for my application. I am inflating the settings via a xml file so that my onCreate (and complete class methods) looks like this: public class FooActivity extends PreferenceActivity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.preference); } } The javadoc of PreferenceActivity states, that These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android.content.Context) with a context in the same package as this activity. But how I get the name of the SharedPreference in another Activity? I can only call getSharedPreferences(name, mode) in the other activity but I need the name of the SharedPreference which was used by the PreferenceActivity. What is the name or how can i retrieve it?

    Read the article

  • SharedPreferences.onSharedPreferenceChangeListener not being called consistently

    - by synic
    I'm registering a preference change listener like this (in the onCreate() of my main activity): SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.registerOnSharedPreferenceChangeListener( new SharedPreferences.OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged( SharedPreferences prefs, String key) { System.out.println(key); } }); The trouble is, the listener is not always called. It works for the first few times a preference is changed, and then it is no longer called until I uninstall and reinstall the app. No amount of restarting the application seems to fix it. I found a mailing list thread reporting the same problem, but no one really answered him. What am I doing wrong?

    Read the article

  • How to save preferences to somewhere other than SharedPreferences

    - by Adrian
    My application is used on multiple platforms so it saves it preferences to a file (rather than to the standard Android SharedPreferences). Is there any easy of reusing the PreferenceActivity to save preferences to a file or is it a case of creating a whole new activity to do the job? If the latter is the case is there a layout I can use that will make the activity look like the normal preferences screen? PreferenceActivity uses com.android.internal.R.layout.preference_list_content but this doesn't appear to be available to apps for reuse.

    Read the article

  • Store in sharedPreferences

    - by klaus-vlad
    Hi, I have some things in my app that I need to store, in order to have it available the next time I open the application. I wonder if I could save them using the sharedPreferences mechanism even if I don't have any "view" associated with them ! .If this is possible please let me know, if not, what would you suggest instead ?

    Read the article

  • How do I get preferences to work in Android?

    - by Dan T
    I've really been struggling through this. New to Java/Android. I'm writing my first app and this is the first thing that has taken me longer than a couple days of searching to figure out. Here's the setup: It's a BAC calculator / drink counter: A formula is used to calculate the BAC. Here's the forumla: Bac = ((StandardDrinks / 2) * (GenderConstant / Weight)) - (0.017 * Hours); So as you can see, being able to modify the gender and weight will produce more accurate and personalized results. So I have them as doubles: double GenderConstant = 7.5; //9 for female double Weight = 180; To change these variables I would like the person to be able to go into the settings and choose different values. I have these things set up, but not linked to the variables shown above because I cannot for the life of me figure out how. Here they are: I press the menu button and this pops up. Great. I'll click Settings. Now the preferences pops up. Here is my preferences.xml: <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="Personal Settings"> <ListPreference android:title="Gender" android:summary="Verify or deny the presence of a Y chromosome." android:key="genderPref" android:defaultValue="male" android:entries="@array/genderArray" android:entryValues="@array/genderValues" /> <ListPreference android:title="Weight" android:summary="How much the planet pulls on you, in pounds." android:key="weightPref" android:defaultValue="180" android:entries="@array/weightArray" android:entryValues="@array/weightValues" /> </PreferenceCategory> <PreferenceCategory android:title="Drink Settings"> <ListPreference android:title="Beer Size" android:summary="The volume of your beer, in ounces." android:key="beerPref" android:defaultValue="12" android:entries="@array/beerArray" android:entryValues="@array/beerValues" /> <ListPreference android:title="Shot Size" android:summary="The volume of your shot, in ounces." android:key="shotPref" android:defaultValue="1.5" android:entries="@array/shotArray" android:entryValues="@array/shotValues" /> <ListPreference android:title="Wine Size" android:summary="The volume of your wine, in ounces." android:key="winePref" android:defaultValue="5" android:entries="@array/wineArray" android:entryValues="@array/wineValues" /> </PreferenceCategory> </PreferenceScreen> Onward to the weight ListPreference: And that shows up. The values are stored as string-arrays in res/values/arrays.xml. Here's a sample, of just the weight ones: <string-array name="weightArray"> <item>120 lbs</item> <item>150 lbs</item> <item>180 lbs</item> <item>210 lbs</item> <item>240 lbs</item> <item>270 lbs</item> </string-array> <string-array name="weightValues"> <item>120</item> <item>150</item> <item>180</item> <item>210</item> <item>240</item> <item>270</item> </string-array> This is basically as far as I've gotten. I can click a value, sure, but it doesn't change the formula because it's not linked with the doubles I created in DrinkingBuddy.java. All of the stuff displayed in the settings are just empty shells for now, including the spinner on the main layout (the default time is just set to 1 hour) I did create a Preferences.java and have tried implementing various combinations of code found in tutorials and resources around the web, but to no avail. Here it is anyway, filled with failed attempts to make beerPref (the settings option to change how many ounces in the beer) correlate with a variable in my main class: package com.dantoth.drinkingbuddy; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.Preference.OnPreferenceClickListener; public class Preferences extends PreferenceActivity { public static final String PREF_BEER_SIZE = "PREF_BEER_SIZE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); //Get the custom preference Preference beerPref = (Preference) findPreference("beerPref"); beerPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { SharedPreferences customSharedPreference = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = customSharedPreference.edit(); editor.commit(); return true; }} );} } A full on tutorial and sample code would be AWESOME as I've yet to find any reliable guides out there.

    Read the article

  • Using the LIMIT statement in a SQLite query

    - by anselmophil
    Hi guys. I have a query that selects rows in a ListView without having a limit. But now that i have implemented a SharedPreferences that the user can select how much rows will be displayed in the ListView, my SQLite query doesnt work. Im passing the argument this way: return wDb.query(TABELANOME, new String[] {IDTIT, TAREFATIT, SUMARIOTIT}, CONCLUIDOTIT + "=1", null, null, null, null, "LIMIT='" + limite + "'"); Help, please!

    Read the article

  • Why is my onSharedPreferenceChangeListener being called multiple times when I change a pref.

    - by brockoli
    I've written an app with 3 tabs. Each tab has the same list view with different data sources. I have setup SharedPreferences in the tabhost activity, but I put my onSharedPreferenceChangeListener method in my listactivity. When I change a preference, my listener gets called and it updates my database. This is all working. However, if I change the data in tab 1, it calls my listener once. If I change the data for tab 2 it calls it twice and if I change the data in tab 3 it calls it three times. Any idea why it works this way? I guess I could setup my shared prefs in my listactivity and that might avoid the issue, but I'm curious why my listener is called multiple times if it's in a different tab. brockoli

    Read the article

  • Android - overlay small check icon over specific image in gridview or change border

    - by oscar
    I've just asked a question about an hour ago, while waiting for replies, I've thought maybe I can achieve what I want differently. I was thinking of changing the image but it would be better if I could perhaps overlay something over the top of complete levels in the gridview i.e a small tick icon At the moment, when a level has been completed I am storing that with sharedpreferences So I have a gridView layout to display images that represent levels. Let's just say for this example I have 20 levels. When one level is complete is it possible to overlay the tick icon or somehow highlight the level image. Maybe change the border of the image?? Here are the image arrays I use int[] imageIDs = { R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four, R.drawable.five, R.drawable.six etc....... and then I have my code to set the images in gridView. Obviously there is more code in between. public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(context); imageView.setLayoutParams(new GridView.LayoutParams(140, 140)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(5, 5, 5, 5); } else { imageView = (ImageView) convertView; } imageView.setImageResource(imageIDs[position]); return imageView; would it be possible to do any of the above, even the border method would be fine. Thanks for any help

    Read the article

  • Weird exception: Cannot cast String to Boolean when using getBoolean

    - by La bla bla
    I'm getting a very weird error. I have 2 activities. On both I'm getting the SharedPreferences using MODE_PRIVATE (if it matters) by sp = getPreferences(MODE_PRIVATE); on each activity's onCreate() I'm calling sp.getBoolean(IntroActivity.SHOW_INTRO, true) On the IntroActivity this works fine. But when I'm trying in the main activity, I'm getting this 10-12 04:55:23.208: E/AndroidRuntime(11668): FATAL EXCEPTION: main 10-12 04:55:23.208: E/AndroidRuntime(11668): java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.app.SharedPreferencesImpl.getBoolean(SharedPreferencesImpl.java:242) 10-12 04:55:23.208: E/AndroidRuntime(11668): at com.lablabla.parkme.ParkMeActivity$2.onClick(ParkMeActivity.java:194) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.view.View.performClick(View.java:4084) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.view.View$PerformClick.run(View.java:16966) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Handler.handleCallback(Handler.java:615) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Handler.dispatchMessage(Handler.java:92) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Looper.loop(Looper.java:137) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.app.ActivityThread.main(ActivityThread.java:4745) 10-12 04:55:23.208: E/AndroidRuntime(11668): at java.lang.reflect.Method.invokeNative(Native Method) 10-12 04:55:23.208: E/AndroidRuntime(11668): at java.lang.reflect.Method.invoke(Method.java:511) 10-12 04:55:23.208: E/AndroidRuntime(11668): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 10-12 04:55:23.208: E/AndroidRuntime(11668): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 10-12 04:55:23.208: E/AndroidRuntime(11668): at dalvik.system.NativeStart.main(Native Method) I made sure that I'm not putting a String somewhere in the middle with that same key Any ideas? Thanks! EDIT: some code: //onCreate() sp = getPreferences(MODE_PRIVATE); // other method boolean showIntro = sp.getBoolean(IntroActivity.SHOW_INTRO, true); // Exception is here showIntroCheckBox.setChecked(showIntro); If it matters, the code which throws the exception is inside a button's onClick

    Read the article

  • Best place/area to store file for Trail period

    - by hotveryspicy
    I need to have a trial period (7 days) in my application. From this I came to know that you can do that by keeping permanent file, database or shared preference. Where do I keep that file so that the user isn't able to see/delete it. If I put that logic in Sharedpreference or a file with a path "data/data/packagename", when the application is uninstalled then all history will be lost. Any other workaround/ideas? Note: there is no server, application works locally with no Internet.

    Read the article

  • PreferenceFragment - Difference between getPreferenceManager() and getPreferenceScreen()?

    - by Zynga Liker
    I've implemented my own PreferenceFragment subclass (detailed here), and want to listen for preference changes within it. PreferenceFragment provides you with two ways of doing this: getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); and getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); Which one should be used? What's the difference? I don't really understand the distinction made in the Android docs.

    Read the article

  • Live wallpaper settings not applying

    - by Steve
    I have added settings to my live wallpaper but they are not being applied when changed. I would greatly appreciate it if someone could tell me why my settings are not being applied when changed. Here is my code: settings.xml <PreferenceCategory android:title="@string/more"> <PreferenceScreen android:title="@string/more"> <intent android:action="android.intent.action.VIEW" android:data="market://search?q=pub:PSP Demo Center" /> </PreferenceScreen> <ListPreference android:persistent="true" android:enabled="true" android:entries="@array/settings_light_number_options" android:title="@string/settings_light_number" android:key="light_power" android:summary="@string/settings_light_number_summary" android:defaultValue="3" android:entryValues="@array/settings_light_number_optionvalues" /> <ListPreference android:persistent="true" android:enabled="false" android:entries="@array/settings_speed_number_options" android:title="@string/settings_speed_number" android:key="speed" android:summary="@string/settings_speed_number_summary" android:defaultValue="10" android:entryValues="@array/settings_speed_number_optionvalues" /> <ListPreference android:persistent="true" android:enabled="false" android:entries="@array/settings_rotate_number_options" android:title="@string/settings_rotate_number" android:key="rotate" android:summary="@string/settings_rotate_number_summary" android:defaultValue="8000" android:entryValues="@array/settings_rotate_number_optionvalues" /> </PreferenceCategory> </PreferenceScreen> Settings.java public class GraffitiLWPSettings extends PreferenceActivity implements SharedPreferences .OnSharedPreferenceChangeListener { public static final String SHARED_PREFS_NAME = "wallpaper_settings"; protected void onCreate(Bundle icicle) { super.onCreate(icicle); getPreferenceManager(). setSharedPreferencesName(GraffitiLWP.SHARED_PREFS_NAME); addPreferencesFromResource(R.xml.settings); getPreferenceManager().getSharedPreferences(). registerOnSharedPreferenceChangeListener(this); } protected void onResume() { super.onResume(); } protected void onDestroy() { getPreferenceManager().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this); super.onDestroy(); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { } } wallpaper.java public class GraffitiLWP extends Wallpaper { private GraffitiLWPRenderer mRenderer; public static final String SHARED_PREFS_NAME = "wallpaper_settings"; public Engine onCreateEngine() { mRenderer = new GraffitiLWPRenderer(this); return new WallpaperEngine( this.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE), getBaseContext(), mRenderer); } } renderer.java public class GraffitiLWPRenderer extends RajawaliRenderer { private Animation3D mAnim; private BaseObject3D mCan; private SettingsUpdater settingsUpdater; //private SharedPreferences preferences; public GraffitiLWPRenderer(Context context) { super(context); setFrameRate(20); } public class SettingsUpdater implements SharedPreferences .OnSharedPreferenceChangeListener { private GraffitiLWPRenderer renderer; public SettingsUpdater(GraffitiLWPRenderer renderer) { this.renderer = renderer; } public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { preferences.getInt("wallpaper_settings", 0); renderer.setSharedPreferences(preferences); } } public void initScene() { System.gc(); ALight light = new DirectionalLight(); light.setPower(this.preferences.getLong("light_power", 3)); light.setPosition(0, 0, -10); mCamera.setPosition(0, -1, -7); mCamera.setLookAt(0, 2, 0); mCamera.setFarPlane(1000); ObjParser parser = new ObjParser(mContext .getResources(), mTextureManager, R.raw.spraycan_obj); parser.parse(); mCan = parser.getParsedObject(); mCan.addLight(light); mCan.setScale(1.2f); addChild(mCan); Number3D axis = new Number3D(0, this.preferences.getLong("speed", 10), 0); axis.normalize(); mAnim = new RotateAnimation3D(axis, 360); mAnim.setDuration(this.preferences.getLong("rotate", 8000)); mAnim.setRepeatCount(Animation3D.INFINITE); mAnim.setInterpolator(new AccelerateDecelerateInterpolator()); mAnim.setTransformable3D(mCan); setSkybox(R.drawable.posz, R.drawable.posx, R.drawable.negz, R.drawable.negx, R.drawable.posy, R.drawable.negy); } public void onSurfaceCreated(GL10 gl, EGLConfig config) { settingsUpdater = new SettingsUpdater(this); this.preferences.registerOnSharedPreferenceChangeListener( settingsUpdater); settingsUpdater.onSharedPreferenceChanged(preferences, null); super.onSurfaceCreated(gl, config); mAnim.start(); } public void onDrawFrame(GL10 glUnused) { super.onDrawFrame(glUnused); mSkybox.setRotY(mSkybox.getRotY() + .5f); } } I know the code is long but I would greatly appreciate any help that someone could give me. Thank you.

    Read the article

  • Is there a way for a user to disable an AlertDialog completely?

    - by NewGuyChris
    In the app I'm making, I have an "if" statement where if two strings are saved to a certain string, an AlertDialog pops up. These strings will stay the same for some users, thus having this AlertDialog constantly pop up whenever they launch the activity where the ALertDialog is set to appear. Code (I have no setNegativeButton as of yet): private void SetWarning() { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Warning!"); alert.setMessage(R.string.Warning); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //No action needed; just close the AlertDialog. } }); alert.show(); } Here is a segment of my code that makes this AlertDialog appear: SharedPreferences sharedPreferences = getSharedPreferences("MY_PREF", MODE_PRIVATE); String s = sharedPreferences2.getString("MEM1", ""); String s2 = sharedPreferences2.getString("MEM2", ""); if(s.equals("String1") && s2.equals("String2")) SetWarning(); Is there a way to make an "alert.setNegativeButton" method where if the user clicks it, the AlertDialog will NEVER appear again? I'm thinking of maybe somehow implementing another SavedPreferences somehow so it saves the users selection and will then prevent the AlertDialog from ever appearing again. So far, to no luck. I've searched to find nothing, other than people asking how to disable buttons in an AlertDialog. Thank you! New updated code: alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //set sharedpreferences boolean called DONTSHOWAGAIN to true; SharedPreferences sharedPreferences2 = getSharedPreferences("MY_PREF", MODE_PRIVATE); Boolean dontShowAgain = sharedPreferences2.getBoolean("dontShowAgain ", false); SharedPreferences.Editor ed = sharedPreferences2.edit(); ed.putBoolean("dontShowAgain", true); ed.commit(); } }); alert.show(); } private void StringWarning() { SharedPreferences sharedPreferences2 = getSharedPreferences("MY_PREF", MODE_PRIVATE); String s = sharedPreferences2.getString("MEM1", ""); String s2 = sharedPreferences2.getString("MEM2", ""); if(s.equals("String1") && s2.equals("String2")){ if(!dontShowAgain){ SetWarningExamConflict(); } }

    Read the article

  • How do I cast from int to generic type Integer?

    - by Rob Kent
    I'm relatively new to Java and am used to generics in C# so have struggled a bit with this code. Basically I want a generic method for getting a stored Android preference by key and this code, albeit ugly, works for a Boolean but not an Integer, when it blows up with a ClassCastException. Can anyone tell me why this is wrong and maybe help me improve the whole routine (using wildcards?)? public static <T> T getPreference(Class<T> argType, String prefKey, T defaultValue, SharedPreferences sharedPreferences) { ... try { if (argType == Boolean.class) { Boolean def = (Boolean) defaultValue; return argType.cast(sharedPreferences.getBoolean(prefKey, def)); } else if (argType == Integer.class) { Integer def = (Integer) defaultValue; return argType.cast(sharedPreferences.getInt(prefKey, def)); } else { AppGlobal.logWarning("getPreference: Unknown type '%s' for preference '%s'. Returning default value.", argType.getName(), prefKey); return defaultValue; } } catch (ClassCastException e) { AppGlobal.logError("Cast exception when reading pref %s. Using default value.", prefKey); return defaultValue; } } I've tried various ways - using the native int, casting to an Integer, but nothing works.

    Read the article

1 2 3 4  | Next Page >