I’m new to Android programming and probably I don;t understand Java very well yet, so i got this problem with my program.
Every time I press button on my menu I get the java.lang.NullPointerException.
Is there any way to reference to this TextView object and change its text when item2 on menu is clicked?
public class MainActivity extends Activity {
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainActivity.this.tv = (TextView) findViewById(R.id.tekst1);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.item2) {
MainActivity.this.tv.setText("aaa");
}
return super.onOptionsItemSelected(item);
}
}
EDIT:
mymenu xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/item1"
android:icon="@android:drawable/ic_menu_week"
android:title="Option 1"/>
<item
android:id="@+id/item2"
android:icon="@android:drawable/ic_menu_month"
android:title="Option 2"/>
</menu>
activity_main.xml
<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" >
<TextView
android:id="@+id/tekst1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
You need to load the layout BEFORE retrieving the element.
Just replace
By
The findViewById method tries to find an element (from an ID) inside the hierarchy of the view. That’s why you need to load this hierarchy (from the XML file) before! Otherwise you search in an empty hierarchy of views