Using JSON to retrieve and display images from Tumblr
因此,我在这里完全不了解使用API?屑焖鳎允镜任侍狻N乙丫竦昧舜兴胁问柚玫鹊腏SON URL,但是我不知道如何在Android应用程序中表达这一点。我使用jsongen.com格式化所有内容并将JSON解析为java对象,但从那时起就一无所知。
Java代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | package com.android.tumblr.api; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; public class MainActivity extends Activity { ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { ImageView image = (ImageView)findViewById(R.id.tvImage); Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL("https://pbs.twimg.com/profile_images/423147305605554176/EYnBh68.jpeg") .getContent()); image.setImageBitmap(bitmap); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
布局的XML代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${packageName}.${activityClass}"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tvImage" android:minHeight="50dp" android:minWidth="50dp"/> </RelativeLayout> |
清单的XML代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.tumblr.api" android:versionCode="1" android:versionName="1.0"> <uses-permission android:name="android.permission.INTERNET" /> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name="com.android.tumblr.api.MainActivity" android:label="@string/title_activity_main"> </activity> </application> </manifest> |
您需要实现JSON解析器,并应考虑实现缓存管理器以提高性能。
对于Json解析器的实现,您有很多选择,但是根据我的经验-Gson和JsonParser是最好的。
Gson为您提供了从Java实体或gson的Java实体自动创建json的能力。
在这里,您可以找到一个很好的gson解析示例,并且可以从此处下载该库。
一个不错的开源缓存管理器,您可以在这里找到-bitmapFun,凌空,毕加索
如果您不想添加缓存管理器,则只需下载映像并执行:
1 2 | ImageView imageView = (ImageView)findViewById(R.id.image_view); imageView.setBitmap(bitmap); |
您可以在此处找到将该图像流化为位图的代码
尝试使用Retrofit库来实现REST客户端。毕加索足以将URL中的图像显示到ImageView
中