EDIT:
just incase you read this i got the problem sorted i had gotten confused by my layouts and was editing the wrong one when i realised this all was sorted!
END EDIT!
every time i add a thread to my application it causes it to crash when the activity containing the thread is called below is the code piece containing the thread:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cam);
Toast t = Toast.makeText(this, "Just Click The Magnifying Glass To Search", 5000); //creates a new pop up message that lasts for 5 seconds
t.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
t.show();
bt = (ImageButton)findViewById(R.id.button); //creates instance of button
bt.setOnClickListener(search); //starts an on click listener for button
preview = (SurfaceView)findViewById(R.id.myview); //creates instance of surfaceview
previewHolder = preview.getHolder(); //creates a surfaceholder
previewHolder.addCallback(this); //sets surfaceholder callback as the activity
previewHolder.setType(3); //sets the type to SURFACE_TYPE_PUSH_BUFFERS
th = new Thread() {
public void run() {
handler.post(new Runnable() {
public void run() {
tv.setVisibility(0);
}
});
}
};
th.start();
}
if anyone could shed some light on the situation it would be greatly appreciated
EDIT:
i have got the thread working and got it to call a method which creates Toast however when i try to modify a setting of the textview it throws an NullPointerException error
I don't see initialization of TextView tv in your code (tv = (TextView)findViewById(R.id.id_of_textview);).
May be it is the cause of the problem?
To show TextView after 5 seconds, you can use handler.postDelayed()
If you're doing TextView tv = new TextView(); then this is wrong and even if you're doing TextView tv = (TextView)findViewById(R.id.tv); then the layout will not be inflated before setContentView(); so you have to initialize tv in onCreate() method.
Related
I am writing here because I have a very annoying problem in Android Studio.
My "application" is extremely simple, one page with 13 button; All I want is simple: update the first twelve buttons one by one when I click the 13th button.
I would like to see buttons updating with a little interval between each of them, but I can't understand how to do it.
I tried many tricks inside the "onClick" method but I can not figure out how to solve it; what I obtain is that after some time (the time obtained adding up the various "sleep" I put in the function) all the buttons become colored at the same time.
I put my last attempt, but if you have any other way to do that I am willing to change the way to proceed.
int[] buttonIDs = new int[] {R.id.button1, R.id.button2, R.id.button3, R.id.button4, R.id.button5, R.id.button6, R.id.button7,
R.id.button8, R.id.button9, R.id.button10, R.id.button11, R.id.button12 };
int currentI = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button goButton = (Button) findViewById(R.id.button13);
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentI < buttonIDs.length) {
Button b = (Button) findViewById(buttonIDs[currentI]);
b.setBackgroundColor(Color.parseColor("#FF22FF"));
currentI++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread t = new Thread() {
public void run() {
goButton.performClick();
}
};
t.start();
}
}
});
}
The result of this attempt is that the first button become colored and then I get "Application has stopped" error on the Android Emulator.
Thanks in advance
Use this
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 1000ms
}
}, 1000);
The basic idea here is that you need to create a new thread which signals the UI thread to update each button. In between each update, the new thread needs to wait until the UI has a chance to perform the update. I'm not very experienced with this kind of thing. You can most likely do this with a Handler. There might be more high-level tools you can use instead, but I'm not sure.
You definitely do not want to sleep the UI thread. This will only cause the UI to become unresponsive.
This question already has answers here:
How do you display a Toast from a background thread on Android?
(14 answers)
Closed 7 years ago.
my application always crash whenever it reach Toast(parent) part. i tried emptying the entire run() and there were no problem.
this codes work fine in emulator but not on device.
please ignore the Toast if you would like to, my main problem is not the Toast but its the codes onwards. they crash on device.
im merely using the Toast to know where the application crashed.
public class LoadingActivity extends Activity {
/** Duration of wait **/
private final int SPLASH_DISPLAY_LENGTH = 2000;
Intent intent;
LoadingActivity parent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_loading);
intent = getIntent();
parent = this;
ImageView logo = (ImageView) findViewById(R.id.imageView);
TextView splash = (TextView) findViewById(R.id.splash);
splash.setText(intent.getStringExtra(Constant.SPLASH_TEXT));
TranslateAnimation animator = new TranslateAnimation(logo.getX(), logo.getX(), logo.getY(), logo.getY() + 300);
animator.setDuration(2000);
animator.setFillAfter(true);
logo.startAnimation(animator);
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
//error on here
Toast.makeText(parent, "im still fine", Toast.LENGTH_LONG).show();
/* Create an Intent that will start the Menu-Activity. */
Intent nextIntent = new Intent(parent, HomeActivity.class);
nextIntent.putExtra(Constant.LOGIN_USERNAME, intent.getStringExtra(Constant.LOGIN_USERNAME));
parent.startActivity(nextIntent);
Toast.makeText(parent, "passed", Toast.LENGTH_LONG).show();
LoadingActivity.this.finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
}
You cannot use Toast(any UI related elements) inside background thread because worker thread doesn't access Ui elements , so you can use Activity.runOnUiThread(Runnable) , also you can use your Activity context to make your Toast.
Toast.makeText(LoadingActivity.this, "passed", Toast.LENGTH_LONG).show();
How to display a Toast inside a Handler/thread?
I'm having an awful time trying to get a simple Android app to work properly. I've very little experience in Java, having come from C, and I'm trying to start small with a simple clock app that will update the display every second. Here's my Java code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String currentdatetime =
DateFormat.getDateTimeInstance().format(new Date());
final TextView textview = new TextView(this);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
String currentdatetime =
DateFormat.getDateTimeInstance().format(new Date());
textview.setText(currentdatetime);
}
};
textview.setGravity(Gravity.CENTER);
textview.setTextSize(20);
textview.setText(currentdatetime);
setContentView(textview);
handler.postDelayed(runnable, 1000);
runnable.run();
}
I'm running this in Debian Linux with the Google-provided ADT bundle, and have followed all the suggestions Eclipse gives for fixing these problems, to no avail. The program compiles fine and displays exactly as I'd expect it to, except that it does not update at all. I've scoured Google as best I can and have followed many different ways of doing this, but I've not been successful.
What I'd expect this program to do is, on creation, set "currentdatetime" to the current date and time, stick it in a TextView, and then change the TextView to the main view. I'd expect it to then hit handler.postDelayed and do this again every thousand milliseconds. Clearly, though, that's not what's happening.
I'm afraid I'm completely lost. Can anyone point me in the right direction?
Well, appears that I was on rather the wrong track. I've got the code working now, rather more neatly, with the following:
protected void onCreate(Bundle savedInstanceState) {
final Handler handler = new Handler();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textview = new TextView(this);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
String currentDateTimeString =
DateFormat.getDateTimeInstance().format(new Date());
textview.setGravity(Gravity.CENTER);
textview.setTextSize(60);
textview.setText(currentDateTimeString);
setContentView(textview);
}
});
}
},1000,1000);
}
So thanks to anyone who was getting ready to answer.
All! I am pretty new to Developing Android. I have run into many issues already and solved most of them myself, and some by searching here and on other sites. The problem I currently face now, I can't seem to find a solution for. It is close to what others on here have asked, but I can't find anything for my problem.
I am working on the beginning stages of my first big app, in which a user signs in to the fist page and is then allowed access to the rest of the app and features with. I am using basic examples right now of a simple log in app and it works fine, but when I try to delay the first activity from calling the second one until the results are posted, either it posts and doesn't call the second activity, or it doesn't post the results and moves on anyways. I am also currently trying to bundle the results and display them in the second activity. I Will change that later though, I just need to see if it will work right.
Here is my code:(not sure if I'm doing this right. It's my first time!)
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Login button clicked
ok = (Button)findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.lbl_result);
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Bundle b = new Bundle();
EditText txt1 = (EditText)findViewById(R.id.editText1);
EditText txt2 = (EditText)findViewById(R.id.lbl_result);
b.putString("ID", txt1.getText().toString());
b.putString("PW", txt2.getText().toString());
final Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
final Intent myIntent = new Intent(TempActivity.this, TempActivity2.class);
myIntent.putExtras(b);
startActivity(myIntent);
}
}, 3000);
}
});
}
}, 4000);
}
Am I just going about this the wrong way? Any help is greatly appreciated! I hate being a noob! Let me know if anymore information is needed!
Ohhhh... i dont know.. if it is actually right.. but as far as i understand your code... you are using
handler1.postDelayed(new Runnable() {
and in its runnable
public void run() {
ok.setOnClickListener(new View.OnClickListener() {
here.. you are setting onClickListener.. and it will happen after 4 seconds.. because of this line..
}, 4000);
so if you click before 4 seconds.. i think onclicklistener is not being set... so give some time.. like 4 seconds after the application starts
.. and then try clicking... i think then it should work..
i'm making a 15 puzzle (http://en.wikipedia.org/wiki/Fifteen_puzzle) game, and i have an activity for user to select the background image, and then i pass that image to a new activity in order to scale and crop it.
Now i want to show the solution to the user first for 3 secs then it would shuffle, i'm using code like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//...skip the code that gets the image and scales it
start();
}
then in my start() funcion:
public void start() {
//the createPuzzle function would create all the Views(tiles)
//and add them to the root LinearLayout using addView() function
createPuzzle(game.getBoardConfig(), dimension);
//i was trying to sleep here
shuffle();
}
i used:
try {
Thread.sleep(3000);
} catch (InterruptedException e) {}
or:
SystemClock.sleep(3000);
but neither of them worked properly, they all paused the the thread right after i selected the image and when it was paused i can't see the new activity and the tiles i created. When the thread resumes, it was already showing the shuffled puzzle.
I've been looking at the documentation for quite a while but still can't figure out what's wrong with my code, thanks for helping!
Don't make the UI thread sleep because that will lock up the entire UI thread which is a no-no. Instead, use a Handler to post a runnable with a delay...like
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
shuffle();
}
}, 3000);