Anshuman Pattnaik
Anshuman Pattnaik

Reputation: 923

How to print all the values inside for loop in Android?

I am getting quite confused why i am not able print the all array values inside the loop. It's only printing the last value of the array.

the following code-:

package com.example.code_1;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import android.util.Log;


public class MainActivity extends Activity 
{


@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tt=(TextView)findViewById(R.id.and);


    try
    {


 String abc[]={"1","2","3","4","5","6","7","8","9","10","11","12"};


        for(int i=0;i<abc.length;i++)
        {

             tt.setText(String.valueOf(abc[i]));

        }

    }
    catch(NullPointerException e)
    {


    }

 }

}

I searched the internet and i found to use StringBuilder class to append all values and display the array outside the loop but i think it's quite similar to sum the all content into a string display it in a single variable. I don't want this solution.

Please help me out, how can i print all values inside the loop. !!!

Thanks in Advance..

Upvotes: 1

Views: 5537

Answers (3)

Raghunandan
Raghunandan

Reputation: 133560

Use append instead of setText.

   for(int i=0;i<abc.length;i++)
    {
       tt.append(String.valueOf(abc[i]));
       tt.append("\n"); // for new line
    }

setText set's the latest one to textview.

You can use StringBuilder also and use append

 StringBuilder builder = new StringBUilder();

  for(int i=0;i<abc.length;i++)
    {
        builder.append(String.valueOf(abc[i]));
        builder.append("\n");  
    }

  tt.setText(builder.toString()));

http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

Upvotes: 4

Egor Neliuba
Egor Neliuba

Reputation: 15054

By doing setText() you are replacing the text inside TextView. To add text you should use append() method like so:

 tt.append(String.valueOf(abc[i]));

Now if you want your new text to be on the new line you should write something like this:

 tt.append("\n" + String.valueOf(abc[i]));

Upvotes: 3

StarsSky
StarsSky

Reputation: 6711

You need to add the previous text

tt.setText(tt.getText().toString()+String.valueOf(abc[i]));

Upvotes: 3

Related Questions