In Activity A, I click a button to go to Activity B. I bring data using Bundle back to the Activity A and I managed to change a String value in the ListView. Then I go to another Activity C to manipulate another data. The problem is, when I get back again to the Activity A, the data from the Activity C is reflected in the ListView, but the previous data from the Activity B is gone.
Here's a code to the Activity B from the Activity A.
private void gotoRepeatWeeklyOptionActivity() {
Intent intent = new Intent(CreateNewAlarmActivity.this, RepeatWeeklyOptionActivity.class);
startActivity(intent);
finish();
}
This one is the method from the Activity A to the Activity C.
private void openAlarmToneOptionDialog() {
Intent intent = new Intent(CreateNewAlarmActivity.this, ChooseAlarmToneActivity.class);
startActivity(intent);
}
And this is a code that leads to the Activity A from the Activity B.
#Override
public void onBackPressed() {
Intent intent = new Intent(this, CreateNewAlarmActivity.class);
ArrayList<Integer> repeatStatusIntList = new ArrayList<>();
intent.putExtra(Keys.OPTION, Keys.OPTION_REPEAT);
if(cbRepeatEveryDay.isChecked()) {
super.onBackPressed();
intent.putExtra(Keys.VALUE, Keys.EVERY_DAY);
Toast.makeText(this, getString(R.string.alarm_will_repeat_every_day), Toast.LENGTH_SHORT).show();
} else if(allUnchecked()) {
super.onBackPressed();
intent.putExtra(Keys.VALUE, Keys.NO_REPEAT);
Toast.makeText(this, getString(R.string.alarm_will_never_repeat), Toast.LENGTH_SHORT).show();
} else {
for(int i=0; i<repeatStatusList.size(); i++) {
super.onBackPressed();
if(repeatStatusList.get(i).isChecked()) {
repeatStatusIntList.add(getRepeatStatusInt(repeatStatusList.get(i)));
intent.putIntegerArrayListExtra(Keys.KEY_REPEAT_STATUS_INTEGERS_LIST, repeatStatusIntList);
}
intent.putExtra(Keys.VALUE, Keys.ON);
}
Toast.makeText(this, getString(R.string.alarm_will_repeat) + getString(R.string.every) +
getAllRepeatDays(repeatStatusList), Toast.LENGTH_SHORT).show();
}
startActivityForResult(intent, RESULT_OK);
finish();
}
Finally, this is a code from the Activity C, which leads back to the Activity A.
btnSelectTone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), CreateNewAlarmActivity.class);
intent.putExtra(Keys.OPTION, Keys.OPTION_ALARM_TONE);
intent.putExtra(Keys.VALUE, ringtone);
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
startActivityForResult(intent, RESULT_OK);
finish();
}
});
Here's a sample screen from the Activity A.
what Atif has suggested is one solution which is most desirable in your case.
Else you can use Shared Preferences like below. Get the SP instance and commit the data you want to share in editor
// 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.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
And this is how you can retrieve the shared pref data
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
Personally i would suggest you to surf more on developer.android.com or visit below link
https://developer.android.com/guide/topics/data/data-storage.html#pref
In future if you have large amount of data then above solution wont work.
Please follow below link for more options
How to pass the values from one activity to previous activity
Related
Below is my code to the MainActivity.java of my project, this is the welcome like screen for my app and should only appear first time user opens the app. Otherwise the user should get to see the Medicine_Activity.java which is also triggered when the user presses "Get Started" button on MainActivity. In order to implement this i came across something known as SharedPreferences and tried to implement it. But it isnt working quite as expected, the MainActivity flashes for a second before Medicine_Activity is launched. I am new so please help me out
Here is a video clip to view this bug in action - https://www.dropbox.com/s/fqbo9urb6xnh3pd/WhatsApp%20Video%202019-06-20%20at%202.12.50%20PM.mp4?dl=0
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnGetStarted;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.apply();
} else{
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
}
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
getSupportActionBar().hide(); // hide the title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
setContentView(R.layout.activity_main);
Button btnGetStarted = findViewById(R.id.btnGetStarted);
btnGetStarted.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
}
}
Use commit() while storing the true and finish() the MainActivity.
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), true);
edit.commit();
} else{
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
finish();
}
A short explanation: commit() writes the data synchronously (blocking the thread its called from). It then informs you about the success of the operation. However, apply() schedules the data to be written asynchronously. It does not inform you about the success of the operation.
Quoting from Documentation:
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures
So basically I'm trying to pass an EditText String to another fragment which is in the same Activity. Then pass that data to another Activity, depending on which button the pressed. My problem is the application works fine but I just don't see the string being created. I've tried to use a textview just to check if it works when I pass it through the first data, but nothing shows.
I just want to pass the string to another fragment then depending on the button they press pass it on the whichever Activity.
This is my code
Passing my Data to the next Fragment and going to the fragment.
mNextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), ItemStorageFragment.class);
intent.putExtra("itemName", addName.getText().toString());
((AddInventoryActivity)getActivity()).ToExpiration(null);
}
});
Grabbing the data from my First Fragment
Intent intent = getActivity().getIntent();
value = intent.getStringExtra("itemName");
Then Sending it to the Activity
mToFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(getActivity(), FreezerActivity.class);
in.putExtra("itemNameToFreezer", value);
startActivity(in);
}
});
Then Adding it to my RecyclerView
Intent i = getIntent();
String string = i.getStringExtra("itemNameToFreezer");
mDataset.add(string);
mAdapter.notifyDataSetChanged();
Intent extras are fine to share data between Activities, but you cannot use them for Fragments directly, as you did in your code. I assume, you are a beginner, so I recommend you read in depth about Intents here: Android - Intents and Filters
There are several ways of passing data between Activities and Fragments, most common of which is passing arguments. Yet, in your situation I'd recommend using SharedPreferences. You can store String data at any point inside your Fragment or Activity and then easily take it out with these simple steps:
Input data into SharedPreferences:
SharedPreferences.Editor editor = getSharedPreferences("YourPrefsFile", MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
Get data from SharedPreferences:
SharedPreferences prefs = getSharedPreferences("YourPrefsFile", MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "");
int idName = prefs.getInt("idName", 0);
}
I have an activity that i only want to run when the application is ran for the first time.
And never again. It is a facebook login activity. I only want to launch it once when the app is initially opened for the first time.
How do i go about doing this?
What I've generally done is add a check for a specific shared preference in the Main Activity : if that shared preference is missing then launch the single-run Activity, otherwise continue with the main activity . When you launch the single run Activity create the shared preference so it gets skipped next time.
EDIT : In my onResume for the default Activity I do this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
showHelp();
}
Basically I load the default shared preferences and look for the previously_started boolean preference. If it hasn't been set I set it and then launch the help file. I use this to automatically show the help the first time the app is installed.
Post the following code within your onCreate statement
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, FirstLaunch.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
Replace FirstLaunch.class with the class that you would like to launch
something like this might work.
public class MyPreferences {
private static final String MY_PREFERENCES = "my_preferences";
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
}
usage
boolean isFirstTime = MyPreferences.isFirst(CurrentActivity.this);
if (isFirstTime) {
NewActivity.show(CurrentActivity.this);
}
...
public class NewActivity extends Activity {
public static void show(Context context) {
final Intent intent = new Intent(context, NewActivity.class);
context.startActivity(intent);
}
}
SharedPreferences dataSave = getSharedPreferences("firstLog", 0);
if(dataSave.getString("firstTime", "").toString().equals("no")){ // first run is happened
}
else{ // this is the first run of application
SharedPreferences.Editor editor = dataSave.edit();
editor.putString("firstTime", "no");
editor.commit();
}
I had done this without Shared Prefrence...as I know shared prefrence consumes some memory so I used public static boolean variable in global class....First I made Global Class Appconfig...and then I made boolean static variable like this :
public class Appconfig {
public static boolean activity = false;
}
then I used this public static boolean variable into my welcome Activity class. I am Using License agreement page. which I have to use only at once in my application then never display further whenever i run the application. so i had put condtion in welcome activity...if the welcome class run first time so the static boolean variable is false...
if (Appconfig.activity == false) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this,LicesnceActivity.class);
startActivity(intent);
WelcomeActivity.this.finish();
}
if (Appconfig.activity == true) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this, MainActivity.class);
startActivity(intent);
}
Now at Licesnce Activity class I made :
Appconfig.activity=true;
So whenever I run the Application the second activity "Main activity" run after Welcome activity not License Activity....
Declared in the globally
public int count=0
int tempInt = 0;
in your onCreate function past this code at first.
count = readSharedPreferenceInt("cntSP","cntKey");
if(count==0){
Intent intent = new Intent();
intent.setClass(MainActivity.this, TemporaryActivity.class);
startActivity(intent);
count++;
writeSharedPreference(count,"cntSP","cntKey");
}
Past these two method outside of onCreate
//Read from Shared Preferance
public int readSharedPreferenceInt(String spName,String key){
SharedPreferences sharedPreferences = getSharedPreferences(spName,Context.MODE_PRIVATE);
return tempInt = sharedPreferences.getInt(key, 0);
}
//write shared preferences in integer
public void writeSharedPreference(int ammount,String spName,String key ){
SharedPreferences sharedPreferences = getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, ammount);
editor.commit();
}
This is my code to bring the OnBoarding Activity for the first time. If it's not the first time then go directly to the Home Activity.
private void checkFirstOpen(){
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (!isFirstRun) {
Intent intent = new Intent(OnBoardingScreen.this, Home.class);
startActivity(intent);
finish();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun",
false).apply();
}
in first activity i have 3 button firs button go to subject list , second button show last seen activity
Im use this for last seen activity :
in subject list for each item save number in shared preferences and when user click on last seen number in subject list call and show last activity
this code work well but when i turn of phone or app not open for minutes last seen show nothing why?
please help me
in subject list class
shared = getSharedPreferences("count", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
public static int counter;
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Intent intent0 = new Intent(getApplicationContext(),Study.class);
startActivity(intent0);
counter=1;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
}
if (i == 1) {
counter=2;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
Intent intent1 = new Intent(getApplicationContext(),Mo.class);
startActivity(intent1);
}
if (i == 2) {
counter=3;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
Intent intent2 = new Intent(getApplicationContext(),Sa.class);
startActivity(intent2);
}
in fist activity that contain last seen button :
case R.id.last_seen_btn:
if (SubjectActivity.counter==0){
Toast.makeText(getApplicationContext(), " nothing",
Toast.LENGTH_LONG).show();
}
if (SubjectActivity.counter==1){
Intent intent = new Intent(getApplicationContext(),Study.class);
startActivity(intent);
}
if (SubjectActivity.counter==2){
Intent intent = new Intent(getApplicationContext(),Mo.class);
startActivity(intent);
}
if (SubjectActivity.counter==3){
Intent intent = new Intent(getApplicationContext(),Sa.class);
startActivity(intent);
}
You shall use always the "application preferences" and best is to access them via the Application object. There is caching on SharedPreferences aand it's creating some issues some time.
Also update always the SharedPreferences before opening the Activity (if i == 0)
public class MyApp extends Application {
private SharedPreferences mMyPref;
#Override
public void onCreate() {
super.onCreate();
mMyPref = getSharedPreferences("my_pref_name", MODE_PRIVATE);
}
public SharedPreferences getMySharedPreferences(){
return mMyPref;
}
}
In your parts of code where you want to read/write just use
((MyApp)getApplicationContext()).getMySharedPreferences() ....
of of course create a local variable that gives you the possibility to work with it.
I have an activity that i only want to run when the application is ran for the first time.
And never again. It is a facebook login activity. I only want to launch it once when the app is initially opened for the first time.
How do i go about doing this?
What I've generally done is add a check for a specific shared preference in the Main Activity : if that shared preference is missing then launch the single-run Activity, otherwise continue with the main activity . When you launch the single run Activity create the shared preference so it gets skipped next time.
EDIT : In my onResume for the default Activity I do this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
showHelp();
}
Basically I load the default shared preferences and look for the previously_started boolean preference. If it hasn't been set I set it and then launch the help file. I use this to automatically show the help the first time the app is installed.
Post the following code within your onCreate statement
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, FirstLaunch.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
Replace FirstLaunch.class with the class that you would like to launch
something like this might work.
public class MyPreferences {
private static final String MY_PREFERENCES = "my_preferences";
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
}
usage
boolean isFirstTime = MyPreferences.isFirst(CurrentActivity.this);
if (isFirstTime) {
NewActivity.show(CurrentActivity.this);
}
...
public class NewActivity extends Activity {
public static void show(Context context) {
final Intent intent = new Intent(context, NewActivity.class);
context.startActivity(intent);
}
}
SharedPreferences dataSave = getSharedPreferences("firstLog", 0);
if(dataSave.getString("firstTime", "").toString().equals("no")){ // first run is happened
}
else{ // this is the first run of application
SharedPreferences.Editor editor = dataSave.edit();
editor.putString("firstTime", "no");
editor.commit();
}
I had done this without Shared Prefrence...as I know shared prefrence consumes some memory so I used public static boolean variable in global class....First I made Global Class Appconfig...and then I made boolean static variable like this :
public class Appconfig {
public static boolean activity = false;
}
then I used this public static boolean variable into my welcome Activity class. I am Using License agreement page. which I have to use only at once in my application then never display further whenever i run the application. so i had put condtion in welcome activity...if the welcome class run first time so the static boolean variable is false...
if (Appconfig.activity == false) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this,LicesnceActivity.class);
startActivity(intent);
WelcomeActivity.this.finish();
}
if (Appconfig.activity == true) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this, MainActivity.class);
startActivity(intent);
}
Now at Licesnce Activity class I made :
Appconfig.activity=true;
So whenever I run the Application the second activity "Main activity" run after Welcome activity not License Activity....
Declared in the globally
public int count=0
int tempInt = 0;
in your onCreate function past this code at first.
count = readSharedPreferenceInt("cntSP","cntKey");
if(count==0){
Intent intent = new Intent();
intent.setClass(MainActivity.this, TemporaryActivity.class);
startActivity(intent);
count++;
writeSharedPreference(count,"cntSP","cntKey");
}
Past these two method outside of onCreate
//Read from Shared Preferance
public int readSharedPreferenceInt(String spName,String key){
SharedPreferences sharedPreferences = getSharedPreferences(spName,Context.MODE_PRIVATE);
return tempInt = sharedPreferences.getInt(key, 0);
}
//write shared preferences in integer
public void writeSharedPreference(int ammount,String spName,String key ){
SharedPreferences sharedPreferences = getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, ammount);
editor.commit();
}
This is my code to bring the OnBoarding Activity for the first time. If it's not the first time then go directly to the Home Activity.
private void checkFirstOpen(){
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (!isFirstRun) {
Intent intent = new Intent(OnBoardingScreen.this, Home.class);
startActivity(intent);
finish();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun",
false).apply();
}