Declare and Initialize string ArrayList in Android Java

How to make string arraylist in android then assign values to array list and show array list on activity screen using textview.

In this tutorial we are simply creating an array list inside MainActivity.java programming file, after that we have insert values dynamically inside array list then show the string array list on screen with for loop with textview. So here is the complete step by step tutorial for Declare and Initialize string ArrayList in Android Java.

android-project-download-code-button

How to Declare and Initialize string ArrayList in Android Java.

Code for MainActivity.java file.

 package com.initializestringarraylist_android_examples.com;

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView textview;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 textview = (TextView)findViewById(R.id.textView1);
 
 //Initializing string array list;
 List<String> Values = new ArrayList<>();
 
 //Dynamically adding values to array list.
 
 Values.add("ONE");
 Values.add("TWO");
 Values.add("THREE");
 Values.add("Four");

 //Printing array list values on screen.
 
 for(int i=0; i < Values.size(); i++){
 
 textview.setText(textview.getText() + Values.get(i) + " , ");
 }
 }

}

Code for activity_main.xml layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.initializestringarraylist_android_examples.com.MainActivity" >

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text=""
 android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Screenshot:

Declare and Initialize string ArrayList in Android Java

Click here to download Declare and Initialize string ArrayList in Android Java project with source code.

Leave a Reply

Your email address will not be published. Required fields are marked *