Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 254
user3578847 Avatar asked Apr 30 '15 20:04

user3578847


2 Answers

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();
    }
}
like image 172
Stefano Vuerich Avatar answered Oct 24 '22 05:10

Stefano Vuerich


Short answer: add this

import android.content.Context;
like image 45
codemirror Avatar answered Oct 24 '22 05:10

codemirror