Home » Android » java – Cannot find symbol 'Context', android.content.Context

java – Cannot find symbol 'Context', android.content.Context

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have the following code:

package com.androidtest.notification;

import android.app.Activity;
import android.os.Bundle;
import android.widget;
import android.widget.Toast;
import android.content.Context;

public class activityNotification extends Activity
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Context context = getApplicationContext();
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}

I’m trying to compile it using ant on command line ‘$ ant build’, but I keep getting the following error:

error: cannot find symbol
[javac]         Context context = getApplicationContext();
[javac]         ^

Any suggestions please? Thanks!

How to&Answers:

Short answer: add this

import android.content.Context;

Answer:

Context in Activity is obtained by YourActivity.this or easier with this

package com.androidtest.notification;

import android.app.Activity;
import android.os.Bundle;
import android.widget;
import android.widget.Toast;
import android.content.Context;

public class ActivityNotification extends Activity
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Context context = this; // or ActivityNotification.this
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(this, text, duration);
        toast.show();
    }
}