Get same status of checkbox when I restart the application in android - android

I have a list view. I am getting check box when I check it.
But I want to get same status when I restart the application. If is there any way to do it please reply me.
I am really new to android.
my code is follows:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//I am getting status of check box here. If I click on file check box is appearing to me. //I want to be store always for true.
String keyword = value[position];
mediaPlayer.reset();
try
{
mediaPlayer.setDataSource("/sdcard/"+keyword+".mp4");
mediaPlayer.prepare();
mediaPlayer.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
thanks in advance.

You may use SharedPreference for your values to stay even if your application gets closed. Use a default value in your constants file.
For eg:
Create a class for storing all SharedPreferences.
In that give,
private static SharedPreferences sharedPref;
public static final String PREFERENCE_DATA = "some data";
Inside constructor give,
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
Add setter/getter methods for each preference value.
public static void setPreferenceData(String data) {
if (sharedPref != null) {
Editor editor = sharedPref.edit();
editor.putString(PREFERENCE_DATA, data);
editor.commit();
}
}
public static String getPreferenceData() {
String data = "data";
if (sharedPref != null) {
status = sharedPref.getString(PREFERENCE_DATA,your variable name stored in constants);
}
return data;
}
So when you want to set any data, use setPreferenceData and when you want to fetch value use getPreferenceData.

You need to save the state of the checkbox in the onPause method of your activity. After onPause was called the system can close your application without any further warning as described in the Activity Documentations
To save the checked items your onPause method would look something like this:
#Override
protected void onPause() {
super.onPause();
long[] checkedBoxes = getListView.getCheckedItemIds();
setPreferenceData(checkedBoxes);
}
You only have to modify Mathews Code in a way that allows you to save long Arrays.
Now you can get these values from the sharedPreferences file in the onCreate method and set the checkboxes accordingly in your Adapter code.

Related

How to implement permanent splash screen and 1 time tutorial both in one app [duplicate]

This question already has answers here:
Determine if Android app is being used for the first time
(15 answers)
Closed 6 years ago.
I am new to android development and and I want to setup some of application's attributes based on Application first run after installation. Is there any way to find that the application is running for the first time and then to setup its first run attributes?
The following is an example of using SharedPreferences to achieve a 'first run' check.
public class MyActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firstrun", false).commit();
}
}
}
When the code runs prefs.getBoolean(...) if there isn't a boolean saved in SharedPreferences with the key "firstrun" then that indicates the app has never been run (because nothing has ever saved a boolean with that key or the user has cleared the app data in order to force a 'first run' scenario). If this isn't the first run then the line prefs.edit().putBoolean("firstrun", false).commit(); will have been executed and therefore prefs.getBoolean("firstrun", true) will actually return false as it overrides the default true provided as the second parameter.
The accepted answer doesn't differentiate between a first run and subsequent upgrades. Just setting a boolean in shared preferences will only tell you if it is the first run after the app is first installed. Later if you want to upgrade your app and make some changes on the first run of that upgrade, you won't be able to use that boolean any more because shared preferences are saved across upgrades.
This method uses shared preferences to save the version code rather than a boolean.
import com.yourpackage.BuildConfig;
...
private void checkFirstRun() {
final String PREFS_NAME = "MyPrefsFile";
final String PREF_VERSION_CODE_KEY = "version_code";
final int DOESNT_EXIST = -1;
// Get current version code
int currentVersionCode = BuildConfig.VERSION_CODE;
// Get saved version code
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
int savedVersionCode = prefs.getInt(PREF_VERSION_CODE_KEY, DOESNT_EXIST);
// Check for first run or upgrade
if (currentVersionCode == savedVersionCode) {
// This is just a normal run
return;
} else if (savedVersionCode == DOESNT_EXIST) {
// TODO This is a new install (or the user cleared the shared preferences)
} else if (currentVersionCode > savedVersionCode) {
// TODO This is an upgrade
}
// Update the shared preferences with the current version code
prefs.edit().putInt(PREF_VERSION_CODE_KEY, currentVersionCode).apply();
}
You would probably call this method from onCreate in your main activity so that it is checked every time your app starts.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkFirstRun();
}
private void checkFirstRun() {
// ...
}
}
If you needed to, you could adjust the code to do specific things depending on what version the user previously had installed.
Idea came from this answer. These also helpful:
How can you get the Manifest Version number from the App's (Layout) XML variables?
User versionName value of AndroidManifest.xml in code
If you are having trouble getting the version code, see the following Q&A:
How to get the build/version number of your Android application?
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
import android.content.Context;
public class Util {
// ===========================================================
//
// ===========================================================
private static final String INSTALLATION = "INSTALLATION";
public synchronized static boolean isFirstLaunch(Context context) {
String sID = null;
boolean launchFlag = false;
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists()) {
launchFlag = true;
writeInstallationFile(installation);
}
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return launchFlag;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");// read only mode
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
> Usage (in class extending android.app.Activity)
Util.isFirstLaunch(this);
There is no way to know that through the Android API. You have to store some flag by yourself and make it persist either in a SharedPreferenceEditor or using a database.
If you want to base some licence related stuff on this flag, I suggest you use an obfuscated preference editor provided by the LVL library. It's simple and clean.
Regards,
Stephane
I'm not sure it's good way to check it. What about case when user uses button "clear data" from settings? SharedPreferences will be cleared and you catch "first run" again. And it's a problem. I guess it's better idea to use InstallReferrerReceiver.
Just check for some preference with default value indicating that it's a first run. So if you get default value, do your initialization and set this preference to different value to indicate that the app is initialized already.
The following is an example of using SharedPreferences to achieve a 'forWhat' check.
preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferencesEditor = preferences.edit();
public static boolean isFirstRun(String forWhat) {
if (preferences.getBoolean(forWhat, true)) {
preferencesEditor.putBoolean(forWhat, false).commit();
return true;
} else {
return false;
}
}
There's no reliable way to detect first run, as the shared preferences way is not always safe, the user can delete the shared preferences data from the settings!
a better way is to use the answers here Is there a unique Android device ID? to get the device's unique ID and store it somewhere in your server, so whenever the user launches the app you request the server and check if it's there in your database or it is new.
This might help you
public class FirstActivity extends Activity {
SharedPreferences sharedPreferences = null;
Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedPreferences = getSharedPreferences("com.myAppName", MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (sharedPreferences.getBoolean("firstRun", true)) {
//You can perform anything over here. This will call only first time
editor = sharedPreferences.edit();
editor.putBoolean("firstRun", false)
editor.commit();
}
}
}
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
// here you can launch another activity if you like
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference
}
}

Prevent TextViews from having to be loaded every time the activity is opened?

I'm currently parsing a web file then setting 5 textview values upon completion, however, every time the activity is closed and reopened it needs to yet again access the page parse and display the values, how can i prevent it from having to?
It should noted that the data changes quite regularly so i cant simply SAVE the values forever.
public void gatherStockDetails(String symb) {
AsyncHttpClient client = new AsyncHttpClient();
client.get("url" + symb + "&f=snpog",
new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.e("KFF-a", response);
stockinfo = response.split(",");
setTextViews(stockinfo[0].replaceAll("[^a-zA-Z0-9.%+ -]+", ""),
stockinfo[1].replaceAll("[^a-zA-Z0-9.%+ -]+", ""),
stockinfo[2].replaceAll("[^a-zA-Z0-9.%+ -]+", ""),
stockinfo[3].replaceAll("[^a-zA-Z0-9.%+ -]+", ""),
stockinfo[4].replaceAll("[^a-zA-Z0-9.%+ -]+", ""));
}
#Override
public void onFailure(Throwable arg0, String arg1) {
super.onFailure(arg0, arg1);
}
});
}
and
public void setTextViews(String Symbol, String Name, String PClose, String Open, String Low) {
final Animation in = new AlphaAnimation(0.0f, 1.0f);
in.setDuration(500);
tvName.setText(Name.replace("Corpora", "Corporation"));
tvName.startAnimation(in);
tvSymbol.setText(Symbol);
tvSymbol.startAnimation(in);
tvSymbol.setText(PClose);
tvPClose.startAnimation(in);
tvLow.setText(Low);
tvLow.startAnimation(in);
tvOpen.setText(Open);
tvOpen.startAnimation(in);
}
Sorry, i did not mention, this is in a Fragment on an activity, thus there is no onRestoreInstance state.
Maybe you should put you TextViews in a OnCreate, here is a reference picture:
This shows where the different modules are loaded, and where a good idea is to put your modules that dont always need reloading.
Picture is loaned from another stackoverflow thread, here: Difference between onCreate()and onStart()
You can use sharedPreferences. Use a boolean to denote that you don't want page to be parse again and save the textView's text that you got in it. Now everytime the activity opens, check if that boolean is true, if so, just take the values from sharedPreference and assign them to textViews.
If the boolean is false, then parse the page. Whenever you again parse the page, replace old values with new one. This way you don't have to parse the page again and again.
Maybe you can save some flag in SharedPreferences so you just validate the flag.
public void DataDownloaded()
{
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("DataDownloaded", true);
editor.commit();
}
public Boolean isDataDownloaded()
{
SharedPreferences sharedPreferences = getSharedPreferences();
return sharedPreferences.getBoolean("DataDownloaded", false);
}
and just validate in the onCreate() and the onResume() override methods.
if(!isDataDownloaded)
{
//all your cool stuff
}

EditTextPreference.setText(value) not updating as expected

I'm trying to prevent the user from entering an empty string into an EditTextPreference (in the example, catName). I use a OnPreferenceChangeListener to detect when a change is made to the EditTextPreference, and if there is a change and the string is blank, I use the EditTextPreference.setText() command to reset to the old value. However, the new value doesn't show up properly if I reopen the EditTextPreference in the GUI (the string is blank), and if I go back into the main app, I can verify that a blank value is being saved to the preferences.
I've verified that the if statement executes as expected, and that my parameter keeping track of the old name (oldCatName) is updating as expected. I can even log the catName.getText() value right before the setOnPreferenceChangeListener finishes execution and I always see the value I expect (the new value set by the user, and when they enter a blank value, it properly resets to the old value). I'm not sure why setting the value to the EditTextPreference isn't saving the value to the preferences file or updating the GUI.
public class SettingsActivity extends PreferenceActivity {
private String oldCatName;
private EditTextPreference catName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
catName = (EditTextPreference) findPreference("cat_name");
oldCatName = catName.getText();
catName.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newVal) {
final String value = (String) newVal;
if (value.equals("")) {
catName.setText(oldCatName);
Log.e("new value", catName.getText());
}
else
oldCatName = value;
return true;
}
});
}
}
Thanks for the help!
-Michael
Edit: A clarification. The logic in the if statement is executing correctly. The string value of the EditTextPreference is even updating correctly. However, the value in the GUI if the user taps on the EditTextPreference again does not correctly update, and the value in the app's shared preferences does not update correctly. It stays blank.
Finally found a solution by doing the following:
I used a SharedPreferences.OnSharedPreferenceChangeListener instead of a Preference.OnPreferenceChangeListener. The Preference.OnPreferenceChangeListener looks for when the user changes a preference through the settings menu, and behaves before the change is committed to the preference data. The SharedPreferences.OnSharedPreferenceChangeListener listens for changes to the actual preference data, not changes in the GUI, so it happens a little later. I noticed that in my first attempt, I could run setText() immediately followed by getText() on my EditTextPreference object, and the getText() value wouldn't match what I had just set the setText() value to. I'm not sure why this happens, but waiting for the changes to actually commit before trying to run setText() led to the correct response. Maybe it was a timing issue?
I run setPreferenceScreen(null) and addPreferencesFromResource(R.xml.settings) after updating the value in the EditTextPreference. If I didn't do this, sometimes when the user would click on the EditTextPreference again, the value in the field would appear blank even though the value in the settings file wasn't. This forces the settings page to, more or less, refresh itself.
The working code is below:
public class SettingsActivity extends PreferenceActivity {
private String oldCatName;
private EditTextPreference catName;
private SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
createListener();
catName = (EditTextPreference) findPreference("cat_name");
oldCatName = catName.getText();
}
private void createListener() {
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
String value = sharedPreferences.getString("cat_name", "NULL");
if (value.equals("")) {
catName.setText(oldCatName);
setPreferenceScreen(null);
addPreferencesFromResource(R.xml.settings);
} else {
oldCatName = value;
}
}
};
PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.registerOnSharedPreferenceChangeListener(listener);
}
}
~9 yrs late, Hope this helps some one else.
I too faced similar issue. It can be done simply by returning false. As the documentation states returning true will update the value and you want to ignore changes.
catName.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newVal) {
final String value = (String) newVal;
if (value.equals("")) {
catName.setText(oldCatName);
Log.e("new value", catName.getText());
return false ; // <----------------------------------
}
else
oldCatName = value;
return true;
}
});

how to store a text in one activity and retrieve it in another activity.?

I have created an app for alarm service..such that a person can set a alarm to a specific time and the alarm will pop up as a notification..Now i want to create that alarm service app to a task reminder app such a way that at the time of creating or setting the task , user input the message in the edit text and save it and then when the alarm pops up , and if the user taps the notification , a new activity comes up and the message that he typed earlier is printed in front of him..(i mean the message is show as a text view to him) So Please tell me how could i do that using shared preferences..
In simple way just tell how could a load the stored string from the activity where the string was created and save with the help of a button and to load that same string and pass it in a text view to some other activity..
You can use shared-preferences to store data in one activity. and these data will be available in any activity with in same application.
http://developer.android.com/reference/android/content/SharedPreferences.html
example is available at http://developer.android.com/guide/topics/data/data-storage.html
Good Luck.......
I would like to suggest you to do all your preference tasks in your Application Utils.clas
// Declaration
public static String KEY = "SESSION";
// Method declaration :
public static void saveUserName(String userid, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("username", userid);
editor.commit();
}
public static String getUserName(Context context) {
SharedPreferences savedSession = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedSession.getString("username", "");
}
// You can save the values in preference by calling the below :
Utils.saveUserName("12345",YourActivity.this);
// Finally you can retrieve the stored value by calling this code snippet :
String myUserName = Utils.getUserName(YourActivity.this);
Hope it helps
You can use SharedPreferences.
Using setSetting, you can set the text at caller class. Similarly, you can get the text which was set in the caller class using getSetting in the called class.
Method to set the Preference-
public void setSetting(String key, String value) {
if(getActivity() != null)
{
SharedPreferences settings = getActivity().getSharedPreferences("UserPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
// Commit the edits!
editor.commit();
}
}
Method to get the preference-
public String getSetting(String key, String def) {
try
{
SharedPreferences settings = getActivity().getSharedPreferences("UserPref", 0);
return settings.getString(key, def);
}
catch(Exception e)
{
e.printStackTrace();
}
return "";
}
Here,
public abstract SharedPreferences getSharedPreferences (String name, int mode)
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.
More on Android developer reference.

Cannot save or load Integer with Preferences

So I have constructed a class SaveAndLoad that looks like this:
public class SaveAndLoad {
public Preferences pref;
public final String path = "Highscore";
public SaveAndLoad() {
pref = Gdx.app.getPreferences("Gametitle");
}
public void saveInt(int value) {
pref.putInteger(path, value);
pref.flush();
}
public int getInt() {
return pref.getInteger(path);
}
}
When I try to save my highscore I call saveInt(highscore) and when you turn the game on again I call getInt.
constructor(){
SaveAndLoad sdRemote = new SaveAndLoad ();
try {
highscore = sdRemote.getInt();
} catch (NullPointerException e) {
highscore = 0;
}
}
The problem is that when I start the game again after a earlier game, the highscore don't load, it returns zero...
I've done the manifest permission:
Thanks
///Daniel
Ps. In the last answer I say it works on some devices, but I found out later that was not the case.
Make sure you retrieve data like this:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int silent = settings.getInt("score", 0);
And save it like this:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("score", playerScore);
// Commit the edits!
editor.commit(); //<----------
Edit:
Ah you are using GDX. In that case make sure you are initializing this class after GDX has initialized. Check if Gdx.app.getPreferences("Game"); is returning null.
Edit2:
Ok, so we have confirmed it's a problem with Gdx on certain devices (that sucks).
If you REALLY need to make this work on both Desktop and Android devices there is another way. If you just want your game to work on Android you just should't use Gdx at all for saving the data.
I suggest you use something called a GDX Android interface. This way you can handle saving data on Android devices yourself using native Android calls that I used in this answer. This isn't really easy though but there is a tutorial here:
https://code.google.com/p/libgdx-users/wiki/IntegratingAndroidNativeUiElements3TierProjectSetup
you can store and retrive data from this.
following code of class and methods.
public class SaveAndLoad {
public SharedPreferences pref;
public final String path = "Highscore";
public SaveAndLoad() {
pref = Gdx.app.getSharedPreferences("Gametitle",MODE_PRIVATE);
}
public void saveInt(int value) {
Editor edit = pref.edit();
edit.putInt(path, value);
edit.commit();
}
public int getInt() {
return pref.getInt(path,0);
}
}
for Save HighScore.
int highscore = 0;
SaveAndLoad sdRemote = new SaveAndLoad ();
try {
highscore = sdRemote.getInt();
} catch (NullPointerException e) {
e.printStackTrace();
}
for get HighScore.
int highscore = 255;
SaveAndLoad sdRemote = new SaveAndLoad ();
try {
sdRemote.saveInt(highscore);
} catch (NullPointerException e) {
e.printStackTrace();
}
this code working properly for me. and use this i'm sure its useful for you.
From the sounds of it you are doing everything correctly, which leaves the option of us testing the device in question. If you could run the following application listener on the device and see if MyValue is increasing each time you run the application on the device.
public class PrefTest implements ApplicationListener {
#Override public void create() {
final Preferences pref = Gdx.app.getPreferences("TestApp");
int value = pref.getInteger("MyValue", 0);
Gdx.app.log("MyValue", Integer.toString(value));
value++;
pref.putInteger("MyValue", value);
pref.flush();
}
#Override public void render() {}
#Override public void dispose() {}
#Override public void resize(final int width, final int height) {}
#Override public void pause() {}
#Override public void resume() {}
}
You should see value increase in the LogCat each time you launch the application. Example, install app and run, back out and launch from the icon, repeat the back out and launch. If this works, then we know the issue is something to do with your code. If this doesn't work, then we know the issue is something with LibGDX or the phone itself.

Categories

Resources