How do I display what system.out.println() shows in the console, in an Android Application's activity?

StackOverflow https://stackoverflow.com/questions/18412223

  •  26-06-2022
  •  | 
  •  

Question

For example, say I have a simple coin flip program that display a single line of text. After running the program as a Java Project, the console would display "There are 473 heads and 527 tails." I don't mean displaying this in LogCat, but actually displaying it when using the application.

//Basic coin flip statistics program.
package com.company.practice;

import java.util.Random;

public class CoinFlip {
public static void main(String[] args){

    System.out.println("Toss a coin 1000 times");

    int heads = 0;
    int tails = 0;
    Random r = new Random();

    for(int flips = 0; flips < 1000; flips++){ 
        //Change the # after < to set amount of flips.
        int side = r.nextInt(2);
        if(side == 0) heads++;
        else tails++;
    }

    System.out.println("There are " + heads + " heads and " + tails + " tails.");
    }
}

How would I display the line of code at the bottom that says, "System.out.println(...)" as text in an Android Application's activity?

Was it helpful?

Solution

You'd display it in the UI attached to the Activity.

An Android app is not constructed the same as a Java program. There's no "main" class. In fact, you usually don't declare an Application subclass. Instead, you construct a loose web of Activities that interact with each other using Intents. Each Activity has an associated layout that contains Views. When the Activity starts up, you load its main layout, then you store the View objects in variables in the Activity. When you want to modify the contents of a View, you call a method (often setText()) to change the contents.

Layouts and Views can be defined in an XML file, or set up programmatically.

Those of you who have written Java programs before will have to step back some, and approach app construction from a somewhat different point of view. I strongly encourage you to browse through the documentation, particularly the training class, and look at the samples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top