package com.example.helloandroid;
import java.io.File;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;
public class CheckTask extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
while (true) {
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
// access external file
String f = Environment.getExternalStorageDirectory()
+ "/schedule.rtf";
File s = new File(f);
if (s.exists()) {
return true;
}
}
}
}
开发者_如何学Pythonprotected void onPostExecute(Boolean result) {
if (result == true) {
Toast.makeText(CheckTask.this, "Hello", Toast.LENGTH_SHORT).show();
}
}
}
I keep getting the following error message: The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (CheckTask, String, int)
I have tried searching some basic tutorials and they use Toast.makeText in the same way as above. I am not sure whats wrong.
Thank you.
It's because you are passing the CheckTask object instance in to makeText. You need to pass the instance/Context of your activity.
Is your AsyncTask an inner class of an actual activity? That is how the example below works and how I have always seen it done when looking at other people's code.
Here's a working example. Ignore the package name, I was having a play with creating a pedometer awhile back and just reused that project to do this.
package jm.pedometer;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
public class MainView extends Activity {
Chronometer mChronometer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mChronometer = (Chronometer)findViewById(R.id.Chronometer01);
mChronometer.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/digital_clock.ttf"));
CheckTask testTask = new CheckTask();
testTask.execute();
}
/*
* This AsyncTask is an inner class within an Activity
*/
public class CheckTask extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
return true;
}
protected void onPostExecute(Boolean result) {
if (result == true) {
Toast.makeText(MainView.this, "Hello", Toast.LENGTH_SHORT).show();
}
}
}
}
Instead of passing CheckTask.this
, just use this
or this.getContext()
.
精彩评论