I'm trying to set up a dialog that will popup after the users updates or installs the application for the first time. I can't figure out how to exactly do this. Currently I have tried to use the package manager to get the users version and compare it to see if its the most recent. I'm uncertain if this will work as its hard to test for something that relies on a package update. Here is my code:
public void firstrun() {
String version = "";
String currenver = "3.9";
// update function
try {
PackageInfo manager = getPackageManager().getPackageInfo(
getPackageName(), 0);
version = manager.versionName;
} catch (NameNotFoundException e) {
// Handle exception
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString(version, version).commit();
boolean firstrun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("firstrun", true);
if (version.matches(currenver)) {
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("firstrun", false).commit();
} else {
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("firstrun", true).commit();
}
if (firstrun == true) {
new AlertDialog.Builder(this)
.setTitle("Welcome!")
.setIcon(R.drawable.icondialog)
.setMessage("UpdateText")
.setNeutralButton("OK", null).show();
}
}
I think you are on the right track, there are many solutions here and here that may give you ideas.
In addition you could create a database table that contains a flag to prompt or not. By default it would be set to a value to prompt, and then once the user launches and acknowledges the dialog you could change the flag. Then in your onUpgrade() method of your SQLiteOpenHelper you could flip the flag again, and thus your application would prompt on installation of a new version.
Related
I am currently developing an app that requires the data to be fetched from server and stored in my local data base.To ensure that the piece of code runs only once I am doing the following thing.
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean dialogShown = settings.getBoolean("dialogShown", false);
if (!dialogShown) {
//Asyntask executed here
if (haveNetworkConnection()) {
new xyz().execute();
} else {
Toast.makeText(getApplicationContext(), "Sorry... No Internet Connection", Toast.LENGTH_LONG).show();
}
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("dialogShown", true);
editor.apply();
}
Above I am setting the shared preference so that it gets executed only once.Now the Problem is in case if there is no internet connection the shared preference will be executed and the data will not be loaded how can I overcome this situation.Any help Appreciated
Now the Problem is in case if there is no internet connection the
shared preference will be executed and the data will not be loaded how
can I overcome this situation.
Instead of updating value when dialogShown is false, update value in SharedPreferences when Network connection is available otherwise make it false:
if (haveNetworkConnection()) {
new xyz().execute();
// update value in SharedPreferences for dialogShown to true
} else {
// update value in SharedPreferences for dialogShown to false
}
Or use onPostExecute method of xyz class for updating flag value when all operation is successful
You can check for the network connection first.
if (haveConnection()){
if(!dialogShown){
new xyz().execute
dialogShown = true;
}else
//already done
}
}
The above code should check for a connection first then check for a dialogShown variable being false. The con of this approach is the constant pinging of the connection to check if it exists. Depending on how you are using the enclosing method this might cause a design decision review. You can always use onPostExecution() instead.
I'm developing a mobile app using ApacheCordova/Phonegap.
I need a function that sends a SMS to me once per install. If I put my function on "DeviceReady" it will be run each time the app opens.
Is there any solution for a function to be run when app is installed OR when it runs for first time?
Any suggestion would be appreciated.
Check if it is the first time with a method and then perform the action if that method determines that it is the first time.
Ex:
isFirstTime() Method
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
// Send the SMS
}
return ranBefore;
}
You may want to add it to your onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topLevelLayout = findViewById(R.id.top_layout);
if (isFirstTime()) {
topLevelLayout.setVisibility(View.INVISIBLE);
}
I added a field to the localstorage and on startup just check if that field exists. So something like this:
if (window.localStorage.getItem("installed") == undefined) {
/* run function */
window.localStorage.setItem("installed", true);
}
Edit: The reason I prefer this over the other methods is that this works on iOS, WP, etc as well, and not only on android
This should be what u are searching for:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false))
{
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Use some boolean value if its true don't call that function other wise call that function example is here
if(smssent!=true)
{
//call sms sending method
}
else
{
//just leave blank or else notify user using some toast message
}
Note:-the boolean value store in some database like sharedprefernce or sqllite, files....
This code seems to work fine on everything except when I emulate it on Froyo. I don't have an actual device running Froyo, so I can't test it on an actual device, but it FC's when it get's to the commit. I even have the code in a try block, so I would think that it should catch an exception instead of force closing.
private void getPrefs() {
boolean dockRespond;
boolean carDockRespond;
boolean silenceRinger;
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
dockRespond = prefs.getBoolean("dockRespond", true);
carDockRespond = prefs.getBoolean("carDockRespond", true);
silenceRinger = prefs.getBoolean("silenceRinger", false);
Intent startDock = new Intent(this, DockService.class);
if(dockRespond)
{
//start dock listener service
startService(startDock);
}
else
{
//stop dock listener service
stopService(startDock);
}
try
{
editor.putBoolean(DOCKRESPONSEGLOBAL, dockRespond);
editor.putBoolean(CARDOCKRESPONSEGLOBAL, carDockRespond);
editor.putBoolean(SILENCERINGER, silenceRinger);
editor.commit();
}
catch (Exception e)
{
Log.d("Exception caught: ", e.getMessage());
}
}
All of the constants (in all caps) are defined above in the constants area, and as I said before, the code seems to work on any OS version except Froyo. In froyo it FC's on the "editor.commit();" line.
Any suggestions?
I dont see anywhere in your code where you define what editor is? The first line of code that has editor in it is
editor = settings.edit();
but you never define what 'editor' is
I figured it out. What was happening was that I was putting myself into an endless loop. I had to:
settings.unregisterOnSharedPreferenceChangeListener(prefsListener);
make my changes, then
settings.registerOnSharedPreferenceChangeListener(prefsListener);
Not sure why that only created an issue in Froyo. Google must have made a change in the OS to prevent this in future versions.
Okay, check this source code:
public void checkSession() {
SharedPreferences session = getSharedPreferences(PREFS_NAME, 1);
String getSession = session.getString("SESSION", null);
Toast.makeText(this, getSession, Toast.LENGTH_SHORT).show();
if(getSession.length() > 30) {
Intent menu = new Intent(this, menu.class);
startActivity(menu);
finish();
}
else
{
}
}
The problem is that "first time users" get crush.
When I disable the function, run the app and login the code creates session. After that when I logout, and restart the app - there's no problem. Any ideas?
First time the app runs and you don't have a value stored in the SharedPreference "SESSION" you return null as your default value. The getSession().length will then result in a NullPointerException.
You should do like this instead:
String getSession = session.getString("SESSION", "");
If getSession is null, I think Toast.makeText will fall over.* You might want to change the default return to "" from null. getSession.length() won't work if getSession is null either.
*Apparently that isn't true -- see TofferJ's comment.
My app copies files over from res/raw to the sdcard on first run. I want it to update those files on every subsequent app update. How can i have it reset the firstrun preference to true on every app update?
Here is the relevant code:
/**
* get if this is the first run
*
* #return returns true, if this is the first run
*/
public boolean getFirstRun() {
return mPrefs.getBoolean("firstRun", true);
}
/**
* store the first run
*/
public void setRunned() {
SharedPreferences.Editor edit = mPrefs.edit();
edit.putBoolean("firstRun", false);
edit.commit();
}
SharedPreferences mPrefs;
/**
* setting up preferences storage
*/
public void firstRunPreferences() {
Context mContext = this.getApplicationContext();
mPrefs = mContext.getSharedPreferences("myAppPrefs", 0); //0 = mode private. only this app can read these preferences
}
public void setStatus(String statustext) {
SharedPreferences.Editor edit = mPrefs.edit();
edit.putString("status", statustext);
edit.commit();
}
}
In my app, I save in my shared preferences the version code of the app. At every startup, I check to see if the saved version code is lower than my current version code. If it is, I show a "what's new" dialog.
Give this code a whirl - I use it in my main activity's onCreate:
PackageInfo pInfo;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
if ( prefs.getLong( "lastRunVersionCode", 0) < pInfo.versionCode ) {
// TODO: Handle your first-run situation here
Editor editor = prefs.edit();
editor.putLong("lastRunVersionCode", pInfo.versionCode);
editor.commit();
}
} catch (NameNotFoundException e) {
// TODO Something pretty serious went wrong if you got here...
e.printStackTrace();
}
prefs is a private SharedPreferences object. This works if it's truly the first run, and for upgrades. At the end of the first-run code, the editor.putLong updates your shared preferences with the current version code of your app so the next run doesn't trigger your first-run code.
This also benefits from the fact that your version code must increase for the app to be seen as an upgrade by the market, so you don't need to remember to change a separate value to detect the first-run.
You could mimic what's done on the database side, with version numbers. Instead of having just a firstRun variable, have a couple with firstRun and versionNumber, and put a static version number field in your app, that you increment at each release. This way, you'll be able to check if the app has been updated, and do your operation on each update.
I'm create class for this; download in https://gist.github.com/2509913
Example Use:
long versionInstalled = App.getVersionInstalled(this);
long current_v = App.getVersion(this);
if( versionInstalled != current_v ){
Log.w("TAG", "Veresion not valid");
}
Run this in the MainActivity's OnCreate
public void onUpdateFirstRun () {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
PackageInfo pInfo;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
Log.d("VersionCode", pInfo.versionCode + " ");
if (prefs.getLong(LAST_RUN_VERSION_CODE_KEY, 0) < pInfo.versionCode) {
if (!isInitializedInSP(KEY)) {
editor.putString(KEY, "");
}
//Finalize and Save
editor.putLong(LAST_RUN_VERSION_CODE_KEY, pInfo.versionCode);
editor.apply();
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
Use method to check if you had already initialized it in previous version
public static boolean isInitializedInSP (String key) {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContex());
Object o = mPrefs.getAll().get(key);
if (o != null) {
return true;
}
else {
return false;
}
}