Sai*_*son 3 java android android-intent
我有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");
}
}
Run Code Online (Sandbox Code Playgroud)
和 JSONTask.java
public class JSONTask extends AsyncTask<String, String, String> {
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
我的最后两行总是给我错误:
Intent i = new Intent(this, AnswerActivity.class);
Toast.makeText(i, result, Toast.LENGTH_LONG).show();
Run Code Online (Sandbox Code Playgroud)
我想将其result作为Toast 显示在AnswerActivity中.但为什么我总是收到此错误消息?
Error:(68, 20) error: no suitable constructor found for Intent(JSONTask,Class<AnswerActivity>)
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)
Run Code Online (Sandbox Code Playgroud)
我在这里想念的是什么?谢谢
您需要一个上下文来显示Toast.通常它是Activity或Fragment具有上下文.但既然你AsyncTask不是你的内在阶级,AnswerActivity你就没有上下文的参考.所以你可以传递Activity构造函数并使用它
public class JSONTask extends AsyncTask<String, String, String> {
private Context context;
public JSONTask(Context context){
this.context = context;
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它
new JSONTask(this)... // and so on
Run Code Online (Sandbox Code Playgroud)
这样做的最大好处是,你不会保留对它的引用Activity,只是传递Context- 因为Activity确实扩展了Context.
| 归档时间: |
|
| 查看次数: |
776 次 |
| 最近记录: |