I just started trying to learn development in Android Studio, and while I was trying to make my first application work ( I'm also new to stackoverflow, so sry if the way I present this thread isn't satisfactory ), I ran into a brickwall of nullpointerexceptions. I just wanted to make a button that displays a text message (toast) when I click on it. It probably is a typical newbie mistake, but I just can't seem to find out what the problem is exactly. Can somebody enlighten me please?
The relevant part of the error message as far as I can tell is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Heres the code:
public class FirstActivity extends AppCompatActivity {
private static FirstActivity instance;
Context context = getApplicationContext();
CharSequence text = "A text that appears for a short time";
int duration = Toast.LENGTH_SHORT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
public void buttonclick(View view){
Toast toast1 = Toast.makeText(context,text,duration);
}
}
and the xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.rayaqin.myfirstandroidapp.FirstActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="259dp"
android:text="Press Me"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Me"
tools:layout_editor_absoluteX="-498dp"
tools:layout_editor_absoluteY="527dp"
android:onClick="buttonclick"/>
</android.support.constraint.ConstraintLayout>