Java – Android textview – I can’t get it to continue

Android textview – I can’t get it to continue… here is a solution to the problem.

Android textview – I can’t get it to continue

Hello, I’m trying to build my first Android project. I am a good programmer, good at microcontrollers, php, bash, etc.

However, this Java syntax makes people want to explode.

package com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tv1;


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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

TextView tv1 = (TextView) findViewById(R.id.textView1);
tv1.setText("Text2");

}

and

<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=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:editable = "true" />

I looked up a lot of examples online, but it looks like I can’t do it.

tv1.setText("Text2"); There are always grammatical errors.

Where did I go wrong?

Solution

Change to

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // initialize after setContentView
    tv1 = (TextView) findViewById(R.id.textView1);
    tv1.setText("Text2"); // should be within a method
}

Related Problems and Solutions