I have made an intro slider with this library . I want the slider to appear only once after the app installation. How to do this?
This is my code
public class SliderActivity extends TutorialActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addFragment(new Step.Builder().setTitle("This is header")
.setContent("This is content")
.setBackgroundColor(Color.parseColor("#3F51B5")) // int background color
.setDrawable(R.drawable.image_1) // int top drawable
.setSummary("This is summary")
.build());
addFragment(new Step.Builder().setTitle("This is header")
.setContent("This is content")
.setBackgroundColor(Color.parseColor("#FF4081")) // int background color
.setDrawable(R.drawable.image_3) // int top drawable
.setSummary("This is summary")
.build());
addFragment(new Step.Builder().setTitle("This is header")
.setContent("This is content")
.setBackgroundColor(Color.parseColor("#f816a463")) // int background color
.setDrawable(R.drawable.image_4) // int top drawable
.setSummary("This is summary")
.build());
}
#Override
public void finishTutorial() {
Intent intent = new Intent(SliderActivity.this, WelcomeActivity.class);
startActivity(intent);
}
}
I used the SharedPreferences class to accomplish this. Put this code in your welcome activity in your onCreate() method.
private SharedPreferences sharedPreferences;
sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this);
// Check if we need to display our OnboardingFragment
if (!sharedPreferences.getBoolean(
SliderActivity.COMPLETED_ONBOARDING_PREF_NAME, false)) {
startActivity(new Intent(this, SliderActivity.class));
}
Create a global variable in your SliderActivity class.
public static final String COMPLETED_ONBOARDING_PREF_NAME = "Onboarding Completed";
And place this code in your finishTutorial() method.
#Override
public void finishTutorial(){
SharedPreferences.Editor sharedPreferencesEditor =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
sharedPreferencesEditor.putBoolean(
COMPLETED_ONBOARDING_PREF_NAME, true);
sharedPreferencesEditor.apply();
finish();
}
This code stores weather or not the user has completed the tutorial in app preferences and can't be changed by the user unless they uninstall the app or clear app data. Let me know if you have any other questions.
Related
I am working on an app, so basically, when the user launches the app for the first time, activity A comes up, which asks the user for a bunch of data. Now, that I have the data, I take the user to activity B. Here, if the user kills the app completely, and relaunches it, the app reopens activity A, instead of B... Is there a way to control this behaviour? I want to be able to control what activity the app should open after a particular action by the user... Note : I am a complete newbie, so I have no idea how to do this.. I tried to ask this up on a google search, but couldn't find anything proper ig.
You can store boolean by shared preference to do that. Here your AcitivityA class. Store user provided data before user land to ActivityB.
public class ActivityA extends AppCompatActivity {
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
try {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean firsttimeLoad = prefs.getBoolean("first_time_load", true);
if (!firsttimeLoad) {
sendToB();
}
} catch (Exception e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time_load", false);
editor.commit();
//Store user data here
sendToB();
}
});
}
private void sendToB() {
Intent mainIntent = new Intent(ActivityA.this, ActivityB.class);
startActivity(mainIntent);
finish();
}}
The easiest way to use user data in all over the app. Make a separate class for storing user data and make the getter and setter to get and set the data.
public class UserSharedPrefs {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
#SuppressLint("CommitPrefEdits")
public UserSharedPrefs(Context context) {
sharedPreferences = context.getSharedPreferences("UserData", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void setIsLogin(boolean isLogin) {
editor.putBoolean("isLogin", isLogin);
editor.apply();
}
public boolean getIsLogin() {
return sharedPreferences.getBoolean("isLogin", false);
}
In Activity A makes the reference of that class and get the data and use it as your need. And send the user to desired Activity
if(userSharedPrefs.getIsLogin()){
moveToActivityB()
}
My aim is to allow users select from a list of available themes in my app and make it permanent till they wish to change it again, but i have only been able to achieve that partially. For now, when a user changes the app theme it does change and remains even after the app is minimized and resumed but when a user exits the app and reopens it, the theme goes back to default which is not what i want.
My question now is, how can i make the selected theme permanent even when a user exits the app? I have tried to search for some solutions online but haven't found any that helped me
ThemeActivity.java
public class ThemeActivity extends AppCompatActivity {
public Button blackbtn,bluebtn,pinkbtn,redbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
themeUtils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_theme);
blackbtn = findViewById(R.id.blackbutton);
bluebtn = findViewById(R.id.bluebutton);
pinkbtn = findViewById(R.id.pinkbutton);
redbtn = findViewById(R.id.redbutton);
blackbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
themeUtils.changeToTheme(ThemeActivity.this, themeUtils.BLACK);
}
});
bluebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
themeUtils.changeToTheme(ThemeActivity.this, themeUtils.BLUE);
}
});
pinkbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
themeUtils.changeToTheme(ThemeActivity.this, themeUtils.PINK);
}
});
redbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
themeUtils.changeToTheme(ThemeActivity.this, themeUtils.RED);
}
});
}
themeUtils.java
public class themeUtils {
private static int cTheme;
public final static int BLACK = 0;
public final static int BLUE = 1;
public final static int PINK = 2;
public final static int RED = 3;
public static void changeToTheme(Activity activity, int theme) {
cTheme = theme;
activity.finish();
activity.startActivity(new Intent(activity, activity.getClass()));
}
public static void onActivityCreateSetTheme(Activity activity) {
switch (cTheme)
{
default:
case BLACK:
activity.setTheme(R.style.BlackTheme);
break;
case PINK:
activity.setTheme(R.style.pink);
break;
case RED:
activity.setTheme(R.style.red);
break;
case BLUE:
activity.setTheme(R.style.BlueTheme);
break;
}
}
The simplest solution for this would be to save your selected theme in SharedPreferences. Whenever the app launches, you read the saved value from your SharedPreferences and load the appropriate theme.
To write your selected theme
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.selected_app_theme), YOUR_APP_THEME);
editor.commit();
To read the saved value
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.default_app_theme);
int appTheme = sharedPref.getInt(getString(R.string.selected_app_theme), defaultValue);
EDIT Based on comment
Whenever you change your app theme, you need to save it to SharedPreferences. So, whenever the changeToTheme method is called, after changing the theme, just save it to SharedPrefs. You could create a method which would save the theme like so
void saveThemeToSharedPrefs(int appTheme) {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("MY_APP_THEME, appTheme);
editor.commit();
}
Next time, when your app starts, you will load this value and use it to change the theme like so
int getAppTheme() {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = 0 //For Black theme. Change it to whatever you want as default
int appTheme = sharedPref.getInt("MY_APP_THEME", defaultValue);
}
//Change the theme in your starting activity
ThemeUtils.changeToTheme(activity, getAppTheme())
I am building an android app which displaying a specific pdf through https://github.com/barteksc/AndroidPdfViewer with lots of pages, and now i was just implementing a method to re-open the pdf from the last opened page of the user.
I am using SharedPreferences to store the current page, and then after reloading the app, the app will re-open the pdf where user left.
Here is my Shared Preferences method to store and retrieve the data
private void storepreferences () {
PDFView pdfView = findViewById(R.id.pdfView);
savedpage=pdfView.getCurrentPage();
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("key_name2", savedpage);
editor.apply();
}
private void getpreferences () {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
pageNumber = pref.getInt("key_name2", 0); // getting Integer
}
And then i am using onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
storepreferences();
getpreferences();
Also for a test i am displaying the
TextView txt = findViewById(R.id.textView2);
txt.setText(String.valueOf(pageNumber));
But Still i am getting the default value, What i am doing wrong can anyone tell me?
In StorePreference, First, try putting this code.
editor.commit()
and then,
editor.apply().
Finally I achieved this, I was using (storepreferences) on OnCreate before but now On I am using at BackPressed
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
storepreferences();
super.onBackPressed();
}
}
After that I am retrieving saved data on OnCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getpreferences();
}
I am using the above technique because I thought It is actually not storing my data, because When i use Toast to display the current Page, it was showing exactly the page number where user is
public void pagestorebutton (){
PDFView pdfView = findViewById(R.id.pdfView);
savedpage = pdfView.getCurrentPage();
Toast myToast = Toast.makeText(this,(String.valueOf(savedpage) ), Toast.LENGTH_SHORT);
myToast.show();
storepreferences();
}
And in onCreate i am using above function after clicking a Floating Button
FloatingActionButton fab4 = findViewById(R.id.fab4);
fab4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pagestorebutton();
}
});
Is my Method is achieving my Goal through right path, or is there something more to do??
Some help would be most thankful for. I have two activities. MainActivity and SharedPrefs. I want the app on open to look if there is some saved preferences. If not it must go to another activity which ask for some detail. Then on pressing the submit button it must save the shared preference and go to the MainActivity. But it doesn't, it just jumps back to the SharedPrefs activity. Now I don't know if my shared preference is not being saved (I thought "editor.commit" will do the job), or is there something wrong with my loop. I did change my loop around, and it is working the other way around, but I can have the whole thing wrong since I'm quite new to Android and Java. Like I said, some help will be appreciated.
Here is my MainActivity with my loop:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
boolean check = sharedPreferences.getBoolean("Check",false);
if(!check){
//Intent intent;
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent); }
else {
setContentView(R.layout.activity_main);
TextView brands = (TextView) findViewById(R.id.brands);
brands.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent brandsIntent = new Intent(MainActivity.this, brands.class);
startActivity(brandsIntent);
}
});
}
}
And here is my SharedPrefs where I try to get some info to add to the shared preferences:
public class SharedPrefs extends AppCompatActivity {
//public static Context context;
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shared_prefs);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(SharedPrefs.this,"Thanks",Toast.LENGTH_LONG).show();
Intent BackToMainIntent = new Intent(SharedPrefs.this, MainActivity.class);
startActivity(BackToMainIntent);
}
});
}
Please add "Check" key value to SharedPreferences after setting your desired values as it's always return false on MainActivity.
You may also use .apply() instead of .commit().
It doesn't look like you are saving a Boolean Check anywhere in the second activity. So in your first activity, this Boolean never exists and you are getting the default value which you have set to false. You need a preference called `Check' to be set to true in your second activity.
In your SharedPrefs Activity
Change your this piece of code
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
With
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.putBooleon (Check,true);
editor.commit();
Then It will work as you want.
Happy coding :)
I am a noob on developing android apps. I want to ask. How my PreferenceActivity want to Update without back to MainActivity and goto PreferenceActivity again. In this, i give some feature to change the Theme of PreferenceActivity. This is my PreferenceActivity:
public class SettingsPreference extends PreferenceActivity
{
SwitchPreference themeSwitch;
String myPref = "preferences";
SharedPreferences.Editor editor;
String summary;
int theme;
#Override
public void onCreate(Bundle savedInstanceState)
{
// TODO: Implement this method
final SharedPreferences.Editor editor = getSharedPreferences(myPref, MODE_PRIVATE).edit();
final SharedPreferences prefs = getSharedPreferences(myPref, MODE_PRIVATE);
final String summary = prefs.getString("stringSummary", "Default theme");
final int theme = prefs.getInt("intTheme", (android.R.style.Theme_DeviceDefault_Light));
setTheme(theme);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_preference);
themeSwitch = (SwitchPreference) findPreference("switchTheme");
themeSwitch.setSummary(summary);
if (themeSwitch != null) {
themeSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference arg0, Object isOnObject) {
boolean isThemeOn = (Boolean) isOnObject;
if (isThemeOn) {
Toast.makeText(SettingsPreference.this, "Theme Dark ON", Toast.LENGTH_SHORT).show();
editor.putString("stringSummary", "Theme Dark ON");
editor.putInt("intTheme", (android.R.style.Theme_DeviceDefault));
editor.apply();
themeSwitch.setSummary(summary);
} else {
Toast.makeText(SettingsPreference.this, "Theme Dark OFF", Toast.LENGTH_SHORT).show();
editor.putString("stringSummary", "Theme Dark OFF");
editor.putInt("intTheme", (android.R.style.Theme_DeviceDefault_Light));
editor.apply();
themeSwitch.setSummary(summary);
}
return true;
}
});
}
}
}
If you change the Activity layout you just have to restart it.
Try to add this at the end of onPreferenceChange().
if you're in API11+, call in an Activity.
this.recreate();
Otherwise, we just have to finish the activity and start it again with the same intent.
Intent intent = getIntent();
finish();
startActivity(intent);
If you have update every 20 seconds for example , This is code :
import android.os.Handler;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//update UI
}
},2000);
Put this in a function and re-call in run .