我有2个.java
文件:AnswerActivity.java
public class AnswerActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_answer); new JSONTask().execute("https://example.com/api.php"); } }
和 JSONTask.java
public class JSONTask extends AsyncTask{ @Override protected String doInBackground(String... params) { //--- some code cut here ---// } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Intent i = new Intent(this, AnswerActivity.class); Toast.makeText(i, result, Toast.LENGTH_LONG).show(); } }
我的最后两行总是给我错误:
Intent i = new Intent(this, AnswerActivity.class); Toast.makeText(i, result, Toast.LENGTH_LONG).show();
我想将其result
作为Toast 显示在AnswerActivity中.但为什么我总是收到此错误消息?
Error:(68, 20) error: no suitable constructor found for Intent(JSONTask,Class) constructor Intent.Intent(String,Uri) is not applicable (argument mismatch; JSONTask cannot be converted to String) constructor Intent.Intent(Context,Class>) is not applicable (argument mismatch; JSONTask cannot be converted to Context) Error:(69, 14) error: no suitable method found for makeText(Intent,String,int) method Toast.makeText(Context,CharSequence,int) is not applicable (argument mismatch; Intent cannot be converted to Context) method Toast.makeText(Context,int,int) is not applicable (argument mismatch; Intent cannot be converted to Context)
我在这里想念的是什么?谢谢
您需要一个上下文来显示Toast
.通常它是Activity
或Fragment
具有上下文.但既然你AsyncTask
不是你的内在阶级,AnswerActivity
你就没有上下文的参考.所以你可以传递Activity
构造函数并使用它
public class JSONTask extends AsyncTask{ private Context context; public JSONTask(Context context){ this.context = context; } @Override protected void onPostExecute(String result) { Toast.makeText(context, result, Toast.LENGTH_LONG).show(); } }
并使用它
new JSONTask(this)... // and so on
这样做的最大好处是,你不会保留对它的引用Activity
,只是传递Context
- 因为Activity确实扩展了Context.