I'm trying to append letters from a specific string onto a TextField. This is what I've tried so far. But no luck.
What happens here is it just waits for 100 milliseconds and then displays the string directly.
outConsole = (TextView) findViewById(R.id.outconsole);
int i, j;
String fin = "";
final String in = "HELLO!";
i = in.length;
try{
for(j = 0; j < i; j++){
Thread.sleep(100);
fin = fin + in.charAt(j);
outConsole.setText(fin);
}
}catch(Exception e){}
}
How do I achieve this?
I would like something like this but slower:
https://www.youtube.com/watch?v=Ff-eDOGLuYw
Try using Handlers. Something like this should work:
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
//update your ui
handler.postDelayed(this, 100);//this restarts the handler better to have some terminating condition
}
};
handler.postDelayed(runnable, 100);//starts the handler first time
Related
I have two options to execute my program (I need to have Out_str as a result).
Option 1:
Out_str = "";
for (i = 1; i <= 20000; i++) {
Out_str = Out_str + "word";
}
Option2:
Runnable runnable1 = new Runnable() {
public void run() {
Out_str1 = "";
for (i1 = 1; i1 <= 10000; i1++) {
Out_str1 = Out_str1 + "word";
}
}
};
Runnable runnable2 = new Runnable() {
public void run() {
Out_str2 = "";
for (i2 = 1; i2 <= 10000; i2++) {
Out_str2 = Out_str2 + "word";
}
}
};
Thread thread1 = new Thread(runnable1);
thread1.start();
Thread thread2 = new Thread(runnable2);
thread2.start();
Why using threads does not make my program execute faster (in both cases the execution takes approx 12 sec with my laptop)? What shall I use in this case (to make it faster to obtain Out_str)? Will using services make help in this case?
The Thread allows you to run processes concurrently. You haven't gained any processing power though, with equal priority your threads would be run in a round-robin way I would guess.
I'm working on a school project in Android Studio and so far I've written a code which generates a random equation and then display this equation in a textview. Here is the code:
String[] operationSet = new String[]{"+", "-", "/", "*"};
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation = "";
for (int i = 0; i < numOfOperations; i++) {
equation += numbers.get(i);
equation += operations.get(i);
}
equation += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView3);
TextEquation.setText(equation);
String stringResultOfEquation = String.valueOf(equation);
// Resultat der Rechung berechnen
double doubleAnswer = eval(stringResultOfEquation);
String stringAnswer = Double.toString(doubleAnswer);
TextView textAnswer = (TextView)findViewById(R.id.textView4);
textAnswer.setText(stringAnswer);
So far I've tried to use the TimerTask command:
TimerTask timerTaskWaiting = new TimerTask() {
#Override
public void run() {
}
};
Timer timerwaiting = new Timer();
timerwaiting.schedule(timerTaskWaiting, 5000);
I've put the "equation generater code" and put it into "public void run(){...}" but the app crashed when I tried it out.
My question now is, if there is a simple way which will generate the equation after a certain amount of time (for example 5 seconds) I mean, I want that the equation will be generated 5 seconds after the app is launched.
If there is anything unclear in my question, feel free to ask and I will try to clarify the problem :)
Thank you already in advance for your help!
This bit of code should suffice for you to understand what you need to do. obviously there are other ways you can achieve this.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
generateAndDisplayEquation();
}
}, 5000);
}
Use RxJava library, it is very easy tool to organize periodic tasks.
**bluetoothdatadisplay**
void beginListenForData() {
//final Handler handler = new Handler();
final Handler handler = new Handler(Looper.getMainLooper());
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[2048];//It uses a 1024 bytes long buffer because it doesn't have any way of knowing the length of the input stream.
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
//Log.d("MyLabel", data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
}//end of begindata
Hi I trying to receive the data from Arduino, But when I send all my data were flashing very fast since there is only one textview use. How do I separate them in Android for eg into different textbox? Thanks!
A simple fix would be to append the newly received data instead of replacing the old one.
Use a RecyclerView, with a List<String> representing your data set and connected to the Adapter of the RecyclerView :-)
Each time you add something to the data list, use
adapter.notifyDataSetChanged()
method to have the RecyclerView update :-)
EDIT:
As stated by Kernald, you should actually use the
adapter.notifyItemInserted(list.size())
method instead of notifying the whole data set change, if you want to use a 100% correct and up-to-time approach :-)
How is it possible to make an app that changes between color automatically after specific time. My code doesn't work for some reason
Random r = new Random();
Timer t = new Timer();
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
long m = System.nanoTime();
int seconds = (int) (m/1000);
if(seconds <= 5){
ll.setBackgroundColor(Color.BLACK);
}else{
ll.setBackgroundColor(Color.WHITE);
}
For ex. the screen is black and after specific time white. And that the time decreases itslef, the changing goes faster.
Please try the following code for the color change.
Use the countdown timer for changing the color with condition.
new CountDownTimer(5000,1000)
{
onFinish()
{
if(flag==1)
{
//color set black
flag=0;
//start the countdown timer again.
}
else
{
//color set white
flag=1;
//start the countdown timer again.
}
}
}
Try following the code
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
//Adding Log Statement to check
Log.i(Tag, String.valueOf(seconds);
if(seconds % 10 < 5){
ll.setBackgroundColor(Color.BLACK);
}else{
ll.setBackgroundColor(Color.WHITE);
}
You are trying to convert nanoseconds to seconds, but actually you are doing is not the same!!
try
int seconds = (int) (m/1000000000);
to convert to nan0-seconds to seconds
EDIT:
if you just want to keep changing color use this code:
public static int color = 1;
android.os.Handler customHandler = new android.os.Handler();
customHandler.postDelayed(updateTimerThread, 0);
and its definition:
private Runnable updateTimerThread = new Runnable()
{
public void run()
{
//write here whaterver you want to repeat
if(color == 1){
ll.setBackgroundColor(Color.BLACK);
color = 2;
}else{
ll.setBackgroundColor(Color.WHITE);
color = 1;
}
customHandler.postDelayed(this, 5000);// will repeat after 5 seconds
}
};
You can use tread to manage this, try this . thread will be the best way to achieve this, since you want to continuously change the color at regular interval.
Handler handler ;
LinearLayout ll ;
int i = 0;
int colors[] = {Color.BLACK, Color.WHITE, Color.BLUE, Color.GREEN, Color.GRAY};
Runnable runnable = new Runnable() {
#Override
public void run() {
ll.setBackgroundColor(colors[i]);
i++;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
......
.......
handler = new Handler();
ll = (LinearLayout) findViewById(R.id.ll);
Thread myTread = new Thread(){
public void run() {
try {
while(true){
sleep(3000);
handler.post(runnable);
}
}
catch (InterruptedException e) {}
}
};
myTread.start();
}
the code will change the background color every 3secssleep(3000) as written in the code. also each time it changes it select from a set of pre-define color array.
you can also use random generation of colors. either you randomly generate the rgb values or you can store the colors in an array as i have done and randomly iterate over it
Below I am posting my code for the thread I am running to animate text in a RelativeLayout on top of the Page Curl activity by harism.
public void startProgress(final int index)
{
runnable = new Runnable()
{
#Override
public void run()
{
mArrWords.removeAll(mArrWords);
mStart.removeAll(mStart);
mEnd.removeAll(mEnd);
words = sentence.split(" ");
for(int i = 0; i < words.length; i++)
{
mArrWords.add(words[i]);
if(i == 0)
{
mStart.add(0);
mEnd.add(words[0].length());
}
else
{
mStart.add(mEnd.get(i-1)+1);
mEnd.add(mStart.get(i)+words[i].length());
}
/*Log.e("words", "" + "" + words[i]);
Log.e("mArrWords", "" + mArrWords);
Log.e("mStart", "" + mStart);
Log.e("mEnd", "" + mEnd);*/
}
for (int i = 0; i < mArrWords.size(); i++)
{
final int value = i;
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
mHandler.post(new Runnable()
{
#Override
public void run()
{
currIndex = index;
try
{
if(CurlView.ANIMATE)
tv1.setVisibility(View.VISIBLE);
else
tv1.setVisibility(View.GONE);
final Pattern p = Pattern.compile(mArrWords.get(value));
final Matcher matcher = p.matcher(sentence);
SpannableString spannableTxt = new SpannableString(sentence);
ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
while(matcher.find())
spannableTxt.setSpan(span, mStart.get(value), mEnd.get(value), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv1.setText(spannableTxt);
mHandler.sendEmptyMessage(0);
}
catch (Exception e)
{
e.printStackTrace();
mHandler.sendEmptyMessage(0);
}
}
});
}
}
};
final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
worker.schedule(runnable, CurlView.ANIMTIME+50, TimeUnit.MILLISECONDS);
}
Here, I am animating the text over images. I need to change the text for each page I am changing. I am able to change the text, however, when I turn the page, the index values I store in ArrayLists are not getting cleared. I am storing a sentence in an ArrayList named mArrWords and the indexes to refer to each word of sentence are stored in mStart and mEnd.
The problem I am facing is when the text changes, the animation starts with the previous indexes stored in mStart and mEnd ArrayLists I use to store index of a particular word. What I need to know is how do I stop my thread when the page is turned or the index of the page changes. I am calling this function inside the updatePage(final CurlPage page, final int width, final int height, final int index) method of Curl activity. I hope I was able to explain my problem. Thanks!
EDIT: I would like to specify my question more clearly. How do I check if the thread is already running before starting another thread and stop the execution of the previous thread?
removeCallbacks(..) only stops pending messages (Runnables).If runnable is started then u can not stop it in this way. See the following :
removecallbacks-not-stopping-runnable