Mo920192
Mo920192

Reputation: 39

Problems with ArrayList in Android

I am trying to build an app to translate English into pig latin. But before I do the conditional coding for it I want it to print what I have on screen. It only prints the last word on the screen. Eg if I type This is the words it types words. I am guessing it is because I am not using an index but I have no clue. I am a beginner programmer and I need help. This is my Java Code.

package com.example.morna.piglatin;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity
{

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

    public void onClickTranslate(View v)
    {
        final String vowels = "aeiouAEIOU";
        EditText inputTranslateText =      (EditText)findViewById(R.id.edEnglishText);
        String t = inputTranslateText.getText().toString();
        List <String> objects = Arrays.asList(t.split("\\s+"));



        for(String object: objects)
        {
            TextView outputPigLatin = (TextView)findViewById(R.id.txtPigLatin);
            outputPigLatin.setText(String.valueOf(object));

        }

Upvotes: 0

Views: 103

Answers (1)

miljon
miljon

Reputation: 2771

It's because with every iteration of loop you set new text into textView, so old text is overridden by a new one from a loop, moreover you declare textView many times in a loop, it's pointless and not optimal, so it will be slow. Instead of this code:

for(String object: objects)
{
    TextView outputPigLatin = (TextView)findViewById(R.id.txtPigLatin);
    outputPigLatin.setText(String.valueOf(object));

}

Use this one, put TextView outside loop, and set text only once outside loop too:

TextView outputPigLatin = (TextView)findViewById(R.id.txtPigLatin);
String myText = null;
for(String object: objects)
{
    myText += object+", ";

}
outputPigLatin.setText(myText);

If you have a lot of words to print (like hundred or thousands), more optimal approach will be use of StringBuilder class:

TextView outputPigLatin = (TextView)findViewById(R.id.txtPigLatin);
StringBuilder myText = new StringBuilder();
for(String object: objects)
{
    myText.append(object).append(", ");

}
outputPigLatin.setText(myText.toString());

Upvotes: 1

Related Questions