android.view.ViewRoot$CalledFromWrongThreadException 异常的解决方案 * 更新时间: 2011-07-21

在android平台下,进行多线程编程时,经常需要在主线程之外的一个单独的线程中进行某些处理,然后更新用户界面显示。但是,在主线线程之外的线程中直接更新页面显示的问题是:系统会报这个异常,android.view.viewroot$calledfromwrongthreadexception: only the original thread that created a view hierarchy can touch its views. (只有原始创建这个视图层次(view hierachy)的线程才能修改它的视图(view)。)。

  也就是说必须在程序的主线程(也就是ui线程)中进行更新界面显示的工作。可以采用下面的方法之一来解决:

解决方案1:在activity.oncreate(bundle savedinstancestate)中创建一个handler类的实例, 在这个handler实例的handlemessage回调函数中调用更新界面显示的函数。例如:

  

public class ExampleActivity extends Activity {
	Handler h = null;
	@override
	public void onCreate(Bundle savedinstancestate){
		h = new Handler(){
			@override
			public void handleMessage(Message msg){
				// call update gui method.
			}
		};
	}
}


  在其它的函数中,利用 send族或post族函数向这个h发送或邮寄消息即可。


解决方案2:利用activity.runonuithread(runnable)

  把更新ui的代码创建在runnable中,然后在需要更新ui时,把这个runnable对象传给activity.runonuithread(runnable)。 这样runnable对像就能在ui程序中被调用。


android.view.ViewRoot$CalledFromWrongThreadException 异常

04-08

我想从服务器中下载图片后并显示出来,当进行下载时,会显示一个进度对话框。使用一个 asynctask 类。运用下面的代码:rnrn private void startDownload() rn rn new DownloadFileAsync().execute(imageUrl);rn image.setImageBitmap(bitmap);rn rn @Overridern protected Dialog onCreateDialog(int id) rn switch (id) rn case DIALOG_DOWNLOAD_PROGRESS:rn dialog = new ProgressDialog(this);rn dialog.setTitle("Loading");rn dialog.setMessage("Please wait...");rn dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);rn dialog.setCancelable(false);rn dialog.show();rn return dialog;rn default:rn return null;rn rn rn rn rn class DownloadFileAsync extends AsyncTask rn int count;rn URL myFileUrl;rn rn @Overridern protected void onPreExecute() rn super.onPreExecute();rn showDialog(DIALOG_DOWNLOAD_PROGRESS);rn rn rn @Overridern protected String doInBackground(String... aurl) rn rn rn try rn myFileUrl = new URL(imageUrl);rn HttpURLConnection conn = (HttpURLConnection) myFileUrlrn .openConnection();rn int lenghtOfFile = conn.getContentLength();rn //conn.setDoInput(true);rn conn.setConnectTimeout(10000);rn conn.setReadTimeout(10000);rn conn.connect();rn InputStream is = conn.getInputStream();rn bmImg = BitmapFactory.decodeStream(is);rn bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUrl)rn .getContent());rn bitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);rn rn byte data[] = new byte[1024];rn System.out.println("mmmmmmmmmmmm");rn rn long total = 0;rn System.out.println("nnnnnnnnnn");rn while ((count = ((InputStream) new URL(imageUrl)rn .getContent()).read(data)) != -1) rn total += count;rn publishProgress(""+(int)((total*100)/lenghtOfFile));rn for(int l=0;l<4;l++)rn if(listObject.get(l).getImage()!="")rn image.setImageBitmap(bitmap);rn rn rn rn catch(Exception e)rn System.out.println(e);rn rn return null;rn rn rn protected void onProgressUpdate(String... progress) rn dialog.setProgress(Integer.parseInt(progress[0]));rn rn rn @Overridern protected void onPostExecute(String unused) rn image.setImageBitmap(bitmap);rn dismissDialog(DIALOG_DOWNLOAD_PROGRESS);rn rn rn rnrn却给出下面的异常:rnrn android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. rnrn我找不出错误所在,请大家帮忙改正。

android.view.ViewRoot$CalledFromWrong 这个异常怎么解决。。

12-09

就是用socket编程,已经能和服务端连上了,主要是服务端发来消息后要在TextView上显示,一开始单独写个类把activity传进去直接改里面的TextView,发现不行,就出现上面的异常,百度后说要用handler,就照上面用了handler,可是发现还是不行,别人说不能传activity,应该把操作都放在activity里面,好吧,接着改(其实也没啥就是挪个地方),后来发现还是不行,还是这个异常,我下面贴代码,大家给看看啊。。[code=java]package com.example.chatphone;rnrnimport java.io.BufferedReader;rnimport java.io.IOException;rnimport java.io.InputStreamReader;rnimport java.io.PrintWriter;rnimport java.net.Socket;rnimport java.net.UnknownHostException;rnrnimport android.os.Bundle;rnimport android.os.Handler;rnimport android.os.Message;rnimport android.app.Activity;rnimport android.view.Menu;rnimport android.view.View;rnimport android.view.View.OnClickListener;rnimport android.widget.Button;rnimport android.widget.EditText;rnimport android.widget.TextView;rnrnpublic class MainActivity extends Activity rn private TextView disText = null;rn private EditText input = null;rn private Button btnSend = null;rn private MyHandler myHandler = null;rnrn private BufferedReader BR = null;rn private PrintWriter PW = null;rn private Socket s = null;rn private boolean isConnectioned = false;rn private Thread thRecv = null;rnrn @Overridern protected void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn setContentView(R.layout.activity_main);rn myHandler = new MyHandler();rn disText = (TextView) findViewById(R.id.disText);rn input = (EditText) findViewById(R.id.input);rn btnSend = (Button) findViewById(R.id.btnSend);rn connection();rn btnSend.setOnClickListener(new OnClickListener() rnrn @Overridern public void onClick(View v) rn send("hello");rn rn );rn rnrn @Overridern public boolean onCreateOptionsMenu(Menu menu) rn getMenuInflater().inflate(R.menu.main, menu);rn return true;rn rnrn /**rn * 定义handle提醒ui更新rn */rn class MyHandler extends Handler rnrn @Overridern public void handleMessage(Message msg) rn super.handleMessage(msg);rn Bundle b = msg.getData();rn String msgStr = b.getString("msg");rn disText.setText(msgStr);rn rn rnrn private class Recv implements Runnable rnrn @Overridern public void run() rn while (true) rn try rn System.out.println("run");rn String msgStr = BR.readLine();rn Message msg = new Message();rn Bundle b = new Bundle();rn b.putString("msg", msgStr);rn msg.setData(b);rn System.out.println(msg + "->>");rn MainActivity.this.myHandler.handleMessage(msg);rn catch (IOException e) rn e.printStackTrace();rn rn rn rn rnrn private void connection() rn try rn isConnectioned = true;rn s = new Socket("169.254.66.14", 8888);rn BR = new BufferedReader(new InputStreamReader(s.getInputStream()));rn PW = new PrintWriter(s.getOutputStream());rn thRecv = new Thread(new Recv());rn thRecv.start();rn catch (UnknownHostException e) rn e.printStackTrace();rn catch (IOException e) rn e.printStackTrace();rn rn rnrn /**rn * 像服务器发送消息rn * rn * @param msgrn * 要发送的消息rn */rn private void send(String msg) rn PW.println(msg);rn PW.flush();rn rn[/code]

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试