我在Android应用程序中面临AsyncTask
的一个问题。问题是,我在我的应用程序中从AsyncTask
开始另一个Activity
,当它的布局具有简单的Button
时运行良好,但是当我使用ImageButton
时,它会给我处理程序和循环器的错误。我不明白为什么会发生这种错误。我在调用Activity
时显示带有图像的菜单。
谁能告诉我这个问题是什么,我怎么才能实现这种功能?
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (Dialog != null && Dialog.isShowing()) {
Dialog.dismiss();
locationManager.removeUpdates(locationListener);
Intent homeIntent = new Intent(ATMActivity.this.getApplicationContext(), HomeMenuActivity.class);
homeIntent.putExtra("lat", latitude);
homeIntent.putExtra("lng", longitude);
startActivity(homeIntent);
}
}
XML文件:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/atm_icon"
android:onClick="buttonClicked" />
</LinearLayout>
另一个Activity Class:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Button btn = (Button) findViewById(R.id.imageButton1);
btn.setHint("ATM");
float latitude = getIntent().getFloatExtra("lat", 0);
float longitude = getIntent().getFloatExtra("lng", 0);
Toast.makeText(getApplicationContext(), "Location Floats:- " + latitude + "," + longitude, Toast.LENGTH_LONG).show();
}
我认为你正在玩UI线程(更新UI线程)从一个非UI线程,这是导致你的问题。如果你想从非ui线程中更新任何东西,你需要将代码放入runOnUiThread()
。
Activity_name.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// here you can add stuff to Update the UI.
}
});
没有完整的堆栈跟踪很难确定,但我最好的猜测是你实际上得到了一个ClassCastException
。
您的ATMActivity
正试图将imageButton1
(在xml中定义为ImageButton
)转换为Button
。这是不可能的,因为后者不是前者的超类。
// Can't do below: Button is not a superclass of ImageButton
Button btn = (Button) findViewById(R.id.imageButton1);
因为你是从AsyncTask的onPostExecute开始活动的,你可能会在堆栈跟踪中发现一些提到循环器/处理程序的东西。