-6

I'm a beginner in android developer and I want to create an action for an item in menu.
This is the mainActivity.java:

public class MainActivity extends AppCompatActivity {

private TextView m;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    m = (TextView)findViewById(R.id.principal);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main,menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==R.id.info){
        m.setText(R.string.about_text);
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

And this is activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/principal"
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="bd2c.bd2c_appdemo.MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/app_text" />
</RelativeLayout>

and menu_main.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/info"
    android:title="@string/get_info"/>

When I start my app, It display: unfortunately app has stopped

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Kate
  • 145
  • 3
  • 12

3 Answers3

0

System.out.print(findViewById(R.id.principal));--//Null In main activity above line ,what is principal and what you have initialized to principle.

Porkko M
  • 307
  • 2
  • 10
0

Move android:id="@+id/principal to your TextView

<TextView
    android:id="@+id/principal
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/app_text" />
Emanuel Canha
  • 441
  • 5
  • 11
0
<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="bd2c.bd2c_appdemo.MainActivity">

<TextView
    android:id="@+id/principal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/app_text" />
</RelativeLayout>

This is your fixed layout select all copy that and go to your layout select all and paste this. Bingo :)

Muhammad Saad Rafique
  • 3,158
  • 1
  • 13
  • 21