how to show one time toast messages in android studio - java

I wanted to add a `toast message` when clicked on a button and I added it. Now I want show it only **one time**, that means the toast message will **not show again** if clicked on the button after the first time **also after a restart of app**.
Please help me!

You can do it with SharedPreferences that you store in another class like Utility.java:
public class Utility {
public static SharedPreferences preferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
public static Boolean hasSendToast(Context context) {
return preferences(context).getBoolean("Toast", false);
}
public static void setSendToast(Context context, Boolean bool) {
preferences(context).edit()
.putBoolean("Toast", bool).apply();
}
}
And use it with your Toast inside the onClickListener in your MainActivity.java like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(v -> {
if (!Utility.hasSendToast(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "My Toast", Toast.LENGTH_SHORT)
.show();
Utility.setSendToast(getApplicationContext(), true);
}
});
}
}

You might want to look into https://developer.android.com/training/data-storage/shared-preferences. After the first click write a boolean into shared preferences to indicate the first click has happened. Next time the user clicks the button make sure to check if that boolean has been set and don't show the toast if that's the case.

You can use a boolean flag and store the value using Shared Preference.
btn.onClickListener {
if(!getToastShownStatusFromSharedPreference()) {
showToast()
changeToastShowsStatusToSharedPreference()
}
/* other operations */
}

Yes you can do that with SharedPreferences which is a pref manager in android. You can follow the below process:
Declare a boolean as like isFirstTime = true.
On the click of the button check boolean status, and if its true then fire the toast message and make isFirstTime = false.
That's it.

Related

How to make users come back to a particular activity after they kill the app

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()
}

How to make radio buttons display a text in another activity when clicked in android studio?

I have 6 options that the user can select from and a button that takes them to the next page when clicked. I have two pages like this. After one choice from each page is selected, I would like to display certain text depending on the radio buttons clicked previously, in another activity. How can I do this in java in android studio?
If you are controlling the FragmentManager you can just pass the options as an argument to the next Fragment's constructor otherwise, you can save everything in a static variable (as long as no Views are in there, so don't store the radio buttons there) and access that variable from outside.
Like this:
public class MyFragment {
public static boolean isRadioButtonXPressed = false; //change to true if it's pressed by default
public void onCreate(...) {
radioButtonX.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
isRadioButtonXPressed = checked;
}
});
}
}
//from the other fragment
public class MyFragment2 {
public void onCreateView(...) {
if (MyFragment.isRadioButtonXPressed) {
//it's been pressed
} else {
//it's not been pressed
}
}
}
There are many different ways.
As you are using activity, you can use Intent to pass data. Here is a sample:
Intent page = new Intent(FirstActivity.this, SecondActivity.class);
page.putExtra("key", "This is my text");
startActivity(page);
For getting the value on Second Activity onCreate() method:
String value = getIntent().getStringExtra("key");

Saving Edittext and making it stay on EditText

I have an app where I take the Name of the user in an editText and I have it storing to firebase but when I get out of the activity and go back into it, the editText field does not show the Name of the user anymore. I want their name to stay in the editText field.
also how would I do the same thing but for an image in an ImageView that the user puts in. Please help.
IDEA:
You can use shared preference. When user launches his application first task will be load his user name and password from shared preference.
By doing this you can also manage a session manager for better user experience.
For example: After every successful authentication you can store the basic information of the user that is needed to update the screen everytime.
Benefit:
This will help you to show old data on screen if user launches your app without internet enabled. You can check the internet and if disabled then simply show the old data from preference.
You Can do something like this
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
text.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
{
prefs.edit().putString("autoSave", s.toString()).commit();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
//At here you can call some method to get the text from shared preferences and display it on EDitText
}
or You can save into DB at onTextChanged() method
Here is a little activity example which saves the username into SharedPreferences at stop of activity and restores the value to the EditText when activity is (re)started:
public class Test extends Activity {
EditText edtUser;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
edtUser = (EditText) findViewById(R.id.editTextUser);
edtUser.setText(preferences.getString("username", ""));
}
#Override
protected void onStop() {
super.onStop();
preferences.edit().putString("username", edtUser.getText().toString()).commit();
}
}
Set on click listener to edit text.
Inside on click enable edit text and write to firebase using setValue.
Set on click to parent layout or check is focus changed of edit text. Inside read from firebase using add value event listener.
In Oncreate disable edit text and read from firebase using add value event listener.
This will auto save and retrieve edit text data seamlessly.
In OnCreate create method of activity
//Initialize edittext
mEditText = (EditText) findViewById(R.id.edittext);
// Disable mEditText
mEditText.setEnabled(false);
//Read from firebase and set text to mEditText if mTextEdit is not in focus
if (!mEditText.isFocused()){
mFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String editTextData = (String) dataSnapshot.getValue();
mEditText.setText(editTextData);
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
// Set onclick listener to mEditText
mEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mEditText.setEnabled(true);
editTextData = mEditText.getText().toString();
mFirebaseRef.setValue(editTextData);
}
});
This works for me and UI looks simple without any extra buttons to switch between edit and save.
Hope I understood your requirement correctly. Thanks

stopping toast android in other actvity

my problem is this:
I make a toast "welcome" in the Activity Main for the first time that you open the home, and it's ok,but when another page to return to the home via the back button, how can I make the toast "welcome" does not appear anymore?
the code of main activity is:
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
MyActivity actvi1;
int cont=0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnabout=(Button)findViewById(R.id.about);
//click
btnabout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// definisco l'intenzione di aprire l'Activity "aboutme.java"
Intent aboutmejava= new Intent(MyActivity.this,aboutme.class);
startActivity(aboutmejava);
}
}
);
//toast
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
code of aboutme.java
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutme);
Button btnback=(Button)findViewById(R.id.scritta);
btnback.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent main = new Intent(aboutme.this,MyActivity.class);
startActivity(main);
If you want it to only show the very first time the application runs, put a boolean flag in SharedPreferences and check here. There are tons of examples but here is one
If you want it to show *every time the Activity is first run when the app starts, simply replace your onClick() code with onBackPressed(). This way it won't start a new instance of your MyActivity and since the Toast code is in onCreate() and not onResume(), it won't run when you go back by clicking the back button.
SharedPreferences
This works.
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
int show = sp.getInt("firstlaunch", 0);
if(show == 0) {
Toast.makeText(getApplicationContext(), "WELCOME", Toast.LENGTH_LONG).show();
sp.edit().putInt("firstlaunch", 1).apply();
}
Place it in your home activities onCreate method.'
A shared preference is a "setting" of sort. It's a xml file that is loaded which contains all of your settings. When we first run "sp.getInt" you can see that i have a 0 after the "key - fistlaunch". The 0 is specifying what to give our Int SHOW if it can't find any shared preference with that key. Next if the int show is equal to 0 we run our Toast and then change the shared preference value to 1 so next time you run it doesn't show...
boolean b = false;
if(!b) {
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
b = true
}
kind of like that?
Are you another instance of MainActivity?
In order to return to your Main activity you should send an Intent with the flag FLAG_ACTIVITY_CLEAR_TOP (or set android:launchMode="singleTop" in launchMode in AndroidManifest.xml)
Intent main = new Intent(aboutme.this,MyActivity.class);
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
By doing so, your main activity will be restored, instead of creating a new instance of MainActivity

Can't get onSharedPreferenceChanged() to work

I wanna display a dialog when the user selects a specific item from a ListPreference in my preferenceActivity. But, I cannot get the onSharedPreferenceChanged() to work. I've put a Toast in the beginning of the method, and it does not show, so the method doesn't even run through, why is this?
Here's my code: (Thanks)
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Toast.makeText(Preferences.this, "prefs Changed", Toast.LENGTH_SHORT)
.show();
if (key.equals("boolean_ad_type")) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String value = sharedPreferences.getString("boolean_ad_type", "");
if (value != null && value.equals("Pop-up Ads")) {
Toast.makeText(Preferences.this, "Pop-up Ads Selected",
Toast.LENGTH_SHORT).show();
}
}
}
And do I need to implement it in the activity like this? (I've tried with and without, no difference)
public class Preferences extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
onSharedPreferenceChanged not fired if change occurs in separate activity?
public class MyActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
you have to set a click listener for that specific preference you want to show the dialog in your onCreate
PreferenceScreen ps2 = (PreferenceScreen) findPreference("ic_vol");
ps2.setOnPreferenceClickListener(this);

Categories

Resources