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();
Related
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();
}
};
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.
In my application I have 2 buttons.
The first button in start game and the second button in continue game.
I want to disable my second button for the first time when my application runs.
It means just for the first time my second button is disabled to onClick. How to handle this?
How can I make it understand it is the first time?
public class Menu extends Activity implements View.OnClickListener {
SharedPreferences prefs;
Editor edit;
TextView best;
private boolean flag;
public static ImageView btn1, conti, but3, but4;
static Noti_Queue noti_queue;
static Splash splash;
public static AppList applist;
public static int userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.home_activity);
flag = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("flag", false);
if (applist == null) {
applist = new AppList(this);
applist.set_identity("1");
}
if (splash == null) {
splash = new Splash(this);
splash.set_identity("1");
}
if (noti_queue == null) {
noti_queue = new Noti_Queue(this);
noti_queue.set_identity("1");
}
btn1 = (ImageView) findViewById(R.id.button1);
conti = (ImageView) findViewById(R.id.btn2);
but3 = (ImageView) findViewById(R.id.button3);
but4 = (ImageView) findViewById(R.id.button4);
btn1.setOnClickListener(this);
conti.setOnClickListener(this);
conti.setBackgroundResource(R.drawable.cont);
if (!flag) {
flag = true;
conti.setBackgroundResource(R.drawable.cont_press);}
conti.setEnabled(flag);
but3.setOnClickListener(this);
but4.setOnClickListener(this);
// giving question id
final int que_id = getIntent().getIntExtra("integer", 0);
Log.e("mhs", que_id + "");
//now lets save the que_id(now it is save to SharedPreferences
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
userId = myPrefs.getInt("userId", 0);
//let get it to show
Log.e("saved", que_id + "");
setsize();
best = (TextView) findViewById(R.id.textView1);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
best.setTypeface(tf, Typeface.BOLD);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
edit = prefs.edit();
if (prefs.getInt("Best", 0) <= 0) {
edit.putInt("Best", 0);
edit.commit();
}
best.setText("بیشترین امتیاز : " + prefs.getInt("Best", 0));
}
#Override
public void onBackPressed() {
splash.Display();
splash = null;
super.onBackPressed();
}
#Override
protected void onResume() {
best.setText("بیشترین امتیاز : " + prefs.getInt("Best", 0));
super.onResume();
}
private void setsize() {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int h = dm.heightPixels;
int w = dm.widthPixels;
h = h / 6;
w = w - ((w * 30) / 100);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(w, h);
but4.setLayoutParams(params);
but3.setLayoutParams(params);
btn1.setLayoutParams(params);
conti.setLayoutParams(params);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
if (!flag) {
flag = true;
PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("flag", flag).commit();
conti.setEnabled(flag);
conti.setBackgroundResource(R.drawable.cont_press);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
//finishing this activity is important to exit from app
Menu.this.finish();
}
break;
case R.id.btn2:
Toast.makeText(getApplicationContext(), userId + "", Toast.LENGTH_LONG).show();
Intent intent1 = new Intent(Menu.this, ContinueActivity.class);
intent1.putExtra("integer2", userId);
startActivity(intent1);
Menu.this.finish();
break;
case R.id.button3:
Toast.makeText(getApplicationContext(), "help", Toast.LENGTH_LONG).show();
break;
case R.id.button4:
applist.Display();
break;
}
}
With the help of sharedprefrence you can achieve this for example.
SharedPreferences sharedPreferences = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("enableButton", true);
editor.commit();
put this code for enabling Button.
SharedPreferences sharedPreferences = getSharedPreferences("myPref", MODE_PRIVATE);
flag = sharedPreferences.getBoolean("enableButton", false);
if (flag) {
conti.setEnabled(true); ;
}
Trying to display simple edit text dialog, requesting a string be provided before the rest of my application starts. Currently im trying to make it so the APIKEY of my app is request first thing, then once entered its saved a shared preference and then the dialog will not display. The current code is being reused from a old project of mine. If anybody can help point me in the right direct to making this simple dialog.
public void getapikey() {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
LayoutInflater adbInflater = LayoutInflater.from(this);
View eulaLayout = adbInflater.inflate(R.layout.custom_dialog, null);
editText = (EditText) eulaLayout.findViewById(R.id.editText1);
adb.setView(eulaLayout);
adb.setTitle("Api Key");
adb.setMessage("Welcome to the app, Please input your APIkey below");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
// CheckBox Confirm for Alert Dialog
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString();
if (editText !=null)
//Unsure about this part above and below
editText = "0"
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("apikey", value);
// Commit the edits!
editor.commit();
return;
}
});
// Preferences For Alert Dialog
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String apikey = settings.getString("apikey", "0");
if (apikey!=null )
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}
}
RECOMMENDED CHANGES
public class Welcome extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
public EditText editText;
public String value;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getapikey();
}
public void getapikey() {
// Alert Dialog
AlertDialog.Builder adb = new AlertDialog.Builder(this);
LayoutInflater adbInflater = LayoutInflater.from(this);
View eulaLayout = adbInflater.inflate(R.layout.custom_dialog, null);
// dontShowAgain = (CheckBox) eulaLayout.findViewById(R.id.checkBox1);
editText = (EditText) eulaLayout.findViewById(R.id.editText1);
adb.setView(eulaLayout);
adb.setTitle("Api Key");
adb.setMessage("Welcome to the app, Please input your APIkey below");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//String checkBoxResult = "NOT checked";
String value = editText.getText().toString();
// if (dontShowAgain.isChecked())
// checkBoxResult = "checked";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//editor.putString("skipMessage", checkBoxResult);
editor.putString("apikey", value);
// Commit the edits!
editor.commit();
return;
}
});
// Preferences For Alert Dialog
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//String skipMessage = settings.getString("skipMessage", "NOT checked");
String apikey = settings.getString("apikey", value);
if(!value.equals(""))
adb.setIcon(R.drawable.ic_launcher);
adb.show();
setContentView(R.layout.splash_screen);
Thread splashThread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// changed from 5000 to 4000 11.29
while (waited < 3000) {
sleep(100);
waited += 100;
}
} catch (InterruptedException e) {
// do nothing
} finally {
Intent i = new Intent();
i.setClassName("com.example.app",
"com.example.app.CardsTesting");
startActivity(i);
finish();
}
}
};
splashThread.start();
}
}
Still doesnt save the preference after the first time then never displays
//try this one i think it may be work
SharedPreferences settings = PreferenceManager.getSharedPreferences(PREFS_NAME, 0);
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.