I'm new to Android Studio programming and I'd like to know what is the substitute for code below..
I'm trying to iterate an infinite loop that has a nested one and it seem to not work. The application still crushes when it comes to that loop.
I also tried to use non-infinite loop without nesting another inside of it.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
while (state) {
int i = 0;
while (i < person[i].length) {
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
someTextView.setText(person[i].getName());
}
});
}
i++;
}
}
This Logcat below just represents the nested while loop without
the onClickListener unlike shown in code.
2019-06-01 11:59:10.695 19529-19529/com.example.app2 I/Timeline: Timeline: Activity_launch_request id:com.example.app2 time:120814793
2019-06-01 11:59:10.771 19529-19543/com.example.app2 I/art: Enter while loop.
2019-06-01 11:59:10.789 19529-19543/com.example.app2 I/art: Enter while loop.
After entering while loop all I'm getting is a black screen on my device.
How do I use these loops within onCreate() method?
I have a few questions. If you want a infinite loop why not just:
while(true)
{
//Execute some code
}
My next question is why are you trying to do this? The reason why you are getting a black screen is cause you are stuck in an infinite loop. The code for the nested loop gets executed but because you are incrementing i outside the nested loop you will always return true, i will always be less than the length of person[]. There is nothing to render because a result is never reached. If you are looking to add onClickListeners to multiple objects the far better approach is to use a Recycler view with cards, and to assign the OnclickListeners in the Recycler adapter.
Assuming your goal is to do something repeatedly, e.g. every 1 second, you could use postDelayed(...)
// Java
Handler handler = new Handler();
int delay = 1000; // milliseconds
handler.postDelayed(new Runnable() {
public void run() {
// do something
handler.postDelayed(this, delay);
}
}, delay);
Source: How to run a method every X seconds
Related
I tried to get the width of a LinearLayout.
Here is the code of the MainActivity.java:
public class MainActivity extends AppCompatActivity {
BoardClass board;
private int widthareagame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout gamearea;
ImageView im1 ;
Button abutton;
abutton = (Button) findViewById(R.id.buttonnew);
gamearea = ( LinearLayout) findViewById(R.id.boardarea);
gamearea.post(new Runnable(){
public void run(){
widthareagame = gamearea.getWidth();
}
});
board = new BoardClass(this,widthareagame);
gamearea.addView(board);
}
The value of widthareagame at new BoardClass(this,widthareagame); is still Zero.
Thanks
Here is what documentation says about View#post():
Causes the Runnable to be added to the message queue. The runnable
will be run on the user interface thread.
Your task, of modifying the value of widthareagame variable, has been pushed to the message queue of the view. It doesn't guarantee that it will get executed at the very same instance. The control then proceeds to the next line, where you still get the unmodified value.
You can try something like this, to ensure that you are able to use the modified value:
gamearea.post(new Runnable(){
public void run(){
widthareagame = gamearea.getWidth();
board = new BoardClass(this,widthareagame);
gamearea.addView(board);
}
});
This is because post method call queued the setting of widthareagame where as your view is rendering.You didn't guarantee the order of execution.
You have to make sure the statements inside the run method execute first and then new Board(.. is invoked.For that you can do something like this
final AtomicBoolean done = new AtomicBoolean(false);
run(){
//inside run method
done.set(true);
notify();
}
then do something like this
synchronized(task) {
while(!done.get()) {
task.wait();
}
new Board(..
}
where task is your runnable task defined something like this
final Runnable task = new Runnable() {
#Override
public void run() {
The reason is zero is because within the onCreate the LinearLayout has not been measured yet.
And the reason it only works when within the Runnable is because since this one has been posted then it will run on the next execution cycle, which is after the onCreate and the rest of the Activity lifecycle methods (onStart, onResume, etc.) and even onAttachedToWindow have been called, at which point will be already measured and give the correct size.
Said all that, a safer way to get your layout metrics with certainty would be to listen when the layout state changes.
gamearea.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// Remove the listener here unless you want to get this callback for
// "every" layout pass, which can get you into an infinite loop if you
// modify the layout from within this method
gamearea.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// A this point you can get the width and height
widthareagame = gamearea.getWidth();
}
});
I need to add an artificial pause before my AI plays its turn on the tic tac toe board. However, when I try to use something like Thread.sleep, in the location where I have the comment, the entire onClick function lags. What I mean by lagging is that the ((Button) v).setText("0") does not set the button text to 0 for the amount of time I use the sleep function and the moment that the timer is up, everything happens immediately. It is like the lag happens in the beginning of the function rather than the middle where the comment is. Is there anyway to address this problem or explain why the sleep function isn't lagging where it is suppose to be?
public void onClick(View v) {
if(!((Button) v).getText().toString().equals("")){
return;
}
((Button) v).setText("0");
turn();
// Need a pause before tictacAI does anything
tictacAI("0", "X").setText("X");
turn();
if(won){
resetBoard();
won = false;
}
}
When using Thread.sleep in onClick, you are actually blocking the entire UI Thread, This will prevent Android Framework redraw your view, so your change to View's property will not be displayed.
In order to delay the execution, you should use View.postDelayed, which will post your action to a message queue and execute it later.
public void onClick(View v) {
if(!((Button) v).getText().toString().equals("")){
return;
}
((Button) v).setText("0");
turn();
// Need a pause before tictacAI does anything
v.postDelayed(new Runnable() {
#Override
public void run() {
tictacAI("0", "X").setText("X");
turn();
if(won){
resetBoard();
won = false;
}
}
}, 1000L); //wait 1 second
}
If you are using Java 1.8, you can use lambda instead of anonymous class.
Another note:
this Runnable will not be garbage collected until executed, so a long interval may cause your entire view leaked, which is very bad. Consider using View.removeCallbacks when this callback is not needed anymore(like activity's onDestroy, for example)
Ok, somewhat similar questions have been asked, but there is no answer that has made any difference in solving my problem. I've tried Thread.sleep, and also the delayed runnable. Using a Handler, etc.
I want to display a sequence of frame animations(AnimationDrawable) using the same imageview and changing the background animations as needed. The user inputs a series of 5 animations and can then play them back(if my program worked). Once the animations are selected I use a for loop that contains if statements and a switch statement to select that whatever animations were chosen and play them back.
As you might imagine, this doesn't work correctly, as the program whips through the for loop and only the first and last animation actually play. Here is the jist of the code:
for(i=0;i<5;i++){
if(conditions){
view.setBackground(chosenAnimation);
((AnimationDrawable)view.getBackground().start();
}
}
So as I said, I have tried Thread.sleep(), that doesn't do what I'm looking for. I have tried using the Handler class and putting a delay on the runnable. I have tried this:
view.postDelayed(new Runnable() {
#Override
public void run() {
//works the same without this line
((AnimationDrawable)view.getBackground()).stop();
((AnimationDrawable)view.getBackground()).start();
}
}, 1000);
None of these things do anything at all except add pauses before it does the exact same thing it did before I added this stuff. I have meticulously debugged the code and everything is working correctly. The animations have all been individually tested.
As I said, similar questions have been asked and answered and nothing offered does what I want, which is for the program to wait until one animation is finished before it runs through the for loop again.
I'd like to state again that this is a series of frame animations using AnimationDrawable and the same imageview each time. Thanks in advance!
All your animations will be started with the same delay, you should increase this delay by multiplying it by i for example. You also can count duration of every animation programmatically and increase delay as you need it.
I just tried to achieve what you want and had no problems, although my example uses 3rd party library, it's not necessary.
package com.example.masktest.app;
import android.animation.Animator;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.concurrent.atomic.AtomicReference;
import static com.dtx12.android_animations_actions.actions.Actions.*;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playAnimation();
}
});
}
private void playAnimation() {
final AnimationDrawable firstDrawable = (AnimationDrawable) ContextCompat.getDrawable(MainActivity.this, R.anim.anim_android);
final AnimationDrawable secondDrawable = (AnimationDrawable) ContextCompat.getDrawable(MainActivity.this, R.anim.anim_android_2);
final AtomicReference<Integer> cpt = new AtomicReference<>(0);
Animator sequence = repeat(6, sequence(run(new Runnable() {
#Override
public void run() {
if (imageView.getDrawable() instanceof AnimationDrawable) {
((AnimationDrawable) imageView.getDrawable()).stop();
}
imageView.setImageDrawable(cpt.get() % 2 == 0 ? secondDrawable : firstDrawable);
((AnimationDrawable) imageView.getDrawable()).start();
cpt.set(cpt.get() + 1);
}
}), delay(countAnimationDuration(secondDrawable))));
play(sequence, imageView);
}
private float countAnimationDuration(AnimationDrawable drawable) {
int duration = 0;
for (int i = 0; i < drawable.getNumberOfFrames(); i++) {
duration += drawable.getDuration(i);
}
return duration / 1000f;
}
}
You can simply using for loop and you dont need 3rd party library.
Lets say you have a LinearLayout(or any viewgroup) that you want to add these buttons dynamically. You can do something like this:
for (int i = 0; i < buttons.size(); i++) {
Button button = new Button(context);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
linearLayout.addView(button);
animateButton(button);
}
}, BUTTON_DELAY_DURATION * i);
}
Thanks to some assistance from dtx12 here, I have realized my problem, and I thought I'd leave some code here since I am not good enough to completely understand their example.
I didn't quite understand what I was doing making new threads, and it turns out I was just making 5 threads that all went off at the same time, as dtx12 explained and I eventually understood. So here's a basic way of doing this:
public void playAnimation(){
// in dtx12's answer they demonstrate how to get the
// exact duration of any give animation using
//getNumberOfFrames() and getDuration() methods of
// AnimationDrawable but I am just hardcoding it for simplicity
int duration=2000;
// This is to keep track of the animations which are in an array, I use this variable in run()
order=1;
for(int i=0;i<5;i++){
//play the first animation
if(i==0){
view.setBackground(animation[0]);
animation[i].stop();
animation[i].start();
}
else{
//Now set up the next animation to play after 2000ms, the next after 4000ms, etc.
//You are supposed to use a handler if you want to change the view in the main thread.
//it is very easy: Handler handler=new Handler():
handler.postDelayed(new Runnable(){
#Override
public void run() {
view.setBackground(animation[order]);
animation[order].stop();
animation[order].start();
order++;
}
}, duration);
//dtx12 suggestion of multiplying by i is probably smarter
duration+=2000;
}
}
}
So there you have it. Not the most elegant display of coding, but it gets the basic job done. You can't use 'i' in the run() method because it is an anonymous inner class, and if you assign the value of 'i' to another variable in the loop, it will be '4', by the time the other threads execute. So, I just did some counting inside of run to make sure everything fired in order.
I am using the android developer tools in Eclipse, programming in Java, and I need to make an object move across the screen as long as a button is pressed. I've been doing research for hours, and I cannot find any methods to accomplish this. I've tried running threads, which often crash or seemingly don't execute. I've also tried an onClickListener which reads the button state and uses it to determine whether or not the button is still pressed. I'm currently using a while loop, but this just freezes the program. I believe that this is the best method, and I've tried to use Thread.sleep in order to limit the number of iterations per second, as I believe that this is the reason it is freezing. Am I on the right track or am I way off in left field? Here is a snippet of code:
rightButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
while(arg0.isPressed())
{
mover.updateCoordinates(1, 0);
}
}
});
Would you try this another method?
Firstly declare your button as class variable, declare a Handler and a Runnable:
private Button rightButton; // You will assign this in onCreate() method
private Handler mHandler = new Handler();
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
if(rightButton.isPressed())
{
// If press state is pressed, move your item and recall the runnable in 100 milliseconds.
mover.updateCoordinates(1, 0);
mHandler.postDelayed(mRunnable, 100);
}
}
};
Then your button's onClickListener will looks like this:
rightButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0)
{
// Instead of performing a loop here, just call a runnable, do simple press state checking there.
mHandler.postDelayed(mRunnable, 100);
}
});
Create a loop that updates the views, waits, and calls itself after it finishes waiting. Within the loop, have an animation if statement with a boolean field that move on true and does not move on false. Have the onClick method toggle the boolean field's value.
Try:
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
// Start your animation here
} else if (e.getAction() == MotionEvent.ACTION_UP) {
// Stop your animation here
}
return false;
}
});
References:
MotionEvent
OnTouchListener
Alternatively, override onKeyUp and onKeyDown of the View class and check for the KEYCODE_ENTER KeyEvent
I am trying to set images with a 600ms delay using a countdown timer as follows:
protected void onCreate(Bundle savedInstanceState) {
int order[3];
index=0;
image1.setOnClickListener(this);
#Override
public void onClick(View arg0)
{
order={2,1,3};
do_switches();
}
private void do_switches()
{
new CountdownTimer(3*600, 600) {
public void onTick(long millisUntilFinished) {
switch(order[index]){
case 1:
image1.setImageResource(R.drawable.one);
break;
case 2:
image2.setImageResource(R.drawable.two);
break;
case 3:
image3.setImageResource(R.drawable.three);
break;
}
index++;
}
public void onFinish() {
}
}.start();
}
}
This is an example but in my actual code, I use larger arrays (about 50 in size). My problem is, the countdown timer does not always go all the way to the last spot in the array. Sometimes works but other times it stops before reaching the last point of my array. However if I increase the interval time to be 2000ms it always works. Its definitely some processing going on that delays this but I don't expect a countdown to not work just because I have reduced the interval. Can someone tell me what I can do to make sure the countdown timer does not stop before going through my whole array or is there a better way to do this.
I also tried using a timer with scheduleAtFixedRate but I got an error saying I cannot touch views in a thread because they were not constructed in the thread
Please help
Thanks
I'm sure there are other details involved and this may not cure everything, but for the last bit ("...cannot touch views in a thread..."), you need to pass a Runnable to Activity.runOnUiThread. In that Runnable, do your setting of image resources and anything else that will affect the screen.