gpt4 book ai didi

java - 使用 JSON 从 Tumblr 检索和显示图像

转载 作者:行者123 更新时间:2023-12-02 05:47:46 25 4
gpt4 key购买 nike

所以我对使用 API 进行检索、显示等方面完全一无所知。我已经获得了包含所有参数设置等的 JSON URL,但我不知道如何在 Android 应用程序中表达它。我使用 jsongen.com 来格式化所有内容并将 JSON 解析为 java 对象,但从那时起我就一无所知了。

Java 代码:

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代码

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

list 的XML代码

<?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 实体自动创建 json 或从 gson 创建 java 实体的能力。 Here你可以找到一个很好的 gson 解析示例,来自 here您可以下载该库。

您可以在这里找到一个很好的开源缓存管理器 - bitmapFun , volley , picasso

如果您不想添加缓存管理器,您只需下载图像并执行:

ImageView imageView = (ImageView)findViewById(R.id.image_view);
imageView.setBitmap(bitmap);

您可以找到here将图像流式传输至位图的代码

关于java - 使用 JSON 从 Tumblr 检索和显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23887739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com