Android onClick() tasks all happen at once - java

I'm trying to develop a feature for my app that pulls a string of text off of the internet (sort of like twitter, but a lot more basic) and displays it on the screen in a permeanent window. The user sees a large box with a refresh button next to it, and a small space below both where I would like to have a little progress monitor (just a TextView) which displays "Refreshing..." as soon as the refresh button is clicked, and then "Refresh successful!" once the string of text has been successfully pulled from the internet and displayed. This is just to reassure the user that something is actually happening when they press the button.
After a lot of research I've come to the conclusion that the way to update the TextView is to use a handler to execute a runnable which will update the text in the TextView. So my code looks like this:
refreshbutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View abc)
{
//display "Refreshing..."
refreshhandler.post(refreshingmsg);
/*Code to pull the string of text from the internet goes here (not shown)*/
//display "Refresh successul!"
successfulhandler.post(successfulmsg);
//clear the "Refresh successful" message after 2 seconds
clearhandler.postDelayed(clearmsg, 2000);
}
});
I hope that sort of makes sense. My issue is that these things all happen at once: I want the "Refreshing..." message to display, THEN for the phone to connect to the internet to find the string of text for the update, and THEN for the "Refresh Successful" message to display once the internet string has been successfully displayed. But what actually happens is that none of the commands in the onClick method actually happen until the phone has already pulled the message from the internet so the "Refreshing..." message isn't displayed at all. So what actually happens when the user clicks the button is that nothing happens for a second or two (presumably because the phone is busy pulling the string from the internet), then the string from the internet is suddenly displayed along with the message saying "Refresh Successful!".
So why is this happening? Is onClick supposed to work this way? If so, is there a workaround? I haven't posted my runnable and handler statements because I'm not sure it'll make any difference... but if it would help then I can post them!
Also, you can probably tell from this that I haven't been doing android (or indeed java) for very long, but I'm trying my best so please be gentle! Thanks :)

What is happening is that your code is locking on the network communication and doesn't let your app update itself with the handler value.
You should create an AsyncTask to that work for you.
On the OnPreExecute method, change your UI to show the user that you are refreshing your content. Reading your code it appears that you are updating an image, do that here.
On the doInBackground method do your actual network communication, an optional step is to use onProgressUpdate(Progress...) to update your UI to notify the user that the operation is progressing.
On the onPostExecute method you them update your UI to reflect the new content.
For more info check the documentation in AsyncTask, you can also search StackOverflow, there's a lot of good questions about it here.
As a side note, I don't recommend that you use handlers at all, AsyncTasks are easier to use and the code looks better.

Related

Android: call a method after a textView is changed

a simple issue here, but one I haven't been able to find a simple solution for. My Android app has a button that calls a calculations-heavy method which may take a while to return results. I want the user to know that the app is working, not frozen, so upon hitting that button I want to display a textView with a loading message, then call the method and load its results to another textView (while also hiding the first one). How can I make sure the method is started only AFTER the loading message becomes visible, because the code below fires the method when it's still not visible?
buttonCalculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
loadingMessage.setVisibility(View.VISIBLE);
findSolution();
}
});
you are looking for a Progress Bar, it's a an android feature that android made for you.
Here is a link for the official google site: https://developer.android.com/reference/android/widget/ProgressBar
I usually would just throw a Toast message to let them know they should wait, without having to use progress bar, for example when button is clicked it will display a message saying"please wait,loading"
inside the button Toast.makeText(this, "Loading,Please Wait", Toast.LENGTH_SHORT).show();
and you then can change the lenght of how long it should appear, lenghtshort is just 2 seconds

Method for "add to list" - Android application?? what method is suitable?

So i'm planning to develop an android application. In one activity, if i were to click a button of add, then it will prompt a user input and store the data. After that, thare would be another "list of item" button, where users can see which item they added and the information they input earlier.
I was thinking of using if.. else statement to check whether the button is click by setting a variable of default status=0 and change to 1 when clicked.
But how am i going to make sure that the functions won get messed up? is there any better suggestion for this? Im a beginner who just started to explore android studio.
Okay, so it is very simple and logical, and here is my best explanation. It's a rather long explanation, but I made it as thorough as possible...If you need any more help, just let me know:
You don't need to do any of that status=0 stuff. Just have an onclick listener:
(androidfromhome.com)
And in the listener, you want to go to another screen with a text input. So, just have an intent in the onClick which takes user to another screen:
(www.devcfgc.com)
Okay, so now you got your second screen right? You're going to want a textview (Change this in the xml) in the middle of the screen, where the user can enter data:
String stuff = TextView.getText();
Note, you will need to initialize the textview:
(androidfromhome.com)
So, now you got the text that the user entered. Just save it in SharedPreferences, and that's it, you have it saved!
http://developer.android.com/reference/android/content/SharedPreferences.html
Read about SharedPreferences in the link above.
So now, you have it saved. If you are going to get a lot of data, you can also save it in a database, which is more advanced stuff, that I don't know how to do. Now, display the saved data on the screen (A new screen, again, using an intent) using the method:
setText();
on your textView object for the next activity. That's it!

Making an Android App (Java) 'Wait' Until Something Finishes

I have this app that originally has you take a picture, shows you a progress bar, and uploads it to a website.
What I want to add is something so that before the progress bar shows, an Intent starts an activity that loads a layout with a dropdown menu that allows you to choose a descriptor for the picture. Following this, once you hit the 'OK' button on this new layout, the program should return back to where it had left off and display the progress bar.
Does anyone have any ideas on how to achieve this?
It seems that all I really want is some way to tell the program to stall for a while to call an intent, and when the user hits 'OK', the code may resume.
You should be using OnActivityResult().. More information on the link below http://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int)

How to execute one line of code before the rest? Changing text on a button

There's a button in my program that, when clicked, accesses a huge database and takes a second or two to do that, and then disappeaars. During that waiting time, I would like the button's text to change to "LOADING..." or something. I tried
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myButton.setText("LOADING...");
//then do other stuff
}
but of course lines of code aren't executed sequentially like that, so the text doesn't show up (or, shows up so quickly before disappearing that it isn't noticeable). Is there a simple way to do this? The only thing that comes to mind is using a Timer but (1) I'm not really sure how and (2) that seems overly complicated for just one simple line of code like that.
You need to use AsyncTask for your database access. In the runInBackground() you need to set your button to show "loading". You could refer to this - http://developer.android.com/reference/android/os/AsyncTask.html
http://www.vogella.de/articles/AndroidPerformance/article.html#concurrency_asynchtask is also a really good tutorial to help you with what you are trying to do.
The problem is that everything is done on the UI thread, and the long database access blocks the UI thread and prevents the "Loading..." text to be displayed. You should perform the database operation outside of the UI thread. Read http://developer.android.com/resources/articles/painless-threading.html.
You could use a Handler to notify you when the Db query gets completed and change the text appropriately. For using Handlers, I referred this tutorial
Actually the text is changing, it just hasn't been rendered yet, try to invalidate() the button too. You can also just test it out by removing the long process after the button click. Also if you have a long process make sure its not on the main thread and possibly use a ProgressDialog
Set it up to load when the Db starts loading and Change to Finished When the load has stopped.

Why is there no cancel button in Android's progress dialogs?

I'm facing a head-scratching moment similar to what this person (from Jan 2008) experienced when I realized that there is no cancel button in Android's progress dialog or spinners. It is now July 2009 and I've just installed the cupcake version of Android. Has this thing changed? If not, are you adding a cancel button into the dialogs and how do you do it?
not sure about the whole cancel button...i've heard reports of the onCancel() method not firing properly. my solution just consists of making a normal button on the dialog with a call to return whenever the button is pressed.
private void createCancelProgressDialog(String title, String message, String buttonText)
{
cancelDialog = new ProgressDialog(this);
cancelDialog.setTitle(title);
cancelDialog.setMessage(message);
cancelDialog.setButton(buttonText, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Use either finish() or return() to either close the activity or just the dialog
return;
}
});
cancelDialog.show();
}
then just use a simple call method from elsewhere in your activity
createCancelProgressDialog("Loading", "Please wait while activity is loading", "Cancel");
rather simple solution, but it does the trick ;)
also just to note that cancelDialog is an activity wipe variable, if you dont need to call it from elsewhere, then you should be able to get away with just limiting the scope of the variable to that method.
I'm no Android user or developer, but I think the answer given in the linked-to thread is pretty decent: there's a hardware "back" key on all Android devices. Users are supposed to know to press Back to back out of whatever activity they're currently in.
Thus, the UI designers feel it's unnecessary to include a GUI back/cancel button. This could be viewed as the UI application of the DRY principle; if there's already one way of doing something, that's enough.
The hardware key is the answer here. I'd be careful about generalising the DRY principle to UIs. There are plenty of cases where you need to hammer, hammer, hammer the same point to the user repeatedly via headings, body text, colours and images.
Users dont "read" UIs the way you read a novel. They scan read.
I can't speak for other apps, but in mine anything that might cause the UI thread to wait is executed in a seperate thread. The most I'll do is show a small progress spinner in the titlebar to let the user know something is going on in the background.
As an Android user, and developer, I can say, in my opinion, and based around my understanding of the platform, that there is a good reason for not having a cancel button by default on the cancel-free progress dialogs.
As a developer, these dialogs can not be cancelled by default, that is, you have to explicitely set them as cancelable.
This makes sense, because their purpose is to alert the user, via the UI thread, that some work is going on elsewhere that is important to the updating of the UI thread, before the user should continue their use of the application.
For example, when fetching a list of data to occupy an empty screen, there is nothing to interact with, and the user needs to be made aware that something is going on, and to expect there to be nothing available to interact with until this process is complete.
However, there may be cases, such as data retrieval from the internet, where the process is "sketchy" and due to connectivity issues, you may not be able to complete the request, and get stuck here.
This as a develop is where you enable the dialog to be cancel-able.
Now as a user, one that clearly understands the UI paradigm of Android, I know that if I want to go back to what I was doing before, or "cancel" the current operation, I should hit the back key.
As a user, it's no different to knowing that in Android, the menu key can often reveal hidden options, some times on a seemingly blank screen with no way to interact.
This is the behaviour a user expects, and the way the platform is designed. You could very well add a cancel button, but from a users perspective that understands their phone, this makes no difference, the back key is clearly the intended choice for this purpose.
Activities and UIs have a flow, you flow through activities and UI "screens" which are "stacked" and the back button essentially "pops" the last thing off the stack to return you to where you were previously. If you see the dialog as another of these activities, you want to pop it from the top of the stack to return to what is underneath, or an activity previous to that.
If a developer has a dialog that can not be cancelled by back, it is either, by design, for which there can, in cases, be very good reason for, or, it is poor development and an oversight on the devloper's part.

Categories