我正在尝试在按下刷新按钮时在我的程序中显示进度对话框,但是应用程序在调试器中关闭了一个错误,但是创建的线程ui hierachy只能触摸它。
public class MainActivity extends Activity {
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.refreshView();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void refreshView(){
ImageView img = (ImageView) findViewById(R.id.imageView1);
Bitmap bm = null;
InputStream is = null;
BufferedInputStream bis = null;
try
{
URLConnection conn = new URL("http://technomoot.edu.pk/$Common/Image/Content/ciit_logo.jpg").openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream(is, 8192);
bm = BitmapFactory.decodeStream(bis);
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
if (bis != null)
{
try
{
bis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
img.setImageBitmap(bm);
}
public void onRefresh(View view) {
final ProgressDialog dialog = ProgressDialog.show(this,"Loading","Loading the image of the Day");
Thread th = new Thread(){
public void run(){
refreshView();
handler.post(new Runnable(){
public void run(){
dialog.dismiss();
}
}
);
}
};th.start();
}
}
答案 0 :(得分:1)
您正在从非ui线程调用ui操作,您可以使用runOnUiThread
..
或者更好地使用AsynchTask
public YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
ProgressDialog dialog;
Context context;
public YourTask(Context context){
this.context=context;
}
protected void onPreExecute(Object o){
dialog = ProgressDialog.show(this,"Loading","Loading the image of the Day");
}
protected void doInBackground(Object o){
refreshView();
}
protected void onPostExecute(Object o){
img.setImageBitmap(bm);
dialog.dismiss();
}
}
答案 1 :(得分:1)
您无法使用UI
来自Thread
进行操纵!它是被禁止!如果您想更新UI
,请使用
runOnUiThread()
强> AsyncTask
强> 所以试试这样:
runOnUiThread(new Runnable() {
@Override
public void run() {
// do your work.
}
});
AsyncTask
更复杂,也是泛型类型,提供类型控制等一些好处。您可以在此处查看示例: