Removing ProgressDialog when user presses the back button - java

I have an activity that queries a server database and returns a list of results...while querying the app displays a simple progressDialog on the onCreate method like so:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//display progress dialog while querying server for values
final ProgressDialog dialog = ProgressDialog.show(this,"","Retrieving listings please wait...");
dialog.setCancelable(true);
dialog.show();
If the user clicks on an item from the list then another activity placeDetails is opened. Once done a user can press the back button to go back to the previous activity which displays the listings.
When I tested it naturally it shows the above dialog and sends the query back to the server even though the listings can be seen in the background of the progressDialog.
What I want to know is how would I prevent the database being queried again and the above progressDialog from displaying when the user presses the back button.
Do I have to go down the caching route? or is there another way?

1.) To prevent the database from being queried again you can simply cache this data in a local SQLite database as Tom Dignan mentioned.
2.) To prevent the progressDialog from displaying when the user presses the back button, simply override the onBackPressed() method of the current activity (when back is pressed) and set an Intent to the activity that preceeds the progresDialog. I believe there's even a method to do this so that you won't be starting a new instance of that activity but simply accessing a cached version.

I managed to solve this issue the missing link was I did not know how to check for dialog windows the following code helped:
//first declare the dialog so its accessible globally through out the class
public class ListPlaces extends ListActivity {
ProgressDialog dialog;
then on the onCreate first check that a dialog exists or not
if(dialog == null){
dialog = ProgressDialog.show(this,"","Retrieving listings please wait...");
//display progress dialog while querying server for values
dialog.setCancelable(true);
dialog.show();
}
And the mistake was I was using
dialog.hide();
instead of
dialog.dismiss();
Thanks for the contributions

Related

Retrieving keys from a savedinstancestate when a user navigates away from an activity and then back

I'm having a problem with SavedInstanceStates. In the Main Activity of my app, a listview is populated with names from a database. When you click on one of the names, a new activity is opened, which shows another listview drawn from a separate database and details various information about the person. The items on this listview are only shown if their characterID, set according to the person whose name they are created under, and the id of the person in the original database match. So long story short, you can create a person Trevor, there are then a number of pieces of information shown specific to Trevor when you click on Trevor. You can also click on those pieces of information to open a new activity and edit that info/ do stuff with the info. I did this by saving the Uri of the person clicked with setData, and then getting that uri with getData and parsing the id from it for my second query.
When a user clicks a piece of information about Trevor and it opens in a new activity, the variable containing the id is destroyed as is the data I set in the first activity. So when I click back, it crashes due to a NullPointerException. So I now check if the data from getData() is null before performing my database query. But that just leaves the listview empty since it has no id to use when querying the database.
So I tried to used onSaveInstanceState to save the characterId variable. But using onRestoreInstanceState doesn't seem to work. Navigating to the third activity, and then finishing it by clicking back, does not seem to call onRestoreInstanceState. I also tried to check if the savedInstanceState is null in onCreate, see if it contains they key I set, and then withdraw it, but the savedInstanceState is null in onCreate whether Im first navigating to it, or hitting the back button to return to it. I've looked around for a few hours trying to figure out the answer. Is this the wrong tool for the job? Am I missing something?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(savedCIdString)) {
characterId = savedInstanceState.getInt(savedCIdString);
}...
A snippet of my onCreate where I try to retrieve the variable, but SavedInstanceState is null when I first navigate to it, and when I press back from the activity after it.
#Override
protected void onSaveInstanceState (Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(savedCIdString, characterId);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
characterId = savedInstanceState.getInt(savedCIdString);
}

How to keep entered text in edittext field?

I'm creating an app that require user to enter name, email, date and etc in Main_Activity.xml. Then, the user will click submit. The entered data will be displayed in confirm.xml. In confirm.xml, user need to verify entered data and if the want to edit entered data, they will click back button to edit data again. I tried to do that but once I click back button, all the data I entered in editText field disappeared. I want to keep the data I entered in MainActivity.xml's editText field, so I can change only some field that need to be edited. How can I do this? Thank you.
This can happen when the activity where you entered data is destroyed. How do you open the new confirmation activity? That's the part of the code that probably contains the error.
If you call finish() when you open the new activity then activity will be destroyed and data kept in EditText cleared.
To open a new activity and preserve data of the current one you just need to call startActivity(...) without finish().
Intent intent = new Intent(context, ConfirmationActivity.class);
startActivity(intent);
Anyway, the activity can be destroyed by android to free up memory when needed. That happens when you open another application that needs memory but memory is used by your application, so the system destroys your activities and it's up to you to save data on disk by using Bundles and restoring them.
I suggest you to read this guide https://developer.android.com/guide/components/activities/activity-lifecycle.html
You can overwrite the onSaveInstanceState(Bundle savedInstanceState) function and use the savedInstanceState to save the various data that you want to get back during the onCreate(Bundle instanceState) or onRestoreInstanceState(Bundle instanceState).
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("TextFieldX", "Data To Retrieve");
}
And get it back:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//get back value
String value = savedInstanceState.getString("TextFieldX");
}
https://developer.android.com/reference/android/os/Bundle.html
For longer lived persistance of your data, you would write it to SQLite.
You can save all your information to String's like private String Name;
write/set this Name when user enter's the Name and use it again like as follows:
if(name != null && !name.toString().isEmpty()) {
set name String on your editText widget.
}
You can use shared preference object to save value of edittext value in user's phone. When code execute second time, you just check about variable in shared preference. If variable is not null, fetch value from it and set that string using setText() method.

Switch goes back to off

When turn the switch on it stays on.. however when i leave the activity and come back to it.. it goes back to off. I want it to stay ON OR OFF depending on whats last pressed. I have tried the code below but does not resolve my issue
SwitchButton.setChecked(true);
SwitchButton.setChecked(false);
What you need to do is override these methods in your activity:
#Override
protected void onSaveInstanceState (Bundle outState){
super.onSaveInstanceState(outState);
outState.putBoolean("CHECKED", SwitchButton.isChecked());
}
then in onCreate:
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstaceState);
if(savedInstanceState != null){
boolean isChecked = savedInstanceState.getBoolean("CHECKED");
SwitchButton.setChecked(isChecked);
}
}
If you are minimizing the activity and then returning back to it, and you want all controls to retain their states, then look into implementing saved instance state. This will persist the control values while you minimize / maximize the activity or rotate it. No data is permanently saved to the device. Sample code here:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html#SaveState
If you are closing the app completely and want the app to remember the settings, then consider SharedPreferences, which can be used to save data locally on the device. The data persists until your app explicitly deletes it or you uninstall the app. Sample code here:
http://developer.android.com/training/basics/data-storage/shared-preferences.html

The difference between implementation of back and cancelbutton?

I m a newbie an trying to learn Java/Android-programming.
I m doing an app for Android in Eclipse and created some buttons.
I have a back and a cancel button.
Example:
I have a EditText there you can write in your name. If you write yourname and press the backbutton, then u will go back to the previous Activity, but if you go to the same Activity, then you will still see the name that you wrote in the EditText.
But if you press the cancelbutton, you will go back to the previous Activity, but when you come back, yourname will be empty. I will "kill" or "stop" the Activity.
This is the code I use for the Backbutton, what would you use for the Cancel Button?
Thank YOU.
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonBack:
Intent intent = new Intent (AllActivity.this, MenuActivity.class);
startActivity(intent);
break;
For the cancel button you can use the below method, this will kill the activity.
finish()
so in your code it will look something like this:
public void onClick(View v) {
switch(v.getId()){
case R.id.cancel:
finish();
break;
There was little difference in this as per requirement of process or application flow. For cancel and back as work are same for example if you open any dialog and provide cancel button will close/dismiss your dialog same way the back button do this. While for implementing with the Activity you if you implement for closing current activity you can just finish with both option by just calling finish() method. As back button was normally work for finish you current activity and back.
Another way to do this that you may be interested in is to wipe out the content of the EditText yourself.
You would need to have in your xml file an id defined for the EditText so that you could access it programatically.
<EditText
layout stuff here:
android:layout_width="fill_parent"
...
and then the id attribute
android:id="#+id/edit_text_id"
>
then in your code you would put the following in your class (not inside any method):
EditText anEditText;
then in your onCreate(), after the inflation of the layout (if it comes beforehand it will cause the app to crash):
anEditText = (EditText) findViewById(R.id.edit_text_id);
the name edit_text_id is not significant, but it is what we used in the layout file
next add to the onClick method for cancel (after the case statement):
//this wipes the text from the textbox
anEditText.setText("");
// add the rest of the back button code after this and your good!
Best of luck! Remember that we were all newbies once. If you want to be a good android programmer, I suggest that you get a strong background in Java first. This free book helped me very much!
Java Notes

Android activity restart

Hey guys, i am making an android application where i want to show a dialog box about legal agreement everytime the application starts, i have a public method showalert(<>); which shows an alertdialog by building a dialog with alertbuilder. I added a call to showalert() method on the onCreate() method of the main activity to show it, but whenever the user rotates the screen, he gets the dialog everytime. The activity restarts itself when the phone is rotated. I tried adding android:configChanges="keyboardHidden|orientation" to my manifest but that doesnt help on this case. Also can i know how to register a new application class on manifest file. I am trying to create an application class and put the code to show dialog on the new class's oncreate method. But i am not being able to load the class when the app starts.
I also checked Activity restart on rotation Android but i dont seem to get a thing. I am pretty much a newbie to android programming, could someone simplify that for me?
Any help would be appreciated. :)
you could maybe look at the onRetainNonConfigurationInstance() activity method, which is called just before destroying and re-creating the activity on screen orientation change.
it allows you to retain an object that could for instance contain a test variable to know if your legal thing was already shown or not.. example :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String test = (String) getLastNonConfigurationInstance();
if (!("textAlreadyShown").equals(test)) {
//here : show your dialog
}
}
#Override
public String onRetainNonConfigurationInstance() {
return "textAlreadyShown";
}
Set the main activity to an activity that just shows the legal notice, when it is accepted/cleared, show a second activity ( which is currently the main activity )?

Categories

Resources