setContentView execute too late - android

I have a problem, I make a simple application to show you my problem.
I want that setContentView executes and displays the .xml BEFORE the Sleep is executed. I thought everything will be execute in order?
Is there anyone how can say me why it doesn't do that?
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// do something
}
Thanks a lot!
EDIT:
Here is the real OnCreate, seems to be a bigger problem.
Everything with the sleep worked fine, but with the Connect method there are problems.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectBluetooth();
}
In the ConnectBluetooth() method, I just create a new Socket and try a connection.
With a ned thread or a handler it doesn't seems to work, what should I do then? Use something like an asynctask?
Thanks a lot in common!

The layout isn't displayed until after the creation process has finished, after onResume() is called. However there is no callback for when the layout is displayed, but you can use a Handler and Runnable to do this.
Create a couple field variables:
Handler handler = new Handler();
Runnable delay = new Runnable() {
#Override
public void run() {
// Do something
}
};
And onCreate() call:
handler.postDelayed(delay, 10000);

When you call sleep, you are pausing the UI thread. This will prevent onCreate from returning, which will prevent the framework from completing initialization of your activity, including displaying your view hierarchy.
You should never pause the UI thread like that. If you want to do something after 10 seconds, you can start a separate thread that will do it at the right time:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
#Override
public void run() {
try {
Thread.sleep(10000);
doSomething();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
A cleaner approach would be to use a Handler:
Handler mHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
doSomething();
}
}, 10000);
}

Related

How android update ui

Android recommend update ui in the ui thread,but i found that i can update the ui in the non-ui thread directly like below:
public class MainActivity extends Activity {
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
new Thread(new Runnable() {
#Override
public void run() {
textView.setText("SecondThread");
}
}).start();
}
}
That's run correctly,but if i sleep the thread 1000ms:
public class MainActivity extends Activity {
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
new Thread(new Runnable() {
#Override
public void run() {
try {
**Thread.sleep(1000);**
} catch (InterruptedException e) {
e.printStackTrace();
}
textView.setText("SecondThread");
}
}).start();
}
}
I get the error"Only the original thread that created a view hierarchy can touch its views",i try to change the sleep value much times,i found when i set the value 135 or less,it can run correctly:
Thread.sleep(135);
Thread.sleep(134);
Thread.sleep(...);
That's very interesting!But why it happen?I can't find any way to make sense of that,is anyone can help me?thanks!
If you are trying to touch views from background thread you should consider using runOnUiThread method, which accepts runnable as argument in which you can update views
EDIT: Also I would recommed you to use AsyncTask to achieve your goals, it has two callbacks onPreExecute and onPostExecute, whiche are invoked on the UI thread
so will always work
new Thread(new Runnable() {
#Override
public void run() {
try {
**Thread.sleep(1000);**
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runable(){
#Override
public void run(){
textView.setText("SecondThread");
});
}
}).start();
There is another way to use the Handler()

Intro of loading screen

At the app I'm developing, I'm interested in an intro of a loading screen. Which automatically move to the next screen after a duration.
The intro itself, is working just fine. As well as the thread who delaying the system.
My problem is to make them work together.
The code:
public class MainActivity extends Activity implements OnClickListener {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_screen);
final Thread t1=new Thread(new Runnable() {
public void run() {
iv=(ImageView)findViewById(R.id.imgBtn1);
iv.setBackgroundResource(R.anim.loading_i_animation);
AnimationDrawable anim=(AnimationDrawable) iv.getBackground();
anim.start();
}
});
t1.start();
try {
Thread.sleep(2000);
finish();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
Intent st=new Intent(MainActivity.this,Welcome.class);
startActivity(st);
}
}
The result of this code is opening a white screen for the thread sleep-time duration. and after that open the "Welcome.class" screen via the intent.
It's just skipping the loading_screen, as is wasn't even exist.
I hope you guys could please help my with that.
You put your sleep on the UI thread which prevents Android to show anything until it finishes. Try the following code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_screen);
iv=(ImageView)findViewById(R.id.imgBtn1);
iv.setBackgroundResource(R.anim.loading_i_animation);
AnimationDrawable anim=(AnimationDrawable) iv.getBackground();
anim.start();
new Handler().postDelayed(
new Runnable() {
public void run() {
Intent st=new Intent(MainActivity.this,Welcome.class);
startActivity(st);
finish();
}
}, 2000);
}
This way the delay will run on a separated thread, but after 2 seconds it changes back to the main thread and runs the code you specified in your Runnable

Is there a way I can put some delay in setcontentView in android?

I have a SetContentView(R.layout.camera);
I want this layout to be start executing after some milliseconds....till then it should be blank. How can I achieve this in android?
For this Write your onCreate() like this..Then it will work..
Thread t = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
t = new Thread(new Runnable() {
#Override
public void run() {
try {
t.sleep(5000);
runOnUiThread(new Runnable() {
public void run() {
setContentView(R.layout.activity_main);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
}
you can use handler for make delay
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
//setcontentview
}
};
in oncreate methode
Message m = Message.obtainMessage();
handler.sendMessageDelayed(m, delayMillis);
Your activity will not be visible unless onResume() will get called, Do some operation in main Thread or onCreate() Method it will block your main thread and UI will not be displayed until your operation gets completed.
Create root View with all the components and visibility set to INVISIBLE or GONE and then show it after delay. You can use Handler and postDelayed to execute a code after delay.

How to wait for an activity to fully load?

I'm making an activity where I'm planning to display a progress bar and move to a second activity after five seconds. I used Thread.sleep to do this.
Here is the code for the activity with the spinner.
public class WaitScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.waitscreen);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
try{
for(int i=0;i<5;i++){
Thread.sleep(1000);
}
Toast.makeText(getApplicationContext(), "Spinner complete!", Toast.LENGTH_LONG).show();
}
catch(InterruptedException e){
}
Intent i = new Intent("emergency.app.NEWACTIVITY");
startActivity(i);
}
}
My main activity only has a button that leads to this page on being clicked. Problem is, it displays the main activity for five seconds, then this activity very briefly and then the third activity. How do I make the thread start after WaitScreen is fully loaded? As you can see, I tried using the onStart method to do the trick. Or if you could tell me another way to introduce a five second delay, that would be helpful too!
Use a Handler to post a Runnable, like so:
public class WaitScreen extends Activity {
private Runnable task = new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Spinner complete!", Toast.LENGTH_LONG).show();
Intent i = new Intent("emergency.app.NEWACTIVITY");
startActivity(i);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waitscreen);
Handler handler = new Handler();
handler.postDelayed(task, 5000);
}
}
The Runnable task will execute after 5 seconds.
http://developer.android.com/reference/android/os/Handler.html

I am trying to make a simple thread that changes a textview after a time

The problem is that when i click the button for the second my application crashes and i don't understand why. When i clink the button for the second time is suppose to the same all over again.
Any help is appreciated.
public class main extends Activity {
Boolean grabar = false;
TextView texto;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
texto = (TextView) findViewById(R.id.texto);
Button startbtn = (Button) findViewById(R.id.button);
startbtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
background.start();
}
});
}
Thread background = new Thread (new Runnable() {
public void run() {
try {
Thread.sleep(3000);
cambiarHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Handler cambiarHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
texto.setText("ok");
}
};
}
The problem I see is that threads are designed to run once. You need to create a new instance of the thread each time you wish to run it.
This may well have something to do with Android's policy of only allowing the UI thread to modify the UI.
You should be using ASyncTask instead if you want to modify the UI from a separate thread.
See here:
Update UI from Thread
I don't know which exception is thrown. I guess it is NPE thrown. When you try to set text to the TextView. Try instantiating the TextView within the handleMessage() method:
Handler cambiarHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
texto = (TextView) findViewById(R.id.texto);
texto.setText("ok");
}
};
And in the onClick method do this to have new instance of the thread each time button is clicked.
public void onClick(View v){
new Thread (new Runnable() {
public void run() {
try {
Thread.sleep(3000);
cambiarHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}

Categories

Resources