How to Show Random String from String.xml in Android

strings.xml

<resources>
    <string name="app_name">Symon Apps</string>
    
    
    <string-array name="q">
        <item> hello 0</item>
        <item> hello 1</item>
        <item> hello 2</item>
        <item> hello 3</item>
        <item> hello 4</item>
        <item> hello 5</item>
    </string-array>


    

</resources>



 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.example.hp.symonapps.MainActivity">



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

</RelativeLayout>


MainActivity.java 

package com.example.hp.symonapps;

        import android.content.res.Resources;
        import android.os.Bundle;
        import android.support.v7.app.AppCompatActivity;
        import android.widget.TextView;
        import java.util.Random;


public class MainActivity extends AppCompatActivity {


    private String[] myString;
    private static final Random generator = new Random();

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


        Resources res = getResources();
        myString = res.getStringArray(R.array.q);

        String m = myString[generator.nextInt(myString.length)];
        TextView tv = (TextView) findViewById(R.id.tv);
        tv.setText(m);




    } //onCreate end


}




Comments