【问题标题】:android - Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException [duplicate]android - 引起:android.view.ViewRootImpl$CalledFromWrongThreadException [重复]
【发布时间】:2012-06-27 13:53:31
【问题描述】:

可能重复:
Android - ViewRootImpl$CalledFromWrongThreadException

我试图从我的 URL 获取图像并显示在应用程序中,但它抛出错误 原因:android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能接触其视图 .下面是我的代码

代码

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;
        }
    }
}

【问题讨论】:

  • 对不起,我的错...我早些时候提出了这个问题。感谢您的更新。
  • UI的改变必须在'onPostExecute'中完成

标签: java android image url


【解决方案1】:

使用 AsyncTask 的错误做法,

您正在尝试从 doInBackGround() 更新您的主 UI 线程,因为 AsyncTask 从未允许这样做。

永远不要从 AsyncTask 的 doInBackGround() 作为其唯一的工作线程来更新您的 UI。因此,在 AsyncTask 的 onPostExecute() 方法中编写主 UI 更新代码..

@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);
}

【讨论】:

  • 为什么你说不好的做法......请指教。谢谢
【解决方案2】:

将为@user370305 所说的内容加分,

您不能在非 ui 线程中触摸 UI 元素。

如果你使用AsyncTaskdoInBackground在非ui线程中执行所以你不能访问ImageView。

您可以访问onPreExecute,onProgressUpdate & onPostExcecute 中的 UI 元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多