简体   繁体   中英

Hello world example is not working

I am following a tutorial for beginners with Android Studio, and there is a "Hello World" example like this one:

package com.example.moi.scaleguess;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView text = new TextView(this);

        text.setText("Hello, you owe me 1 000 000€.");

        setContentView(R.layout.activity_main);
    }
}

But when I am starting this app either on my phone or on a virtual one, I only get "Hello World !" message AND NOT "Hello, you owe me 1 000 000€.".

I don't understand, it's like another program is started.

Your initialization of TextView is wrong. Here is the example:

TextView text = (TextView) findViewById(R.id.textViewId); // must be tally in your activity_main layout.

You need to cast the view in layout (XML file) into TextView .

Another one is setContentView(R.layout.activity_main); must be called before initializing any view.

Your onCreate function must be look like this:

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

    TextView text = (TextView) findViewById(R.id.textViewId);
    text.setText("Hello, you owe me 1 000 000€.");
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        setContentView(R.layout.activity_main);
TextView text = (TextView) findViewById(R.id.textviewIdInXMLFile);

        text.setText("Hello, you owe me 1 000 000€.");
    }
}

You create a Java View object and then you tell Android to print a XML view with setContentView(R.layout.activity_main); on screen so that is what it does. I you want to use Java object only you should try this code :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView text = new TextView(this);

    text.setText("Hello, you owe me 1 000 000€.");

    setContentView(text);
}

Or you can use XML for instanciate a Java View object, and then change the text as Zarul Izham and Vyacheslav advice you to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM