Executing multiple activities in Android - java

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?

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();

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);

Related

Android: onCreate boolean not changing

In an android application that I am developing Im using a thread, and to make sure I dont get the "java.lang.IllegalStateException: System services not available to Activities before onCreate()" I use a boolean called donecreate. Problem is that Android studio says I have a "java.lang.NullPointerException at picLoop.run(picLoop.java:24)"
Code main class:
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class main extends Activity {
public Boolean donecreate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new eyeCanvas(this));
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
docreate();
}
public void docreate(){
donecreate = true;
}
public void checkHead(){
AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
if(am.isWiredHeadsetOn()){
Toast.makeText(getApplicationContext(), "HEADPHONES", Toast.LENGTH_LONG).show();
}
}
}
Code: pic loop
import android.graphics.Canvas;
//**Threading
public class picLoop extends Thread {
private eyeCanvas eye;
private main main = new main();
public picLoop(eyeCanvas eye) {
this.eye = eye;
}
#Override
public void run(){
Canvas c = null;
while(true) {
if(main.donecreate){ //<-- where error is
main.checkHead();
}
try {
// head.onCreate(Bundle savedInstanceState);
c = eye.getHolder().lockCanvas();
synchronized (eye.getHolder()) {
eye.onDraw(c);
}
} finally {
if (c != null) {
eye.getHolder().unlockCanvasAndPost(c);
}
}
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Also if you guys could give me feedback on how I submitted, It would help :)
You can't create activities like you're trying to do. You can NEVER EVER do 'new Activity()', as the activity needs to be launched by the system to get set up properly and go through its lifecycle as intended.
So remove the line private main main = new main();.
To do what you're trying, make the boolean a static variable.
Change
public Boolean donecreate;
to
public static Boolean donecreate;
Then you can access it like you're trying to do, without creating an instance of main Activity.
There are a large number of things wrong with the assumptions you're making. Firstly, if your Thread requires your Activity to be created, don't start it until your Activity is created. Manage the lifecycle of this object within the Activity itself, i.e.:
#Override
public void onStart() {
super.onStart();
// Start your work here
}
#Override
public void onStop() {
super.onStop();
// Stop your work here
}
Secondly, please don't use the static access approach being recommended -- that makes the assumption that there is only one Activity instance (which is wrong immediately on a configuration change, and/or if you start another instance of that Activity in the task). And even if that assumption were true, you would need to set it back to false in onDestroy() (still, don't do that).
try setting donecreate to false initially
public class main extends Activity {
public Boolean donecreate = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
....
You can request system service on application context, look at this answer.
So create a static variable in application class, initialize it like instance = this; in onCreate of Application class and then you'll be able to get app context whenever you want.

Android Timer and timerTask error

This code is too add a timer on the code.. but i am having a problem with my code when it comes to the timer code...
How will i improve the code for the timer inside the for loop of my code..
Hopefully you understand the my code.. and have improved my code.. Thanks!!!!
package com.thesis.americansignlanguage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class AlphabetCompareClass extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.alphabetcompare);
final String get;
Bundle gotWord = getIntent().getExtras();
get = gotWord.getString("key");
TextView Word = (TextView)findViewById(R.id.textView1);
final ImageView img = (ImageView)findViewById(R.id.image_alpha) ;
Word.setText(get);
for(int x = 0; x > gotWord.getString("key").length(); x++) {
final InputStream is;
Timer timer = new Timer();
TimerTask timertask = new TimerTask() {
#Override
public void run() {
try {
is = getResources().getAssets().open(get + ".png");
Bitmap bitmap = BitmapFactory.decodeStream(is);
img.setImageBitmap(bitmap);
} catch (IOException e) {
return;
}
}
};
}
};
}
Two problem found in current code:
First : Not using timer instance to schedule timerTask. do it as:
timer.schedule(timertask, 500, 3000);
Second : Updating UI from non- ui thread inside run method of TimerTask
Use runOnUiThread or Handler for updating Ui from run method of TimerTask
TimerTask runs on a different thread. Ui can be updated only from ui thread.
This img.setImageBitmap(bitmap); should be executed on the ui thread
Use runOnUiThread. You can also use a Handler. Also i do not understand the need for the for loop.
runOnUiThread(new Runnable() {
#Override
public void run() {
img.setImageBitmap(bitmap);
}
});

handler, runnable and services: I put everything together and it doesn't really work

I wanted to create a service, that runs a method after 10 seconds over and over again, until I stop it. It doesn't work. Can somebody help me?
package com.example.tauben;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Reminder extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
TimerTask task = new TimerTask() {
public void run(){
f();
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 0, 10000);
}
public void f(){
Toast t = Toast.makeText(this, "Service is still running", Toast.LENGTH_SHORT);
t.show();
}
}
And this is how I start the service.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(Log_TAG,"_____________RESTART__________");
Intent i= new Intent(this, Reminder.class);
startService(i);
}
Well I can think of 2 alternatives to what you are trying to achieve here.
1- Use TimerTask in set a repeating task that will call call the required method every 10 seconds.
2- Use setRepeating method of AlarmManager.
Both these alternatives are way better. You can google search the examples of both to get a better understanding.
Happy Coding :)
Edit:- I seem to got your original code working using Handler's postDelayed()
package com.example.tauben;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class Reminder extends Service {
Handler mHandler;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
mHandler = new Handler();
Runnable r = new Runnable() {
#override
public void run() {
f();
mHandler.postDelayed(this, 10000);
}
};
mHandler.postDelayed(r, 10000);
}
public void f(){
Toast t = Toast.makeText(this, "Service is still running", Toast.LENGTH_SHORT);
t.show();
}
}
What you have to do is bind to service and declare a method where service clients can stop the service. Inside that method you have to call handler.removeCallbacksAndMessages(null) to cancel all runable tasks.

Refreshing activity on some operation

In my activity I am receiving the messages which are stored in the database and then in the list. In my scenario activity doesn't know when the message is received so the list remain un-updated .Please suggest me how to refresh activity and keep activity alive.
Thanks.
You can refresh your listview by
myListView.invalidateViews();
and to refresh an acitvity you can use
finish();
startActivity(getIntent());
I must prefer refresh data of listview rather than refresh activity. But if you think refreshing activity is necessary for you then the following code may help you. You can use a timer which will trigger after some interval.
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private Timer RefreshActivity;
#Override
public void onResume() {
super.onResume();
RefreshActivity = new Timer();
RefreshActivity.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
refresh();
}
});
}
}, 10000, 10000); // updates each 10 secs
}
private void refresh() {
Toast.makeText(this, "update", 1).show();
//you can fetch data here and update the list if possible.
//or just finish activity and then recreate the activity
finish();
startActivity(getIntent());
}
#Override
public void onPause() {
RefreshActivity.cancel();
super.onPause();
}
}

Background changing every second

I am trying to change background every second and this is my code:
package com.example.splasher;
import java.lang.reflect.Field;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Typeface;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class Views extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.view);
final ScrollTextView scrolltext=(ScrollTextView) findViewById(R.id.scrolltext);
if(MainActivity.bold.isChecked())
{
scrolltext.setTypeface(null, Typeface.BOLD);
};
if(MainActivity.italic.isChecked())
{
scrolltext.setTypeface(null, Typeface.ITALIC);
};
if((MainActivity.italic.isChecked())&&(MainActivity.bold.isChecked()))
{
scrolltext.setTypeface(null, Typeface.BOLD_ITALIC);
};
scrolltext.setTextSize(Integer.parseInt(MainActivity.tSize[MainActivity.Size.getSelectedItemPosition()]));
scrolltext.setText(MainActivity.text);
scrolltext.setTextColor(Integer.parseInt(MainActivity.colour[MainActivity.TextColour.getSelectedItemPosition()]));
scrolltext.startScroll();
scrolltext.setBackgroundColor(Integer.parseInt(MainActivity.colour[MainActivity.BackgroundColour.getSelectedItemPosition()]));
Thread thread = new Thread()
{
public void run()
{
if(MainActivity.random.isChecked())
{
int delay = 0; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
int n=1;
public void run() {if (n==9)n=1;
scrolltext.setBackgroundColor(Integer.parseInt(MainActivity.colour[n]));
}
}, delay, period);
/*int n=1;
boolean constant=true;
while (constant==true){
if (n==10) n=1;
// int randInt = new Random().nextInt(2);
// scrolltext.setBackgroundColor(Integer.parseInt(MainActivity.colour[randInt]));
scrolltext.setBackgroundColor(Integer.parseInt(MainActivity.colour[n]));
n=n+1;
try
{
Thread.sleep(2000); // 1 second
} catch (Exception e)
{
e.printStackTrace();
}
}*/
}
}
};
thread.start();
// TextView textview=(TextView) findViewById (R.id.textView1);
// textview.setText(MainActivity.text);
// textview.setTextColor(Integer.parseInt(MainActivity.colour[MainActivity.TextColour.getSelectedItemPosition()]));
// textview.setBackgroundColor(Integer.parseInt(MainActivity.colour[MainActivity.BackgroundColour.getSelectedItemPosition()]));
// textview.setTextSize(Integer.parseInt(MainActivity.tSize[MainActivity.Size.getSelectedItemPosition()]));
// textview.setSelected(true);
}
}
But it force closes. Logcat shows: FATAL EXCEPTION: Timer-0; android.view.ViewRootŲcalledfromwrongThreadException: Only original threat that created a view hierarchy can touch its view.
What is wrong with this code?
You can not operate on the UI elements (like call scrolltext.setBackgroundColor()) in a thread separate from the so-called UI thread (which is basically the same thread onCreate() runs in.
To solve your issue, use a Handler. Create a class field:
Handler handler = new Handler();
And in your thread put all UI operations inside a Handler call:
handler.post(new Runnable() {
#Override
public void run () {
// All UI operations, like scrolltext.setBackgroundColor()
}
});
Your problem is
scrolltext.setBackgroundColor(Integer.parseInt(MainActivity.colour[n]));
You are updating UI from worker Thread(it not runs on UI Thread) and this is not allowed. Only Main(UI) Thread can manipulate with UI.
So you need to change it to runOnUiThread() or Handler.
Examples:
runOnUiThread(new Runnable(){
public void run() {
// do your stuff
}
});
Handler example.
Just trying to contribute here, but I have zero experience in android, so be cautions ;p
The exception message seems to suggest that the view can only be altered on the main thread. As you are running code which alters the view on a new thread, it doesn't like it.
Are you aware of a main Event-Dispatcher thread used in Android? Similar to how SWINGs GUI is updated on the EDT. If so, look for a way to tell the main drawing thread to do the final updates.
In swing, it would look something like:
EventQueue.invokeLater(new Runnable(){
public void run(){
}
}
Hope this has some meaning.

Categories