How to use SharedPreferences for splash activity to launch once - java

I want to launch splash activity only once using SharedPreference, how it could be happen. any help will be highly appreciated. Thanks
Thread thread;
MediaPlayer audio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audio = MediaPlayer.create(MainActivity.this, R.raw.iphone);
audio.start();
if (first_run == true){
thread = new Thread(){
#Override
public void run() {
try {
sleep(4000);
Intent intent = new Intent(MainActivity.this, SplashTwo.class);
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
finish();
audio.release();
}
}
};
thread.start();
}
}

try this:
Declare
public static final String MyPREFERENCES = "MyPrefs";
public static final String ID = "idKey";
SharedPreferences sharedPreferences;
Now in your onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
audio = MediaPlayer.create(MainActivity.this, R.raw.iphone);
audio.start();
String first = (sharedPreferences.getString("First", ""));
if (!first.equals("true")) {
thread = new Thread(){
#Override
public void run() {
try {
sleep(4000);
Intent intent = new Intent(MainActivity.this, SplashTwo.class);
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("First", "true");
editor.commit();
finish();
audio.release();
}
}
};
thread.start();
}
}

Instead of sharedprefrence ,i would like to suggest you to use static boolean value like - isFirstTime and set it true by default and on second activity (next to splash) set it to false. Whenever you kill app static value will become dead.Check in onCreate of Splash -
if(!isFirstTime){
goToNextActivity();
}else{
//continue splash code
}
If you want to use shared preference then use same Logic ,take a boolean value and save it in shared pref -
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
and in next activity simply set it to false or clear value. by calling editor.clear(); and put a check in splash if shared pref has some value or have isFirstTime and do next code accordingly.

Related

How to save the value of the number of touches in a button Android Studio

I want to save the number value so that when close the app it continues to be saved and when open it the progress is maintained. I don't know why SharedPreferences don't work.
I have tried in many ways but either the app forces it to close or it just doesn't work
number = numero
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView contador;
int numero = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("valor", numero);
int data = mPrefs.getInt("valor", numero);
contador = findViewById(R.id.contador);
}
public void onClick(View v) {
numero++;
contador.setText(String.valueOf(numero));
SharedPreferences.Editor data = data.edit();
data.putInt("tag", numero).commit();
}
};
You should use the same sharedPreferences for retrieving the values.
also, get the values by the same key you saved them. below is an example you can follow.
SharedPreferences mPrefs = getSharedPreferences("valor",
Context.MODE_PRIVATE);
try{
int data = mPrefs.getInt("tag", numero);
}
catch(NullPointerException e){
e.printStackTrace()
}
public void onClick(View v) {
numero++;
contador.setText(String.valueOf(numero));
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt("tag", numero).commit();
}
};

Android using shared preferences to check on first run

Hi I'm trying to detect whether my app has been opened for the first time. If it has, I need to run an activity and once it's opened for the second time it should not show it again.
This is my code:
fragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
//startActivity(intent);
SharedPreferences settings = this.getActivity().getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", true); // Is it first run? If not specified, use "true"
if(firstRun) {
Log.w("onCreate: ","first time" );
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.apply(); // Save all changed settings
} else {
Log.w("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
getSpecials();
}
But all it does is start the activity and when I start it again it freezes in a white screen but checking the logs it shows like the else statement is constantly running over and over. I'm fairly new to Android so some help or advice would be greatly appreciated
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences pref = YourActivityName.this.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor= pref.edit();
boolean firstRun = pref.getBoolean("firstRun", true);
if(firstRun)
{
Log.i("onCreate: ","first time" );
editor.putBoolean("firstRun",false);
editor.commit();
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
}
else
{
Log.i("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
// getSpecials();
}
It looks like your activity is looping because within your else statement, you tell it to restart the activity which lands again in the else statement and so on and so on.
Try using editor.commit if editor.apply not working
editor.putBoolean("firstRun", false);
editor.apply(); // Save all changed settings
editor.commit(); // Save all changed settings
In else case your starting "MainActivity.class".
Why your loading MainActivity from the oncreate of MainActivity ?
it will make a loop.
Remove the start activity from else case.
Try this approach:
public class MainActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstRun", true)) {
Intent intent = new Intent(MainActivity.this, TutorialFeaturedActivity.class);
startActivity(intent);
prefs.edit().putBoolean("firstRun", false).commit();
}
else
{
//do nothing
}
getSpecials();
}
}
Please Try this my friend
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "ManageRun";
private static final String KEY_IS_RUN = "isRun";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLatest(boolean isRun) {
editor.putBoolean(KEY_IS_RUN, isRun);
// commit changes
editor.commit();
Log.d(TAG, "Manage Version session modified!");
}
public boolean isLatest() {
return pref.getBoolean(KEY_IS_RUN, true);
}
}
**In first Activity Check **
private SessionManager session;
session = new SessionManager(getApplicationContext());
if (session.isLatest()) {
session.setLatest(false);
Log.w("onCreate: ","first time" );
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
}
else
{
Log.w("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
private boolean isFirstTime() {
if (firstTime == null) {
SharedPreferences mPreferences = this.getSharedPreferences("first_time", Context.MODE_PRIVATE);
firstTime = mPreferences.getBoolean("firstTime", true);
if (firstTime) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean("firstTime", false);
editor.commit();
}
}
return firstTime;
}
if (isFirstTime()) {
Intent i = new Intent(SplashActivity.this, Intro_slider.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} else {
final UserFunctions uf = new UserFunctions();
if (uf.isUserLoggedIn(SplashActivity.this)) {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} else {
Intent i = new Intent(SplashActivity.this, Social_Login_Activity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
Try this code.

How to skip second activity after first run forever?

I am working on one app which contain SplashScreen.java my first activity. After that its show LoginActivity.java for login. And my LoginActivity.java class eventually start SplashActivity.java. I want after login first time everytime i start my app SplashScreen.java calls SplashActivity.java instead of LoginActivity.java. For this i made some changes in my SplashScreen.java class but its not working fine.
SplashScreen.java Class-
public class SplashScreen extends Activity
{
private long splashDelay = 5000; //5 seconds
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false))
{
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}
else
{
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent mainIntent = new Intent().setClass(SplashScreen.this, LoginActivity.class);
startActivity(mainIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
Anyone else help me. Now the only problem after first run. App start from SplashActivity instead of starting from SplashScreen.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
Boolean Exist=pref.getBoolean("activity_executed", false);// Check is user logged in or not
if(Exist)// if allready logged in then forward it to Splash Activity
{
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}
else // Not logged in
{
Handler handler = new Handler();
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 2000L);
}
Runnable runnable = new Runnable() {
public void run() {
new AsyncParsing().execute();
}
};
private class AsyncParsing extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
Log.d("Splash Activity", "In pre execute");
}
#Override
protected Void doInBackground(Void... params) {
Log.d("Splash Activity", "In do in backgriund ");
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.d("Splash Activity", "In post execute");
Intent intent = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
}
Step 1 : Declare this in ur login class
SharedPreferences pref;
SharedPreferences.Editor editor;
Step 2 :Declare In onCrete method
pref = getSharedPreferences("login", MODE_PRIVATE);
editor = pref.edit();
Step 3 : OnClick of submit button in login page paste the lines below
:
String check=pref.getString("selected", "nil")
if(check.equals("TRUE"))
{
Intent intent=new Intent(this,splash.class);
startActivity(intent);
}
Step 4: put this where u r getting the success message when user credentails and db credentials matches.
editor.putString("selected", "TRUE");
editor.commit();
#John check and just refer this working code, i hope,it help u,
setContentView(R.layout.main);
pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Log.v("","onCreate is calling");
if(pref.getBoolean("activity_executed", false))
{
Log.v("","Before if called");
setContentView(R.layout.menu_frame);
Log.v("","after if called");
new Handler().postDelayed(csRunnable1, 3000);
}
else
{
new Handler().postDelayed(csRunnable2, 3000);
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
}
Runnable csRunnable1=new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(SplashScreen.this, SplashActivity.class);
startActivity(intent);
finish();
}
};
Runnable csRunnable2=new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(intent);
finish();
}
};
I would think you have a logic problem there. Should be if not executed, run it and mark as executed.
if(!pref.getBoolean("activity_executed", false)) {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}
The problem is that calling finish does not stop the rest of onCreate from being executed. You need to put a return statement after:
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
You missing I hope It will solve your problem
public class SplashScreen extends Activity
{private long splashDelay = 5000; // 5 seconds
/** Called when the activity is first created. */
TimerTask task = new TimerTask() {
#Override
public void run() {
finish();
Intent mainIntent = new Intent().setClass(Test.this,
LoginActivity.class);
startActivity(mainIntent);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF",
Context.MODE_PRIVATE);
if (pref.getBoolean("activity_executed", false)) {
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
} else {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
}
// try this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false))
{
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}
else
{
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
#Override
public void run() {
timer.cancel();
Intent mainIntent = new Intent().setClass(SplashScreen.this, LoginActivity.class);
startActivity(mainIntent);
finish();
}
};
timer.schedule(task, splashDelay);
}
}

Open tutorial on first run doesn't work properly

I have a tutorial in my app showing up when a user runs it for the first time
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
if (firstRun == true) {
Intent tut = new Intent(MainActivity.this, Tutorial.class);
startActivity(tut);
firstRun = false;
}
}
}, 200);
I have delayed it because without a delay i just get a black screen (the interface doesn't have the time to load)
But doing so i get the Tutorial.class opened many times, what am i doing wrong?
EDIT:
Here is some more code, i won't paste all of it since it would be only too long to read and it wouldn't be relevant to the problem
I save my preferences like this
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Counter1", counter);
editor.putInt("Counter2", counter2);
editor.putBoolean("FirstRun", firstRun);
editor.putString("Label1", label1S);
editor.putString("Label2", label2S);
editor.commit();
}
protected void onPause(){
super.onPause();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Counter1", counter);
editor.putInt("Counter2", counter2);
editor.commit();
}
Here is how i restore them inside the onCreate();
// Restore previous settings and data
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int counterRestored = settings.getInt("Counter1", 0);
int counter2Restored = settings.getInt("Counter2", 0);
boolean firstRunRestored = settings.getBoolean("FirstRun", true);
String label1Restored = settings.getString("Label1", "Counter 1");
String label2Restored = settings.getString("Label2", "Counter 2");
counter = counterRestored;
counter2 = counter2Restored;
firstRun = firstRunRestored;
label1S = label1Restored;
label2S = label2Restored;
renameLabel();
calculateTotal();
This is my second activity Tutorial.class
public class Tutorial extends MainActivity{
ImageButton btnSkip, btnSkip2, btnNext, btnNext2;
RelativeLayout tutorial, tutPage1, tutPage2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial);
btnSkip = (ImageButton) findViewById(R.id.btn_skip);
btnNext = (ImageButton) findViewById(R.id.btn_next);
btnSkip2 = (ImageButton) findViewById(R.id.btn_skip2);
btnNext2 = (ImageButton) findViewById(R.id.btn_next2);
tutorial = (RelativeLayout) findViewById(R.id.tutorial);
tutPage1 = (RelativeLayout) findViewById(R.id.page1);
tutPage2 = (RelativeLayout) findViewById(R.id.page2);
btnSkip.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
btnSkip2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
btnNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
tutPage1.setVisibility(View.GONE);
tutPage2.setVisibility(View.VISIBLE);
}
});
btnNext2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
tutPage1.setVisibility(View.VISIBLE);
tutPage2.setVisibility(View.GONE);
tutorial.setVisibility(View.VISIBLE);
finish();
}
});
}
}
why don't you try
if(firstRun){
firstRun = false;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent tut = new Intent(MainActivity.this, Tutorial.class);
startActivity(tut);
}
}
}, 200);
}
The value of firstRun will not be stored persistantly over several runs.
You should store this value in SharedPreferences so that it will retain its value even after the app has been closed. You can find a tutorial on how to use SharedPreferences here.

Android - Disabling sound on start up screen

I have a splash screen for my application that plays an mp3 clip on start up.
I want to give the user the option to disable/enable sound via a settings menu of my app. How can I implement this so that application remembers the user's preference every time they open the app.
Please see my code below for the sound.
public class Splash extends SherlockActivity {
SoundPool sp;
int explosion = 0;
MediaPlayer mp;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.splash);
sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
explosion = sp.load(this, R.raw.soundfile, 1);
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
if (explosion != 0)
sp.play(explosion, 1, 1, 0, 0, 1);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openMenu = new Intent(
"ttj.android.t3w.STARTINGPOINT");
startActivity(openMenu);
}
}
};
timer.start();
}
Use SharedPreferences to store and retrieve it: http://developer.android.com/reference/android/content/SharedPreferences.html
Example: http://developer.android.com/guide/topics/data/data-storage.html#pref
public static final String PREFS_NAME = "MyPrefsFile";
//retrieve
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
//use silent
//store
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
editor.commit();

Categories

Resources