我是android和它的编程新手。我想在android 片段中实现 AsyncTask ,在这里我想让我的toast工作。(出于测试目的)请帮助我,并在下面找到我使用的代码。当我试试这个,我得到了以下错误
log cat
03-15 19:52:25.666: E/AndroidRuntime(18845): FATAL EXCEPTION: AsyncTask #1
03-15 19:52:25.666: E/AndroidRuntime(18845): java.lang.RuntimeException: An error occured while executing doInBackground()
03-15 19:52:25.666: E/AndroidRuntime(18845): at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-15 19:52:25.666: E/AndroidRuntime(18845): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-15 19:52:25.666: E/AndroidRuntime(18845): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
我的代码
public class Login extends Fragment {
View view;
ImageView button,pic;
@SuppressLint("ValidFragment")
public Login() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.login, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
button=(ImageView) view.findViewById(R.id.login);
pic=(ImageView) view.findViewById(R.id.pic);
button.setOnClickListener(btnClick);
}
ImageView.OnClickListener btnClick=new ImageView.OnClickListener()
{
@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
// my code begins here
if(fb.isSessionValid())
{
new MyAsyncTask().execute("");
}
else
{
}
}
};
class MyAsyncTask extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... params) {
Toast.makeText(getActivity(),"session valid" , Toast.LENGTH_LONG).show();
return null;
}
}
}
答案 0 :(得分:0)
你无法在后台制作祝酒词。将您的Toast移动到onPostExecute()
或在UI线程上运行toast:(第3个答案)
How to raise a toast in AsyncTask, I am prompted to used the Looper
答案 1 :(得分:0)
Toast在UI线程中执行,而doInBackGround()方法在后台线程上运行。这就是错误的原因。将Toast移动到onPostExecute()方法。 onPostExecute()方法获取doInBackGround()方法的结果,因此它看起来像:
@Override
public void onPostExecute(String result) {
// make Toast
}
请记住,必须强制覆盖doInBackGround方法。所以你仍然需要它。