How to redraw a screen in Android - android-layout

I want to know how I can for a screen to redraw it's current content?
What I have at the moment is the following: I have an activity that checks if a flag is set to true or false, if the flag is true it needs to load one xml file as it's layout, if the flag is false it needs to load a different one. This code works.
The problem I have is that the screen does not redraw itself unless I change the orientation of it, aka I flip the phone. I need the redraw to happen the moment the state of the flag changes. I had this working with the onResume(), but the problem with that was that the layout went back to the default state and did not save any input or button changes that had been made, this happened when I switched from one tab to the next.
So I guess what I am asking is something along the lines of how I can make changes to a layout file and keep them when switching between tabs in my application, so that when I go back to that tab, all the changes are still there?

Why don't you you an AsyncTask waiting in background for your flag to become true (or false idk), then onPostExecute you can modify your UI as you wish. Switching between tabs shouldn't make your Activity change. Hope it helps.
private class WaitMyFlag extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... params) {
while(!youflag){
try {
Thread.sleep(100);
} catch (Exception e){
Log.e(TAG, "Couldn't sleep !");
}
}
}
#Override
protected Void onPostExecute(Void params) {
//UI Modifications
}
}

Related

Fragment in minimize Android Studio

I have a Timer in a fragment and I want the timer to pause when the app is minimize(user clicks home or recent apps).
What should I do?
It seems that the fragment doesnt have onPause! The parent activity has it, which is useless because there I don't have access to the timer.
I also tried to make home button and set on click listener for it but I got null pointer exception error and when I used the code below
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
{
Log.d("IT home","clicked");
}
return super.onOptionsItemSelected(item);
}
but it doesn't work. I didn't see anything it the Log cat.
according to the documentation , fragments have an onPause method. you can use it normally like you would do in an activity.
read more about it in the documentation.
I hope this helps you.

What is the Closing event in UWP Page?

In WPF, there is a Closing event on <Window... tag, where we can hook up some dispose code in MainWindow_OnClosing.
But there is no such event in UWP app. The closing I guess is Unloaded, not even Unloading is there.
I just placed my disposing code there but still feel concerned. Is Unloaded event supposed for this type of work? Is there something I need to take note?
According to the MSDN, the Window class has a Closed event.
I'm mentioning this as you posted the Closing event of a window component, but keep in mind the remark of the event:
The Closed event occurs when a Window closes. However, Windows Store
apps typically use a single Window instance, and do not open and close
additional Window instances.
Now, when using the Frame navigation system of the main window with Pages, I advise you to use the OnNavigatedTo and OnNavigatedFrom events to manipulate all initialisation and dispose functionality of the class.
You may want to pay attention to the OnNavigationFrom as it is invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
A really simple example:
Windows.ApplicationModel.Resources.ResourceLoader loader;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
loader = new Windows.ApplicationModel.Resources.ResourceLoader();
var navigationPageContentFormat = loader.GetString("NavigationPageContent");
var navigationPageContentWhenEmpty = loader.GetString("NavigationPageContentWhenEmpty");
this.ParameterTextBlock.Text = String.Format(navigationPageContentFormat, e.Parameter?.ToString() ?? navigationPageContentWhenEmpty);
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
loader = null;
}

Callback to execute when a thread is finished

Disclaimer (fully editable/removable)
I've done my homework but to the best of my recognition, I can't see the very thing I'd like to know (which is a bit surprising, so I'm sure that a kind soul will flag me as a duplicate - please accept my apology in advance, haha).
Background and anticipated issue
When I start Outlook, I'm performing an update from CRM Dynamics, which takes a while. So, I decided to put the update in a thread. It works as supposed to but there's a button on the ribbon allowing a user to manually call for an update. Anticipating a frantic user, I realize that someone will click the button before the original update is finished and all kinds of excrement may hit the gas redistributive device.
Suggested solution
In order to avoid that, I've put a private property as follows.
private bool KeepYourPantsOn { get; set; }
As long as the said property is true (which it is set to right before I start the updating thread), all the frantic clicking will be either ignored or treated by a calm and informative
MessageBox.Show("Yes, yes... Updating still... Keep your pants on.");
but as soon as the thread is done, I'd like the property to flip over to false enabling the user to manually update Outlook.
Implementation problem
My hick-up is that I haven't found any OnFinished, WhenDone etc. method to call in order to switch the value of KeepYourPantsOn. Moreover, I haven't really seen any suggested solution on how to resolve that (or, rather - I haven't perceived any solution - I might have seen one without realizing that was it, due to ignorance within the area of threaded programming).
You should be able to just set the bool to false as the last line in your thread (or as the last line before looping back to wait on something, if your thread does that).
Note #Tudor comment regarding volatile - just to be sure, do it.
You can create a backing store for your property to hold the value and use a lock whenever you set or get the value to ensure that no concurrency issue arises.
After that, when you start processing on a separate thread, set the value to true and before exiting the method set the value to false.
On user click just check the value of KeepYourPantsOn property and display the message if it is still true.
class YourClass
{
private static readonly object _syncRoot = new object();
private bool _keepYourPantsOn;
public bool KeepYourPantsOn
{
get
{
lock(_syncRoot)
{
return _keepYourPantsOn;
}
}
set
{
lock(_syncRoot)
{
_keepYourPantsOn = value;
}
}
}
private ThreadMethod()
{
KeepYourPantsOn = true; //signal that the update process is starting...
// perform your logic
KeepYourPantsOn = false; //signal that the update process is finished
}
public ManualUpdate()
{
if(KeepYourPantsOn)
MessageBox.Show("Yes, yes... Updating still... Keep your pants on.");
else
Update();
}
}

stopping a thread when cancel command is triggered by the user

Mobile app provides the user with the option of downloading the email attachment from remote.Connecting with a remote server and downloading the content is carried out in a separate thread.A dialog is shown to the user with cancel command.Herewith I am providing the pseudo code.
new Thread(new Runnable()
public void run(){
try{
//open connection to remote server
//get data input stream
//create byte array of length attachment size
//show modeless dialog with the message "Downloading..."
for(int i=0;i<attachmentSize;i++){
//set the progress indicator of the modeless dialog based upon for iteration
//read the byte from input stream and store it in byte array
}
//open file connection outputstream and store the downloaded content as a file in mobile file system
//show dialog with the message "attachment successfully downloaded"
}
catch(IOException ioe) { }
catch(Exception ex) { }
}
).start();
Now I'm in the process of adding cancel command to the dialog with progress indicator. When the user clicks "Cancel" command in mobile, modeless dialog can be disposed by calling dispose() method. How can I abruptly stop the thread which gets the email attachments via streaming?
Please do help me to resolve this issue.
You can stop it abruptly - but it brings more trouble that it's worth.
The canonical way of doing this is to have a flag which is checked in the Runnable:
public class ClassHoldingRunnable {
private volatile boolean stopRequested = false;
public void executeAsync() {
Runnable r= new Runnable() {
public void run() {
while ( !stopRequested ) {
// do work
}
}
}
new Thread(r).start();
}
public void cancel() {
stopRequested = true;
}
}
A few notes:
it's vital for the stopRequested flag to be either volatile or to have another visibility guarantee ( synchronized, Lock, Atomic ) since it's being accessed by multiple threads;
you should check for stopRequested pretty often if it's important for the end user to have a responsive GUI;
There are several complimentary ways to interrupt a Thread that reads from a Connection.
You are probably reading the remote data by looping over a single call to InputStream.read, so you can reuse a single, relatively small, byte[] object. You can check a boolean member variable before each iteration. You don't really need to synchronize around that boolean because it is only supposed to change value once after Thread construction.
closing the Connection means that your Thread will throw a IOException when it next tries to access it. A proper JavaME implementation will not make Connection.close() block even if another Thread is reading from the Connection's InputStream.
I am not an expert on this so take my suggestion with a grain of salt, as my experience is very limited on Java threads.
You cannot stop a running thread. You can just exit it as soon as possible. So what you could do is to have, for example, a shared flag that you test periodically in the secondary thread. When the main thread sets it in response to a Cancel click, the secondary thread returns.
My experience is more in C# but this might still be applicable...
I don't think it's a good idea to find some way of just "killing a thread" any more than you would just delete an object and skip its destructor.
You could tell the thread to commit suicide via an interrupt. You can then either use the thread's interrupted flag as the indicator or, if you have a sleep/wait in there, you could catch an interrupted exception and shut down properly when this is caught (in the finally block). This should provide, more or less, what you're looking for.

j2me network connection

I have read in many places that network connection in a j2me app should be done in a separate thread. Is this a necessity or a good to have?
I am asking this because I could not find anywhere written that this must be done in a separate thread. Also, when I wrote a simple app to fetch an image over a network and display it on screen (without using a thread) it did not work. When I changed the same to use a separate thread it worked. I am not sure whether it worked just because I changed it to a separate thread, as I had done many other changes to the code also.
Can someone please confirm?
Edit:
If running in a separate thread is not a necessity, can someone please tell me why the below simple piece of code does not work?
It comes to a stage where the emulator asks "Is it ok to connect to net". Irrespective of whether I press an "yes" or a "no" the screen does not change.
public class Moo extends MIDlet {
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
Display display = Display.getDisplay(this);
MyCanvas myCanvas = new MyCanvas();
display.setCurrent(myCanvas);
myCanvas.repaint();
}
class MyCanvas extends Canvas {
protected void paint(Graphics graphics) {
try {
Image bgImage = Image.createImage(getWidth(), getHeight());
HttpConnection httpConnection = (HttpConnection) Connector
.open("https://stackoverflow.com/content/img/so/logo.png");
Image image = Image.createImage(httpConnection
.openInputStream());
bgImage.getGraphics().drawImage(image, 0, 0, 0);
httpConnection.close();
graphics.drawImage(bgImage, 0, 0, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Edit: I got my answer for the code here.
Edit: I spawned off a separate question of this here.
The problem is that you are trying to do work within the thread that is responsible for running the UI. If you do not use a separate thread, then that UI thread is waiting while you do your work and can't process any of your other UI updates! so yes you really should not do any significant work in event handlers since you need to return control quickly there.
I agree with Sean, but it is not required to have your network connection in a separate thread, just best practice. I think that it's probably coincidental that the connection worked properly after moving it to a separate thread. Either way though, if you want to provide any visual feedback to the user while the connection is happening (which you probably do considering the disparity of lag that users can experience on a mobile network), you should have the networked processing in a separate thread.
It is not mandatory that you do network connections in a new thread,however practically you'll find that it almost always a good idea to do so since network activities could block and leave your app in an unresponsive state.
This is an old article but it speaks about some of the issues involved in networking and user experience.

Resources