In a primitive test application, the studio gives an error. Error on physical device. In the studio, the following text:

With the app is not running

Just in case, I attach the code. Code from 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:id="@+id/activity_main" 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="com.example.user.myapplication.MainActivity"> <Button android:text="@string/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:id="@+id/button" /> <TextView android:text="@string/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/button" android:layout_centerHorizontal="true" android:layout_marginBottom="78dp" android:id="@+id/textView" /> </RelativeLayout> 

The code from MainActivity.java:

package com.example.user.myapplication;

 import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button button = (Button) findViewById(R.id.button); TextView text = (TextView) findViewById(R.id.text); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { text.setText("НаТата ΠΊΠ½ΠΎΠΏΠΊΠ°"); } }); } } 
  • findViewById needs to be done after setContentView . - post_zeew

1 answer 1

 public class MainActivity extends AppCompatActivity { Button button; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text = (TextView) findViewById(R.id.text); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { text.setText("НаТата ΠΊΠ½ΠΎΠΏΠΊΠ°"); } }); } } 
  • I did everything as shown. The application starts but after clicking on the button it crashes. What now ? - Cthulhu_Rlyeh
  • The next error is exactly what you are using in the activation setContentView (R.layout.activity_main); instead of setContentView (R.layout.main); Your activity knows nothing about the mail markup file - Andriy Martsinkevych
  • Is the error still repeated? - Andriy Martsinkevych
  • Instead of activity_main leave main? But there is no such file in the layout folder. - Cthulhu_Rlyeh