I am a bit new to Android Studio and Java. I am trying to update a text by replacing it from an element of an ArrayList. However, when using setText(userList.get(0)), the app crashes. My guess is that the arraylist is empty or cannot be accessed. But I use the same code on a button with a setOnClickListener, the text is updated by the string found in the arrayList.
I want to make the app automatically update the Text onloading the activity.
Here is my MainActivity.java -- I commented the setText that is crashing the app.
package com.example.sampletest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
    ArrayList<String> userList = new ArrayList<String>();
    TextView text;
    Button swapText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new getUsers().execute();
        text = (TextView) findViewById(R.id.text);
        swapText = (Button) findViewById(R.id.button);
        //text.setText(userList.get(0));
        swapText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                text.setText(userList.get(0));
            }
        });
    }
    class getUsers extends AsyncTask<Void, Void, Void> {
        String error = "";
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection connection = DriverManager.getConnection("jdbc:mysql://192.168.100.5:3306/cardetailingdb", "lau", "lau");
                Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
                while (resultSet.next()) {
                    userList.add(resultSet.getString(1));
                }
            } catch (Exception e) {
                error = e.toString();
            }
            return null;
        }
    }
}
 
     
     
    