Save app when user exits using back button [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I know that when the user presses back button the saveoninstance is not supposed to be called.
I have a layout with many edittexts added dynamically by user, and then the user can enter text. I managed to save these when the user rotates screen using saveoninstance etc.
However, I also want to save these when the user exits app using the back button so when the app is opened again a "continue" button should be available for the user to continue (meaning adding all the text boxes again). I kind of know how to save and retrieve them, but which method should I use? Should i write a file for a example? Thanks.

When the user pressed back button application is closed. When he open app again it start as new instance and don't remember what user done before.
If u have to save data, then u can save them (eg. to Preferences or database) in onPasue or onDestroy

If you know how to save and retrieve them, why dont you just override the Back button and write save functionality there.
e.g.
public boolean onKey(View v, int keyCode, KeyEvent event)
{
// TODO Auto-generated method stub
return false;
}
#Override
public void onBackPressed()
{
/*Your functione here to what should be done on Back Button Press event*/
}

What you have to do is, you have override the below method in your Activity,
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
And save the state of your activity in SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the state accordingly.
Example,
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", "true");
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
onCreate(Bundle savedInstanceState)
{
//just a rough sketch of where you should load the data
LoadPreferences();
}

Basically shared preference in android are used to save the state of an activity or to save the important data within the scope of an application means data will remain saved till the application is installed in the devices. Shared Preference also works as Sessions which are used for the automatic login process.
see this Documentation.
And here is an Example.

Well its pretty simple. All you need to do is:
Use shared preferences and bundle.
Save everything in the onSavedInstanceState(Bundle outState)
Now how you do is:
Overwrite the function onSavedInstanceStae(Bundle outState)
and inside it
Save everything in Shared Preferences and then bundle them ,and this bundle is then sent automatically as a parameter in your onCreate(Bundle bundle)
Thus in your onCreate check if the bundle==null; if not retrieve sharedPreferences and load the data just like you saved it.

Related

How do I overwrite back button of BSImagePicker gallery?

I'm new new in Java and working on an old project that uses bsImagePicker. There's a bug in my current project that when the user wants to click the below back button of the gallery it takes the user to home page.
This shouldn't be the default behavior, rather it should take the user 1 step back. Please, How do I overwrite the method of this back button? Unfortunately, I couldn't find any xml file that has referenced this button neither there's any previous overwritten method.
Thanks in advance.
Edit: I searched more and figured out maybe it has to do something with getSupportActionBar().setDisplayHomeAsUpEnabled() but I don't know how to set its android:parentActivityName attribute.
To override onBackPressed() method and implement your own functionality or behavior.
#Override
public void onBackPressed() {
//implement your own functionality in this
}
But since you are trying to implement it for back button shown in attached image and you don't have reference of it. Either you can create a reference by own or you can try on onCancelled method as provided in BSImagePicker gallary github repo.
//Optional
#Override
public void onCancelled(boolean isMultiSelecting, String tag) {
//Do whatever you want when user cancelled
}

Does Android have an "onInstall" method?

I am trying to log installs of my app using Firebase with this simple code below:
firebaseAnalytics.logEvent("foo", bundle);
However, I am not sure where to put this code. Does any one know of an "onInstall" method in the Application class?
Or is there another, easier way to log installs with Firebase?
Thank you!
You could determine if the user launches the application for the first time, and log that event.
public class MyActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
firebaseAnalytics.logEvent("foo", bundle);
prefs.edit().putBoolean("firstrun", false).commit();
}
}
}
Code referenced from this SO answer.
There's another answer in that same SO question that explained how to differentiate between first run and subsequent upgrades, I'll just link that SO answer here for your reference.
The cleanest method would be to have a remote server that holds a unique ID for each user.
Also, you could theoretically write a file directly on the device. But then, you'd need to get the write permission and it's most definitely not a good idea to create and leave a file on the device.
P.S - To answer the actual question, No, Android doesn't have an onInstall method.

How to add find facility to an activity

In my application, there are five activities containing very long text. I want to add find facility to my activity, so that when a user types something to the search bar then if the activity contains that word then the word should scroll to top automatically being highlighted.I am able to call the Search Dialog (as instructed in the Android Developer page). Can you guys help me compare the input in the search dialog with the texts in my activity and scroll it to top?
MainActivity.java
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested(); //opens the search dialog
break;
return super.onOptionsItemSelected(item);
}
SearchableActivity.java
public class SearchableActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
//Get the intent, verify the action and get the query
Intent intent = getIntent();
if (intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query);
}
}
private void doMySearch(String query) {
//what to do here???
}
}
Here the searchable activity is a different activity. How do I compare the search input with a text which is in another activity (MainActivity.java)?
What you trying to do is:
Take Certain Input Value from an activity (input in the dialog from MainActivity), then use that value to compare with something else in the another activity (SearchableActivity)
There should be few method to do so, I would suggest a simple method which is:
Store the Value Input to a Global Variable that can be access Global in the whole application.
Then used the store value in the Global Variable to do comparison the any activity you want to.
To store something to Global variable, you can use the SharedPreference Method: Android Shared preferences example
This Method store Specify Value into a Global Variable where all activity can be access and Store Permanently only until you command to delete. Something like a 'Session' of a Website.
In your case, I will make use of the sharedpreference by:
When user enter something in the search dialog, I will store the value in a SharedPreference Variable.
Then when come to the SearchableActivity that need to use the input value of search dialog to do comparison, I will call the SharedPreference Variable to do comparison.
For your information:
Share Preference is very useful to store Value that used for Permanent usage of the application and its Scope is covering all the Activity in your Application. You can have Great Control of it, because you can specify to Store, Rewrite, Delete the value whenever you want, in wherever you want.
Hope This Would Help.

Entering app exactly as it was left

I know there must be douzens of answers to this question out there, but either i cant't find them or I don't understand them.
The Question:
How do I get my app to exactly start as it was left?
F.e. dynamicly added checkBoxes shouldn't dissapear!
There is no "out of the box" way of doing it. You could save the current state of your Activity in some way (More on persistence)
Then you need to be able to rebuild the desired state of the persisted state in your Activity lifecycle
You could save and load with the shared preferences for example:
public void saveState(YourState state) {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
sharedPreferences.edit()
.putString("CustomAtt", state.getCustomAtt())
}
public YourState loadState() {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
String customAtt = sharedPreferences.getString("CustomAtt", "DefaultValue")
return new YoutState(customAtt)
}
And use it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
YourState state = loadState();
// Rebuild your activity based on state
someView.setText(state.getCustomAtt())
}
You can store such values in SharedPreferences.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
It is using key-value approach for saving. So you can save some values and read it from SharedPreferences whenever you want to.
This is the best approach for small data, that can be used on the app launch. So you can quit your app and the data is still present - so can be read on the next app launch.
Or save the condition of your program to a text file, so that the program can "translate" it back into conditions before it stops, or what I do not recommend, it saves every object created with ObjectOutputStream.

Android save details screen

I am working on a small project that requires a details screen where the user inputs his details and they are permanently stored. The user must have the option to change the details as well if he needs to do so. I looked into the saved preferences library however it does not seem to offer such functionality.
To give a visual idea of what is required, something like this screen should be fine:
http://www.google.com.mt/imgres?start=97&num=10&hl=en&tbo=d&biw=1366&bih=643&tbm=isch&tbnid=aQSZz782gIfOeM:&imgrefurl=http://andrejusb.blogspot.com/2011/10/iphone-web-application-development-with.html&docid=YpPF3-T8zLGOAM&imgurl=http://2.bp.blogspot.com/-YRISJXXajD0/Tq2KTpcqWiI/AAAAAAAAFiE/-aJen8IuVRM/s1600/7.png&w=365&h=712&ei=rbX6ULTDCOfV4gTroIDoCg&zoom=1&iact=hc&vpx=834&vpy=218&dur=2075&hovh=314&hovw=161&tx=80&ty=216&sig=108811856681773622351&page=4&tbnh=155&tbnw=79&ndsp=35&ved=1t:429,r:4,s:100,i:16
Any help is much appreciated. Thanks in advance
You could easily use Shared Preferences to store user's details. Everytime the Preference screen is opened the stored data can then be extracted from the Shared Preferences and presented to the user for edit. ONce the edit is done the new data can be updated back in the the Shared Preferences.
Also look at this thread to see how this can be done.
Using SharedPreferences would be perfect for this kind of small amount of data which you want to store persistently.
// 'this' is simply your Application Context, so you can access this nearly anywhere
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To obtain from the preferences:
// You can equally use KEY_LAST_NAME to get the last name, etc. They are just key/value pairs
// Note that the 2nd arg is simply the default value if there is no key/value mapping
String firstName = prefs.getString(KEY_FIRST_NAME_CONSTANT, "");
Or to save:
Editor editor = prefs.edit();
// firstName being the text they entered in the EditText
editor.putString(KEY_FIRST_NAME_CONSTANT, firstName);
editor.commit();
You can achieve such functionality using SharedPreferences Class in android.
public void onCreate(Bundle object){
super.onCreate(object);
// Initialize UI and link xml data to java view objects
......
SharedPreferences myPref = getPreferences(MODE_PRIVATE);
nameView.setText(myPref.getString("USER_NAME", null));
passView.setText(myPref.getString("PASSWORD", null));
}
public void onStop(){
super.onStop();
if (isFinishing()) {
getPreferences(MODE_PRIVATE).edit()
.putString("USER_NAME", nameView.getText().toString())
.putString("PASSWORD", passView.getText().toString())
.commit()
}
}

Categories