我尝试从URL获取图像(ImageGetter)

时间:2015-09-04 11:54:54

标签: android textview android-image androidhttpclient

我在TXT中有一个外部SQLite数据库。条目应该包含来自URL的文本和图像,因此,我在我的项目中实现了ImageGetter。但是当我将img src标记放在条目中时:< img src="https://www.backpacker.com.br/img/midia_site/uol.jpg">(我故意添加了一个空格&lt;故意)应用程序被强制关闭。

这是我的代码:

URLWorldActivity

public class URLWordActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.word);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    Uri uri = getIntent().getData();
    Cursor cursor = managedQuery(uri, null, null, null, null);

    if (cursor == null) {
        finish();
    } else {
        cursor.moveToFirst();

        TextView word = (TextView) findViewById(R.id.word);
        TextView definition = (TextView) findViewById(R.id.definition);

        int wIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_WORD);
        int dIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_DEFINITION);

        word.setText(Html.fromHtml(cursor.getString(wIndex)));

        URLImageParser p = new URLImageParser(definition, this);
        Spanned htmlSpan = Html.fromHtml(cursor.getString(dIndex), p, null);
        definition.setText(htmlSpan);

    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));     
        searchView.setIconifiedByDefault(false);


    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.search:
            onSearchRequested();
            return true;
        case android.R.id.home:
            Intent intent = new Intent(this, BancoDictionary.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            startActivity(intent);
            return true;
        default:
            return false;
    }
}



              public class URLImageParser implements ImageGetter {
            Context c;
            View container;

            /***
             * Construct the URLImageParser which will execute AsyncTask and refresh the container
             * @param t
             * @param c
             */
            public URLImageParser(View t, Context c) {
                this.c = c;
                this.container = t;
            }

            public Drawable getDrawable(String source) {
                URLDrawable urlDrawable = new URLDrawable();

                // get the actual source
                ImageGetterAsyncTask asyncTask = 
                    new ImageGetterAsyncTask( urlDrawable);

                asyncTask.execute(source);

                // return reference to URLDrawable where I will change with actual image from
                // the src tag
                return urlDrawable;
            }

            public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable>  {
                URLDrawable urlDrawable;

                public ImageGetterAsyncTask(URLDrawable d) {
                    this.urlDrawable = d;
                }

                @Override
                protected Drawable doInBackground(String... params) {
                    String source = params[0];
                    return fetchDrawable(source);
                }

                @Override
                protected void onPostExecute(Drawable result) {
                    // set the correct bound according to the result from HTTP call
                    urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0 
                            + result.getIntrinsicHeight()); 

                    // change the reference of the current drawable to the result
                    // from the HTTP call
                    urlDrawable.drawable = result;

                    // redraw the image by invalidating the container
                    URLImageParser.this.container.invalidate();
                }

                /***
                 * Get the Drawable from URL
                 * @param urlString
                 * @return
                 */
                public Drawable fetchDrawable(String urlString) {
                    try {
                        InputStream is = fetch(urlString);
                        Drawable drawable = Drawable.createFromStream(is, "src");
                        drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0 
                                + drawable.getIntrinsicHeight()); 
                        return drawable;
                    } catch (Exception e) {
                        return null;
                    } 
                }

                private InputStream fetch(String urlString) throws MalformedURLException, IOException {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpGet request = new HttpGet(urlString);
                    HttpResponse response = httpClient.execute(request);
                    return response.getEntity().getContent();
                }
            }
        }  
    }

URLDrawable

public class URLDrawable extends BitmapDrawable {
// the drawable that you need to set, you could set the initial drawing
// with the loading image if you need to
protected Drawable drawable;

@Override
public void draw(Canvas canvas) {
    // override the draw to facilitate refresh function later
    if(drawable != null) {
        drawable.draw(canvas);
    }
}
}

1 个答案:

答案 0 :(得分:0)

正如你告诉我你只想展示图像。我建议您使用图像加载库Picasso。它会使得从URL加载图像就像Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);一样简单,您甚至不需要关心使用UIThread。