currently developing an app where I need to take a number of wifi measurements, take an average of these measurements and store the averages. However I've found that I have to implement a delay between measurements otherwise there's not enough time to see any variation between measurements.
In the Handler.postDelayed() method I've tried to implement a 2000ms delay, however when I view the timestamp of the logs generated by TAKEWIFI, there appears to be no delay at all.
Any help would be greatly appreciated :)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_takewifi);
final String[] strArr = new String[60];
for (int i=0;i<60;i++)
{
strArr[i] = "EMPTY";
}
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
final int state = wifi.getWifiState();
if(state == WifiManager.WIFI_STATE_ENABLED) {
RawData rD = new RawData();
Toast.makeText(TakeWifi.this,
"Taking RSS measurement, hold still!",
Toast.LENGTH_SHORT).show();
for(int a=0;a<30;a++)
{
wifi.startScan();
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 2000);
}
});
List<ScanResult> results = wifi.getScanResults();
String index = (String) results.toString();
int forCount = 0;
int ifCount = 0;
for (String retval: index.split(",")){
if (((forCount%5==1)||(forCount%5==3))&&(ifCount<60)){
strArr[ifCount] = retval;
strArr[ifCount] = strArr[ifCount].replace(" BSSID:", "BSSID:");
strArr[ifCount] = strArr[ifCount].replace(" level:", "level:");
ifCount++;
}
forCount++;
}
for(int check=0;check<60;check++)
{
Log.d("TAKEWIFI","strArr[" + check + "]: " + strArr[check]);
}
rD.setStrArr(strArr,rD);
}
final String[] temp = rD.getStrArr(rD);
for(int b=0;b<20;b++)
{
strArr[b]=temp[b];
}
for(int i=0;i<20;i++)
{Log.d("STRARR",strArr[i]);}
List<String> stringList = Arrays.asList(temp);
for (int i = 0; i < 20; i++) {
Log.d("STRLIST",stringList.get(i));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stringList);
ListView listview = (ListView) findViewById(R.id.listview);
if (listview==null)
{
Log.d("LISTVIEW","NULL");
}listview.setAdapter(adapter);
Toast.makeText(TakeWifi.this,"RSS measurement complete",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(TakeWifi.this,"Wifi Not Enabled",Toast.LENGTH_SHORT).show();
}
final Button commitBut=(Button)findViewById(R.id.button4);
commitBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(state == WifiManager.WIFI_STATE_ENABLED){
commit(strArr);
}
else
{
Toast.makeText(TakeWifi.this,"Wifi Not Enabled",Toast.LENGTH_SHORT).show();
}
}
});
}
Replace your handle with this and put everything you want delayed into it.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Everything you want to be delayed needs to go inside this runnable
}
}, 2000);
You are waiting in another thread (hence the run() method in your handler) :) Try removing that whole handler magic and call Thread.sleep directly.
Related
I'm working on a tank-game and I have a TextView which represents the shot. Now I want to display the TextView at the specific point and remove it after a second that it looks like the shot goes further step by step. But when I add a countdown or a Thread.sleep the program stops for a second but the TextView doesn't disappear. i want to move the TextView over the screen and after every iteration of my for loop i want to wait a second and then rearrange it again?
Here is the code :
public void shot(float power, float winkel, Button button) {
if(winkel>90) {
winkel = winkel - 10;
}else if(winkel<90){
winkel = winkel +10;
}
for (double i = 0; i<100;i = i+ 1) {
final TextView textView = new TextView(context);
textView.setText(".");
double x = tanks.get(currentTank).getxPos()+(i*power*Math.cos(winkel *(Math.PI/180)));
double y = tanks.get(currentTank).getyPos()+(-1*(i*power*Math.sin(winkel *(Math.PI/180))));
double gravity = (-1*((9.81/2)*Math.pow(i,2)));
y = (y-gravity);
textView.setX((float) x);
textView.setY((float) y);
layout.addView(textView);
for (int j = 0;j<tanks.size();j++){
if(textView.getX()>tanks.get(j).getxPos()&&textView.getX()<tanks.get(j).getxPos()+100){
if(textView.getY()>tanks.get(j).getyPos()&&textView.getY()<tanks.get(j).getyPos()+100){
float k = tanks.get(j).getxPos()-textView.getX();
if(k<0){
k = k*-1;
}
makeDamage(k,tanks.get(j));
}
}
}
new CountDownTimer(2000,1000){
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
layout.removeView(textView);
}
}.start();
}
newTurn();
}
I want to pause the program after adding the TextView for one second and the remove it. The program stops but the TextView doesn't disappear till the for-loop finished. Then all TextViews disappear.
Problem solved:
i've added all positions in a array and then this
public void drawShot(final Button firework, final ArrayList<TextView> toDraw){
final int[] i = {0};
final Handler mHandler = new Handler();
firework.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
firework(firework,toDraw.get(i[0]).getX(),toDraw.get(i[0]).getY());
}
});
Runnable runnable = new Runnable() {
#Override
public void run() {
layout.addView(toDraw.get(i[0]));
if(!check(toDraw.get(i[0]))) {
mHandler.postDelayed(this, (long) 1);
}
i[0]++;
}
};
// start it with:
mHandler.post(runnable);
}
probably need to run the remove command on main thread
Handler mainHandler = new Handler(context.getMainLooper());
Runnable myRunnable = new Runnable() {
#Override
public void run() {
layout.removeView(textView);
}
};
mainHandler.post(myRunnable);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
take = getIntent();
levelone = take.getIntArrayExtra("level1");
take = getIntent();
leveltwo = take.getIntArrayExtra("level2");
take = getIntent();
levelthree = take.getIntArrayExtra("level3");
colors[0] = (R.drawable.blue1);//Suppose to give integer value for the colors
colors[1] = (R.drawable.purple1);
colors[2] = (R.drawable.yellow1);
colors[3] = (R.drawable.green1);
colors1[0] = (R.drawable.blue);//Suppose to set the colors back to origin
colors1[1] = (R.drawable.purple);
colors1[2] = (R.drawable.yellow);
colors1[3] = (R.drawable.green);
purple = findViewById(R.id.purplee); //1
green = findViewById(R.id.greenn);//2
yellow = findViewById(R.id.yelloww);//3
blue = findViewById(R.id.bluee);//4
for (int i = 0; i < btn.length; i++) {
buttons[i] = findViewById(btn[i]);
buttons[i].setOnClickListener(this);
}
/*new CountDownTimer(5000,1000)//5000=5sec to wait and 1000=1sec for interval
{
// loop for timer
#Override
public void onTick(long l) {
Toast.makeText(Main.this, ""+l/1000, Toast.LENGTH_SHORT).show();
}
//what happend after finish 5 sec
#Override
public void onFinish() {
Intent go=new Intent(Main.this,Start.class);
startActivity(go);
}
}.start();*/
new CountDownTimer(2000,500)//5000=5sec to wait and 1000=1sec for interval
{
// loop for timer
#Override
public void onTick(long l) {
buttons[1].setBackgroundResource(colors1[1]);//purple Butttons[1]
buttons[2].setBackgroundResource(colors1[2]);//Yellow Buttons[2]
buttons[3].setBackgroundResource(colors1[3]);//Green Buttons[3]
buttons[0].setBackgroundResource(colors1[0]);//Blue Buttons[0]
}
//what happend after finish 5 sec
#Override
public void onFinish() {
}
}.start();
I want to change the buttons color by delay so I ran a couple of options to do so and none of them worked, I mean I didn't see the delay and the color of the buttons didn't change as it supposed to so how should I do that? In the code, I have tried something but it didn't work so if you have any ideas I will be happy to hear.
You can use a handler
Handler handler = new Handler();
for(int i=0; i<btn.size; i++){
handler.postDelayed(new Runnable() {
#Override
public void run() {
buttons[i].setBackgroundResource(colors1[i]);
}
},1000); // Delay every "1" second
}
//Write This Code Inside onCreate Methode
Timer timer = new Timer();
MyTimer myTimer = new MyTimer();
timer.schedule(myTimer, 1000, 1000);
//Make this Class Outside onCreate Methode
class MyTimer extends TimerTask {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Random random = new Random();
for (int i = 0; i < btn.size; i++) {
buttons[i].setBackgroundColor(Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256)));
}
}
});
}
}
I want the Text in a TextView to be displayed word after word or even letter after letter, just like in most rpgs and adventures with textboxes. A good example how the textflow should look like is the game phoenix wright ( http://youtu.be/2OOX2Gv0768?t=1m7s )
What i have tried until now is this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String text = "test test test test";
String[] split = text.split(" ");
Deque<String> words = new LinkedList<String>();
for (int i = 0; i<split.length; i++)
{
words.addLast(split[i]);
}
showNextWord(words);
}
public void showNextWord(final Deque<String> words)
{
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
TextView t = (TextView) findViewById(R.id.textBox);
t.append(words.pollFirst()+" ");
if (words.size()>0)
showNextWord(words);
}
}, 500);
}
I tested on an emulator and it seems to be with low performance, even more if i would start a delay after displaying each letter. The delay isnĀ“t consistent.
In addition to that I hope there is a more elegant solution to that. Maybe some way to be more flexible with the delays? E.g. a bigger delay after a sentence and so on.
Thank you very much!
public class Typewriter extends TextView {
private CharSequence mText;
private int mIndex;
private long mDelay = 500; //Default 500ms delay
public Typewriter(Context context) {
super(context);
}
public Typewriter(Context context, AttributeSet attrs) {
super(context, attrs);
}
private Handler mHandler = new Handler();
private Runnable characterAdder = new Runnable() {
#Override
public void run() {
setText(mText.subSequence(0, mIndex++));
if(mIndex <= mText.length()) {
mHandler.postDelayed(characterAdder, mDelay);
}
}
};
public void animateText(CharSequence text) {
mText = text;
mIndex = 0;
setText("");
mHandler.removeCallbacks(characterAdder);
mHandler.postDelayed(characterAdder, mDelay);
}
public void setCharacterDelay(long millis) {
mDelay = millis;
}
}
And use above class in your activity like this:
Typewriter writer = new Typewriter(this);
//Add a character every 200ms
writer.setCharacterDelay(200);
writer.animateText("Sample String");
Try this:
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
if (words.size()>0)
showNextWord(words);
}
}, 500);
public void showNextWord(words)
{
TextView t = (TextView) findViewById(R.id.textBox);
t.append(words.pollFirst()+" ");
}
Alright here is what I came up with!
public static void main(String[] args) {
printWord("Sup dude!", 150);
}
public static void printWord(String word, int time){
for(int i = 0; i < word.length(); i++){
double start = System.currentTimeMillis();
double end = System.currentTimeMillis();
while(end - start <= time){
end = System.currentTimeMillis();
}
System.out.print(word.charAt(i));
}
}
I bet you can easily can the print to your textview by changing the syso to:
tv.setText(tv.getText() + word.charAt(i));
Hope that answers your question and helps! Good luck :)
Take a look at this Library: https://github.com/flavienlaurent/spans It has a feature called typewriter that might suit your needs. You can see it in action in this blog post: http://flavienlaurent.com/blog/2014/01/31/spans/
I've searched the internet far and wide about getting the UI to update in real-time in Android to no avail. I implemented an AysncTask class as most of the other posts suggested, but it's still not updating my UI in real-time like I want. It only updates after the program is done running. I've even been getting the "Skipped n frames. The application may be doing too much work in its main thread." error, which I don't understand because I'm trying to do these updates in the UI thread. About 5 seconds into running my program the screen turns black and stays like that until its done finishing. Any help would be much appreciated as I've been pulling my hair out on this one for awhile Here's my code.
EDIT: Solved. Removed the Thread.sleep(n) from my UI thread and added it to my AsyncTask. Thanks everyone!
Main class:
public class Home extends Activity {
// Declare objects
Button turingB, socratesB, voltaireB, descartesB, platoB;
int[] eating, thinking, hungry;
Philosopher socrates, turing, voltaire, descartes, plato;
Philosopher[] philosophers;
Chopstick[] chopsticks;
TextView info;
String value;
Context context;
int toastLength;
boolean turingHungry, socratesHungry, voltaireHungry, descartesHungry, platoHungry;
String running;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Instantiate objects (keep track of each button individually
context = getApplicationContext();
toastLength = Toast.LENGTH_SHORT;
info = (TextView) findViewById(R.id.textView1);
info.setText("Click Start to begin!");
socratesB = (Button) findViewById(R.id.button1);
descartesB = (Button) findViewById(R.id.button5);
platoB = (Button) findViewById(R.id.button4);
voltaireB = (Button) findViewById(R.id.button3);
turingB = (Button) findViewById(R.id.button2);
running = "false";
// Set all philosophers to thinking (blue)
// socratesB.setBackgroundColor(Color.BLUE);
// descartesB.setBackgroundColor(Color.BLUE);
// platoB.setBackgroundColor(Color.BLUE);
// voltaireB.setBackgroundColor(Color.BLUE);
// turingB.setBackgroundColor(Color.BLUE);
turingHungry = false;
socratesHungry = false;
voltaireHungry = false;
descartesHungry = false;
platoHungry = false;
//Button platoTempButton = (Button) findViewById(R.id.button4);
// Listen for buttons
OnClickListener pBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
platoHungry = true;
}
};
//platoTempButton.setOnClickListener(pBtn);
OnClickListener tBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
turingHungry = true;
}
};
OnClickListener sBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
socratesHungry = true;
}
};
OnClickListener vBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
voltaireHungry = true;
}
};
OnClickListener dBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
descartesHungry = true;
}
};
platoB.setOnClickListener(pBtn);
turingB.setOnClickListener(tBtn);
socratesB.setOnClickListener(sBtn);
voltaireB.setOnClickListener(vBtn);
descartesB.setOnClickListener(dBtn);
// Set arrays to count time spent eating, thinking, hungry
eating = new int[5];
thinking = new int[5];
hungry = new int[5];
// Create the chopsticks
chopsticks = new Chopstick[5];
for (int i = 0; i < 5; i ++)
{
chopsticks[i] = new Chopstick(i);
}
for (Chopstick chop: chopsticks)
{
chop.available = true;
}
// Create the philosophers
philosophers = new Philosopher[5];
philosophers[0] = new Philosopher(0, chopsticks[0], chopsticks[1], "Plato", platoB);
philosophers[1] = new Philosopher(1, chopsticks[1], chopsticks[2], "Turing", turingB);
philosophers[2] = new Philosopher(2, chopsticks[2], chopsticks[3], "Socrates", socratesB);
philosophers[3] = new Philosopher(3, chopsticks[3], chopsticks[4], "Voltaire", voltaireB);
philosophers[4] = new Philosopher(4, chopsticks[4], chopsticks[0], "Descartes", descartesB);
// Get sim time from user
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Simulation Time");
alert.setMessage("Please length of time for the simulation to run (in seconds)");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
value = String.valueOf(input.getText());
}
});
alert.show();
// Get info
Bundle extras = getIntent().getExtras();
if (extras != null)
{
running = extras.getString("runApp");
value = extras.getString("numToRun");
}
// Run app
if (running.equals("true"))
{
System.out.println("RUNNING!!!");
run(value);
}
}
public void run(String length)
{
int num = Integer.parseInt(length);
// Run num times
for (int i = 0; i < num; i++)
{
try {
// Pass current index, and data arrays to step method
step(i, eating, thinking, hungry);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Print out some data
for (int j = 0; j < 5; j++)
{
System.out.println("Philosopher " + j + " ate: " + eating[j]);
System.out.println("Philosopher " + j + " thought: " + thinking[j]);
System.out.println("Philosopher " + j + " was hungry: " + hungry[j]);
}
running = "false";
}
// Run simulation n times (n specified by the user)
public void startSim(View v)
{
Intent my_intent = new Intent(this, Home.class);
my_intent.putExtra("runApp", "true");
my_intent.putExtra("numToRun", value);
startActivity(my_intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
// Reset simulation
public void reset(View v)
{
Intent my_intent = new Intent(this, Home.class);
startActivity(my_intent);
}
// Return hunger status of philosopher
public boolean isHungry(String name) {
if (name.equals("Voltaire"))
return voltaireHungry;
else if (name.equals("Socrates"))
return socratesHungry;
else if (name.equals("Plato"))
return platoHungry;
else if (name.equals("Turing"))
return turingHungry;
else if (name.equals("Descartes"))
return descartesHungry;
else
return false;
}
// Step method for simulation
// Takes the current index and each of the data arrays
public void step(int i, int[] eating, int[] thinking, int[] hungry) throws InterruptedException
{
// Make random number
Random randomGenerator = new Random();
int num = randomGenerator.nextInt(10);
// Randomly set a philosopher isFull to false (hungry) (10% chance for each to become hungry if not specified by the user)
if (isHungry(philosophers[0].name))
philosophers[0].isFull = false;
if (num == 1 || isHungry(philosophers[1].name))
philosophers[1].isFull = false;
if (num == 2 || isHungry(philosophers[2].name))
philosophers[2].isFull = false;
if (num == 3 || isHungry(philosophers[3].name))
philosophers[3].isFull = false;
if (num == 4 || isHungry(philosophers[4].name))
philosophers[4].isFull = false;
// For each philosopher
for (Philosopher phil: philosophers)
{
// Print current info
System.out.println("PHIL: " + phil.name + " NUM: " + num + " RIGHT: " + phil.rightChopstick.available + " LEFT: " + phil.leftChopstick.available);
// Temp id var
int tempId = phil.id;
// If philosopher is hungry, try to eat
if (phil.isFull == false)
{
// Try to eat only if both chopsticks are available
if (phil.rightChopstick.pickUp(phil.name) && phil.leftChopstick.pickUp(phil.name))
{
// Change button color
new Background(phil.button).execute((long) 1);
//Toast.makeText(context, phil.name + " is eating.", toastLength).show();
// Increment time spent eating
eating[tempId]++;
}
// Check to see if the philosopher is already eating (has both chopsticks)
else if (phil.rightChopstick.who.equals(phil.name) && phil.leftChopstick.who.equals(phil.name))
{
//Toast.makeText(context, phil.name + " is eating.", toastLength).show();
new Background(phil.button).execute((long) 1);
// Increment eating
eating[tempId]++;
// 30% chance to stop eating
if (num >= 5 && num <=7)
{
// Put down chopsticks
phil.rightChopstick.putDown();
phil.leftChopstick.putDown();
// Stop eating
phil.isFull = true;
}
}
// Hungry
else
{
// Change button color
new Background(phil.button).execute((long) 3);
//Toast.makeText(context, phil.name + " is hungry.", toastLength).show();
// Increment time spent hungry
hungry[tempId]++;
}
}
// Thinking
else
{
new Background(phil.button).execute((long) 2);
//Toast.makeText(context, phil.name + " is thinking.", toastLength).show();
// Increment time spent thinking
thinking[tempId]++;
}
Thread.sleep(1000);
}
// Make each step count as 1 second (1000 miliseconds)
System.out.println("--------------------------------------------------------------");
Thread.sleep(5000);
}
}
Background class (AsyncTask):
public class Background extends AsyncTask<Long, Void, Void>
{
// Variables
String color;
Button button;
public Background(Button button)
{
this.button = button;
}
#Override
protected Void doInBackground(Long... params) {
// Get which color the button needs to be
try
{
// Change the color based on the value passed in
if (params[0] == 3)
{
color = "RED";
}
else if (params[0] == 2)
{
color = "BLUE";
}
else if (params[0] == 1)
{
color = "GREEN";
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set button to that color
System.out.println("Updating color in real time...");
button.setBackgroundColor(Color.parseColor(color));
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Here is one problem
Thread.sleep(1000);
and here is another
Thread.sleep(5000);
these are both making the UI sleep for a total of 6 seconds. You almost never want to call sleep() on the UI Thread. You can do this in doInBackground() or anywhere else that runs on a background Thread.
Edit
You don't set your Listeners. For example:
platoB.setOnClickListener(new pBtn());
Progress can be set with publishProgress in your asynctask, you get a call to onProgressUpdate in the UI thread.
i'm new to android programming. I have the following code happening on a button click
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.morse_btn);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
loopCode();
}
});
}
which calls this:
public void loopCode()
{
String code = "Hello There";
TextView view = (TextView) findViewById(R.id.code_txt);
String s = "";
for(int i = 0; i < code.length(); i++)
{
s+=code.charAt(i);
view.setText(s);
try {
TimeUnit.SECONDS.sleep(1);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
but when i run it on my phone, the text does not get appended until after the for loop has gone through, i.e i press the button, and after a few seconds, the whole string "Hello There" appears.
How can I make it write the text one character at a time, like a typewriter style.
Thanks
You need to use view.append("") which will append new text to the existing one.
Try this code:
int i = 0; //declare this globally
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(i != 10) {
text.append(" " + i);
i++;
handler.postDelayed(this, 1000);
}
}
}, 1000);
}
This code will append a new number to the TextView every one second until it has reached the count 10. You can apply the same logic.
I had provided this solution to a question here -
[EDIT]
Try this:
String code = "Hello There"; //declare variable globally
int i = 0; //declare globally
TextView view; //declare globally
public void loopCode()
{
view = (TextView) findViewById(R.id.code_txt);
//String s = "";
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(i != code.length()) {
view.append(" " + code.charAt(i));
i++;
handler.postDelayed(this, 1000);
}
}
}, 1000);
}
}
Don't forget to declare int i = 0 and String code = "Hello There" globally.
Exist 2 different method setText in TextView.
public final void setText (int resid)
public final void setText (CharSequence text)
when you put variable int in setText, the android try find String in classe R variable in same code.
To resolve this you then cast int to string using String.valueOF(...)
see more in;
http://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence)
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#valueOf(int)
try
public void loopCode()
{
String code = "Hello There";
TextView view = (TextView) findViewById(R.id.code_txt);
String s = "";
for(int i = 0; i < code.length(); i++)
{
view.setText(String.valueOf(i));
try {
TimeUnit.SECONDS.sleep(1);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}