Reputation: 1970
I was trying to execute one activity after executing another,by using threads and using sleep method of thread class. Here is the code,
package com.example.admin.myapplication;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layo);
Thread th=new Thread() {
public void run()
{
try
{
Thread.sleep(3000);
}
catch(InterruptedException i)
{
i.printStackTrace();
}
finally
{
Intent io=new Intent("com.example.admin.myapplication.NEWATTEMPT");
startActivity(io);
}
}
};
th.start();
}
Code for layo.xml is-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/pic">
</LinearLayout>
and NewAttempt is another java class-
My question here is this- In line no. 16 of MainActivity,I am setting the content to layo.xml,and after that I am creating an instance of thread class and starting it, but,If I put setContentView(R.layout.layo) in the try block,then its showing an error,on starting the application.Why is it so??Can somebody explain why?
And can somebody please explain how an execution happens in android,i.e,order in which files are read?I am a beginner in Android and I doesn't have much idea how the control flows from one activity to another?
Upvotes: 0
Views: 61
Reputation: 198
If you want to make a splash screen model activities, then try timer() class and schedule it. try this code inside onCreate() method eg:
Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Intent intent=new Intent(MainActivity.this, NEWATTEMPT.class);
startActivity(intent);
}
},1000);
Upvotes: 0
Reputation: 3043
Whenever you want to modify your view inside Activity, you need to do it on your activity(ui) thread. UI thread is synchronized. Activity has a method that can handle your Runnable
runOnUiThread(new Runnable() {
@Override
public void run() {
//your method that modify view
}
});
In your case, you can put method above inside your thread
Thread th = new Thread() {
public void run()
{
try
{
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//your method that modify view
MainActivity.this.setContentView(R.layout.layo);
}
});
Thread.sleep(3000);
}
catch(InterruptedException i)
{
i.printStackTrace();
}
finally
{
Intent io = new Intent("com.example.admin.myapplication.NEWATTEMPT");
startActivity(io);
}
}
};
th.start();
Upvotes: 1