Android的 - 产生的原因:android.view.ViewRootImpl $ CalledFromWrongThreadException [英] android - Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException

查看:184
本文介绍了Android的 - 产生的原因:android.view.ViewRootImpl $ CalledFromWrongThreadException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  <一href="http://stackoverflow.com/questions/10118301/android-viewrootimplcalledfromwrongthreadexception">Android - ViewRootImpl $ CalledFromWrongThreadException

我试着从我的网址,并显示在应用程序中获取图像,但它抛出错误的产生的原因:android.view.ViewRootImpl $ CalledFromWrongThreadException:只有原来的线程创建一个视图层次可以触摸自己的看法 。下面是我的code

code

 包com.smartag.bird.dev;

公共类MainActivity延伸活动{
    静态字符串ndefMsg = NULL;
    静态字符串ndefMsg1 = NULL;
    NfcAdapter mNfcAdapter;
    PendingIntent mNfcPendingIntent;
    IntentFilter的[] mNdefExchangeFilters;
    static final的字符串变量=读标签;
    TextView的mTitle;
    私有静态的ImageView ImageView的;
    静态字符串URL =htt​​p://sposter.smartag.my/images/chicken_soup.jpg;
    私有静态位图downloadBitmap;
    私有静态BitmapDrawable bitmapDrawable;
    私有静态布尔largerImg = FALSE;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        mNfcAdapter = NfcAdapter.getDefaultAdapter(本);
        mNfcPendingIntent = PendingIntent.getActivity(此,0,
                新意图(本,的getClass())addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0)。
        IntentFilter的ndefDetected =新的IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        尝试 {
            ndefDetected.addDataType(text / plain的);
        }赶上(MalformedMimeTypeException E){}
        mNdefExchangeFilters =新的IntentFilter [] {ndefDetected};
        如果(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent()。的getAction())){
            NdefMessage []消息= getNdefMessages(getIntent());
            字节[] =有效载荷的消息[0] .getRecords()[0] .getPayload();
            ndefMsg =新的String(负载);
            setIntent(新的意向书()); //这个消费意图。
        }

        ConnectivityManager connManager =(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
        的NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        如果(ndefMsg == NULL || ndefMsg.length()== 0)
        {
            startActivity(新意图(MainActivity.this,MainMenu.class));
        }
        其他
        {
            的setContentView(R.layout.main);
            如果(mWifi.isConnected()){
                ndefMsg1 = ndefMsg;
                 新DownloadFilesTask()执行()。
                  ndefMsg = NULL;
            }
            其他
            {
                AlertDialog.Builder对话框=新AlertDialog.Builder(本);
                dialog.setTitle(注意);
                dialog.setMessage(无Internet连接,请启用无线网络。);
                dialog.setPositiveButton(OK,新DialogInterface.OnClickListener(){
                    公共无效的onClick(DialogInterface对话,诠释whichButton)
                    {
                    }
                });
                dialog.show();
            }
        }
    }
    私有类DownloadFilesTask扩展的AsyncTask&LT;虚空,虚空,虚空&GT; {
        保护无效onPostExecute(无效的结果){
        }
        @覆盖
        保护无效doInBackground(虚空...... PARAMS){
            尝试 {
                URL myFileUrl =新的URL(http://sposter.smartag.my/images/chicken_soup.jpg);
                HttpURLConnection的康恩=(HttpURLConnection类)myFileUrl.openConnection();
                conn.setDoInput(真正的);
                conn.connect();
                InputStream的是= conn.getInputStream();
                downloadBitmap = BitmapFactory.de codeStream(是);
                            }赶上(FileNotFoundException异常E){
                e.printStackTrace();
            }
            赶上(IOException异常E){
                e.printStackTrace();
            }
            ImageView的形象=(ImageView的)findViewById(R.id.imview);
            image.setImageBitmap(downloadBitmap);
            返回null;
        }
    }
}
 

解决方案

使用的不良做法的AsyncTask

您尝试更新从您的主UI线程doInBackGround()为AsyncTask的绝对不允许的。

从不更新从你的UI doInBackGround()的AsyncTask作为其唯一的工作线程。所以,写你的主UI updatation $ C $在 onPostExecute C() AsyncTask的..

的方法

  @覆盖
        保护无效doInBackground(虚空...... PARAMS){
            尝试 {
                URL myFileUrl =新的URL(http://sposter.smartag.my/images/chicken_soup.jpg);
                HttpURLConnection的康恩=(HttpURLConnection类)myFileUrl.openConnection();
                conn.setDoInput(真正的);
                conn.connect();
                InputStream的是= conn.getInputStream();
                downloadBitmap = BitmapFactory.de codeStream(是);
                            }赶上(FileNotFoundException异常E){
                e.printStackTrace();
            }
            赶上(IOException异常E){
                e.printStackTrace();
            }
            返回null;
        }

@覆盖
onPostExecute()
{
 ImageView的形象=(ImageView的)findViewById(R.id.imview);
            image.setImageBitmap(downloadBitmap);
}
 

Possible Duplicate:
Android - ViewRootImpl$CalledFromWrongThreadException

Im trying to get image from my URL and display in application but it throw error Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. Below is my code

Code

package com.smartag.bird.dev;

public class MainActivity extends Activity {
    static String ndefMsg = null;
    static String ndefMsg1 = null;
    NfcAdapter mNfcAdapter;
    PendingIntent mNfcPendingIntent;
    IntentFilter[] mNdefExchangeFilters;
    static final String TAG = "Read Tag";
    TextView mTitle;
    private static ImageView imageView;
    static String url = "http://sposter.smartag.my/images/chicken_soup.jpg";
    private static Bitmap downloadBitmap;
    private static BitmapDrawable bitmapDrawable;
    private static boolean largerImg = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);            
        //setContentView(R.layout.main);
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        mNfcPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndefDetected.addDataType("text/plain");
        } catch (MalformedMimeTypeException e) { }
        mNdefExchangeFilters = new IntentFilter[] { ndefDetected };  
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            NdefMessage[] messages = getNdefMessages(getIntent());
            byte[] payload = messages[0].getRecords()[0].getPayload();
            ndefMsg = new String(payload);           
            setIntent(new Intent()); // Consume this intent.
        }

        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if(ndefMsg == null || ndefMsg.length() == 0)
        {               
            startActivity(new Intent(MainActivity.this, MainMenu.class));               
        }            
        else
        {
            setContentView(R.layout.main);
            if (mWifi.isConnected()) {              
                ndefMsg1 = ndefMsg;
                 new DownloadFilesTask().execute(); 
                  ndefMsg = null;
            }
            else
            {                        
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                dialog.setTitle("Attention");
                dialog.setMessage("No Internet Connection. Please enable the wifi.");
                dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) 
                    {
                    }
                });
                dialog.show();
            }
        }           
    }
    private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
        protected void onPostExecute(Void result) {             
        }           
        @Override
        protected Void doInBackground(Void... params) {             
            try {
                URL myFileUrl = new URL("http://sposter.smartag.my/images/chicken_soup.jpg");
                HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream is = conn.getInputStream();
                downloadBitmap = BitmapFactory.decodeStream(is);
                            } catch (FileNotFoundException e) {             
                e.printStackTrace();
            }
            catch (IOException e) {         
                e.printStackTrace();
            }               
            ImageView image = (ImageView) findViewById(R.id.imview);            
            image.setImageBitmap(downloadBitmap);
            return null;
        }
    }
}

解决方案

Bad practice of use of AsyncTask,

You are trying to update your Main UI Thread from doInBackGround() as AsyncTask never allowed that.

Never update your UI from doInBackGround() of AsyncTask as its only worker thread. So write your Main UI updatation code in onPostExecute() method of AsyncTask..

@Override
        protected Void doInBackground(Void... params) {             
            try {
                URL myFileUrl = new URL("http://sposter.smartag.my/images/chicken_soup.jpg");
                HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream is = conn.getInputStream();
                downloadBitmap = BitmapFactory.decodeStream(is);
                            } catch (FileNotFoundException e) {             
                e.printStackTrace();
            }
            catch (IOException e) {         
                e.printStackTrace();
            }               
            return null;
        }

@Override
onPostExecute()
{
 ImageView image = (ImageView) findViewById(R.id.imview);            
            image.setImageBitmap(downloadBitmap);
}

这篇关于Android的 - 产生的原因:android.view.ViewRootImpl $ CalledFromWrongThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆