草庐IT

java - 如何在android中从json数据在ImageView上显示图像

coder 2023-12-13 原文

我正在获取 json 数据。在那个 json 中,我有一个图像的 url。现在我想在 ImageView 中显示该图像。我怎样才能做到这一点?这是我的代码

class LoadInbox extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Home.this);
        pDialog.setMessage("Loading Inbox ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Inbox JSON
     * */
 protected String doInBackground(String... arg0) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        JSONObject json = userFunctions.homeData();

        Log.e("Data", json.toString());

        // Check your log cat for JSON reponse
        Log.d("Inbox JSON: ", json.toString());

        try {
            data = json.getJSONArray(TAG_DATA);
            Log.d("inbox array: ", data.toString());
            // looping through All messages
            for (int i = 0; i < data.length(); i++) {
                JSONObject c = data.getJSONObject(i);

                // Storing each json item in variable
                String profile_img = c.getString(TAG_PROFILE_IMG);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_PROFILE_IMG, profile_img);

                // adding HashList to ArrayList
                inboxList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        Home.this, inboxList,
                        R.layout.home_list_item, new String[] { TAG_PROFILE_IMG },
                        new int[] { R.id.profile_img2 });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

这是我的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ImageView 
    android:id="@+id/profile_img2" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="8dip"
    android:paddingLeft="8dip"
    android:paddingBottom="4dip" />
</RelativeLayout>

最佳答案

因此您需要创建另一个 AsyncTask,给定一个 URL 将加载图像,并填充一些控件。我通常会这样做:

ImageView imageView = (ImageView)findById(R.id.blah);
new ImageLoader( person.getImageUri(), imageView, 128, 128 ).execute();

ImageLoader 将是另一个像这样的 AsyncTask:

public class ImageLoader extends AsyncTask<URI,Integer,BitmapDrawable> {
    private Uri imageUri;

    private ImageView imageView;

    private int preferredWidth = 80;
    private int preferredHeight = 80;

    public ImageLoader( URI uri, ImageView imageView, int scaleWidth, int scaleHeight ) {
        this.imageUri = uri;
        this.imageView = imageView;
        this.preferredWidth = scaleWidth;
        this.preferredHeight = scaleHeight;
    }

    public BitmapDrawable doInBackground(URI... params) {
    if( imageUri == null ) return null;
    String url = imageUri.toString();
    if( url.length() == 0 ) return null;
    HttpGet httpGet = new HttpGet(url);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute( httpGet );
    InputStream is = new BufferedInputStream( response.getEntity().getContent() );
    try {
        Bitmap bitmap = BitmapFactory.decodeStream(is);
        if( preferredWidth > 0 && preferredHeight > 0 && bitmap.getWidth() > preferredWidth && bitmap.getHeight() > preferredHeight ) {
            return Bitmap.createScaledBitmap(bitmap, preferredWidth, preferredHeight, false);
        } else {
            return bitmap;
        }
    } finally {
        is.close();
    }
    }
}

    public void onPostExecute( BitmapDrawable drawable ) {
        imageView.setImageBitmap( drawable );
    }
}

然后,您可以通过创建自己的子类 ListAdapter,在图像绑定(bind)到 ListView 中时关闭此 AsyncTask。因此,您将不得不放弃使用 SimpleAdapter,因为事情不再简单了。这有很多优点,因此您只需加载正在显示的图像。这意味着从总数中加载的数量非常少。您的用户还可以在图像加载之前查看数据,从而更快地访问数据。如果您在现有的 AsyncTask 中执行此操作,您将加载每张图片,并且用户将不得不等待每张图片完成后再向用户显示数据。有一些事情可以通过这个来改进。一个 AsyncTask 使用自己的线程,因此您可能会同时运行很多线程(10 个或更多)。这可以杀死你的服务器与大量的客户。您可以使用 ExecutorService(即线程池)集中这些,但您必须放弃使用 AsyncTask 并实现您自己的工具以在 UI 线程之外运行作业并将结果发布回 UI 线程。其次,您的图像将在用户每次滚动时加载。为此,我根据图像的 URI 实现了自己的缓存方案,因此我只加载一次图像并从缓存中返回它。此处发布的代码有点多,但这些都是读者的练习。

另请注意,我没有在 onPostExecute() 中回发到 UI 线程。那是因为 AsyncTask 为我做了这件事,我不必像上面的代码所示那样再次做。您应该只删除那个额外的可运行对象并将代码内联到 onPostExecute() 中。

关于java - 如何在android中从json数据在ImageView上显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10885081/

有关java - 如何在android中从json数据在ImageView上显示图像的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  3. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  6. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  7. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  8. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  9. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  10. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

随机推荐