I want to Increment the TextView's value in Android Studio automatically but the problem i am facing is > when i run the following code it only show the app interface when the code is finished. Any Solution?
package com.example.assignment2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import static android.os.SystemClock.sleep;
public class MainActivity extends AppCompatActivity{
private TextView tv;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.t);
while(count<10000000) {
count++;
tv.setText("" + count);
}
}
}
new Thread(new Runnable(){
#Override
public void run() {
int counter = 0;
while (counter < 10000000) {
counter++;
final String counterStr = counter.toString();
tv.post(new Runnable(){
#Override
public void run() {
tv.setText(counterStr);
}
});
Thread.sleep(1000);
}
}
}).start();
The problem here is that:
On Android, there is something called Main Thread. This thread is responsible for rendering all the UI of your app, if this thread is busy with any other task (like run a while with 10.000.000 of loops) your UI will just freeze because there are no resources available to render the UI. To avoid that kind of issue, you should run the heavy part of your code in a separate thread, and all the UI updates on the main / UI thread (both are the same thing). Making these changes your code will look like that:
package com.example.assignment2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import static android.os.SystemClock.sleep;
public class MainActivity extends AppCompatActivity{
private TextView tv;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.t);
//Creating a new thread
new Thread(new Runnable() {
#Override
public void run() {
//This while will run on this new thread
while(count<10000000) {
count++;
/*To ensure that the TextView update will run on the right thread
* we should run this update inside the runOnUiThread method*/
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
tv.setText("" + count);
}
});
}
}
});
}
To learn more about thread take a look at this article:
https://developer.android.com/topic/performance/threads
Related
Upon starting my game, the game does not utilise the entire android screen. This only happens with the game itself, shown by the image as the user is unable to reach the bottom of the screen. Have tried to find a solution however all attempts I have tried seems not to work. Unsure which code to supply, and therefore do not want to provide a large amount of code. Let me know which code to post. Any help would be appreciated.
Image of game
package com.example.spaceattack;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity
{
private SpaceShipView gameView;
private Handler handler = new Handler();
private final static long Interval = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new SpaceShipView(this);
setContentView(gameView);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run()
{
handler.post(new Runnable() {
#Override
public void run()
{
gameView.invalidate();
}
});
}
}, 0, Interval);
}
}
You need to hide the status/system by getting the window of your app and set below flags:
More from Documentation
// hide status bar
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
So in your code:
public class MainActivity extends AppCompatActivity
{
private SpaceShipView gameView;
private Handler handler = new Handler();
private final static long Interval = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new SpaceShipView(this);
setContentView(gameView);
// hide status bar
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mUiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
getWindow().getDecorView().setSystemUiVisibility(mUiOptions);
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run()
{
handler.post(new Runnable() {
#Override
public void run()
{
gameView.invalidate();
}
});
}
}, 0, Interval);
}
}
I'm trying to figure out how progress bars work so i made a simple app where you have a plus and minus button which change the progress of the progress Bar. No errors in Android studio, but it crashes when launched on my phone (Honor 5X)
package net.gamepickle.rcap_new;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
int progressStatus = 50;
ProgressBar progressBar = (ProgressBar) findViewById(R.id.happiness_progress);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void run(){
Button plus = (Button) findViewById(R.id.happiness_plus);
Button minus = (Button) findViewById(R.id.happiness_minus);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(progressStatus!=100){
progressStatus += 1;
progressBar.setProgress(progressStatus);
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(progressStatus!=0){
progressStatus -= 1;
progressBar.setProgress(progressStatus);
}
}
});
}
}
Please add your stack trace.
It seems that you are calling
ProgressBar progressBar = (ProgressBar)findViewById(R.id.happiness_progress);
on the class level.
You need to split it.
Declare: ProgressBar progressBar;
and on the onCreate function:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.happiness_progress);
}
I need to collect data on an interval, here the data collection is simulated with a counting integer. I can't seem to collect that integer though. I need the collection to start after a button is clicked and end when another is clicked. Any ideas?
package com.example.test.gothedistance;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
Button start, stop;
TextView sumText;
int count;
Timer t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById((R.id.stopButton));
sumText = (TextView) findViewById(R.id.sumTV);
t = new Timer();
count = 0;
t.scheduleAtFixedRate(
new TimerTask()
{
public void run()
{
count++;
}
},0,2000);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
sumText.setText(count);
}
});
}
}
The problem is likely with the line sumText.setText(count), which uses TextView.setText(int resid). That means it's looking for an id equal to count, rather than displaying the value of count. You need to convert this value to an integer first:
sumText.setText(Integer.toString(count))
I'm a student at a community college. The following is the Main Activity in which I was tasked to generate a random number instead of the 5 milliseconds to run the sleep()method. I then have to display that random number. I figured out how to accomplish it for the first button, but I keep running into snags for the next two(converting to int, converting to a string for resultsTextView.setText();. I have tried several times to code a method, but then I'm running into other errors because onCreate is void.
package com.example.dan.hour5application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button uiThreadButton;
Button postButton;
Button asyncTaskButton;
TextView resultsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.font_size);
resultsTextView = (TextView) findViewById(R.id.textView);
uiThreadButton = (Button) findViewById(R.id.uiThreadButton);
uiThreadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/////Achieved a random number here////
Random random = new Random();
int x = random.nextInt(10);
SystemClock.sleep(x);
String aString = Integer.toString(x);
resultsTextView.setText(aString);
}
});
postButton = (Button) findViewById(R.id.post);
postButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
resultsTextView.post(new Runnable() {
#Override
public void run() {
resultsTextView.setText("Updated");
}
});
}
}).start();
}
});
asyncTaskButton = (Button) findViewById(R.id.asynctask);
class DelayTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
resultsTextView.setText("Starting AsyncTask");
}
#Override
protected void onPostExecute(Integer result) {
if (result == 0) {
resultsTextView.setText("Updated via AsyncTask");
}
}
#Override
protected Integer doInBackground(Integer... params) {
SystemClock.sleep(5000);
return 0;
}
}
}
}
I have looked at several other examples on Stack, but they aren't quite what I'm doing. I'm only starting my 4th month in Android Development, and I'm still trying to learn Java. The assignment is long gone, and my instructor didn't provide me with help when I asked. Thanks for your help!
I need some suggestions as to how I can update a Textview located in the XML with a value generated through my code.
The program draws a straight line through the canvas, I want the textView to reflect the line's tip x-value.
My code as follows:
package com.example.threadexperiment1;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
lineDrawing InfiniteLine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InfiniteLine = new lineDrawing (this);
setContentView(R.layout.activity_main);
Thread thread = new Thread(InfiniteLine);
thread.start();
RelativeLayout RL1 = (RelativeLayout)findViewById(R.id.RelativeLayout1);
RL1.addView(InfiniteLine);
}
public class lineDrawing extends View implements Runnable {
float x=100, y=100;
Paint lineColour = new Paint ();
TextView TV1 = (TextView)findViewById(R.id.textView1);
//Constructor
public lineDrawing(Context context) {
super(context);
lineColour.setColor(Color.BLACK);
}
//ondraw codes
#Override
public void onDraw (Canvas canvas){
canvas.drawLine(0,0,x,y,lineColour);
if (x==500){
x=0;
y=0;
}
invalidate();
}
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(250);
}
catch (Exception e) {}
x+=10;
y+=10;
}
}
}
}
Try textView.setText(string) within the thread.