實現(xiàn)網絡加載商品數(shù)據(jù)的功能:
1、在AndroidManifest.xml中聲明網絡權限;
2、在app/build.gradle中添加okhttp, glide, gson等必需的第3方庫;
3、在MainActivity中通過OkHttpClient連接給定的Web服務,獲取商品數(shù)據(jù);對應的json數(shù)據(jù)為本地的json文件,名字為goods_list_data.json;數(shù)據(jù)內容為:[
{“id”:1,“count”:“5.4萬”,“goodsName”:“富士拍立得相機”,“goodsPic”:“/img/polaroid.png”},
{“id”:2,“count”:“5.3萬”,“goodsName”:“格蘭仕微波爐”,“goodsPic”:“/img/microwave_oven.png”},
{“id”:3,“count”:“1.4萬”,“goodsName”:“新國標電動車”,“goodsPic”:“/img/electric_vehicle.png”},
{“id”:4,“count”:“1.6萬”,“goodsName”:“官方訂制投影儀”,“goodsPic”:“/img/projector.png”},
{“id”:5,“count”:“0.4萬”,“goodsName”:“美的35L烤箱”,“goodsPic”:“/img/oven.png”},
{“id”:6,“count”:“3.3萬”,“goodsName”:“兒童學習桌”,“goodsPic”:“/img/learning_table.png”}
]
對應的圖片也存儲在本地的img文件中
4、使用gson庫解析JSON格式的商品數(shù)據(jù),轉成java bean商品數(shù)據(jù)對象(Goods類)的列表;
5、創(chuàng)建MsgHandler類,用于異步更新商品列表;
6、在GoodsAdapter中通過glide控件加載并顯示網絡圖片。
1.部署網絡圖片資源
首先,我們需要將對應的文件部署在一個簡易的服務器(Tomcat)中,服務器中存放數(shù)據(jù)的目錄結構如下圖所示
E:.
├─goods
│ └─img
│ └─goods_list_data.json
└─WEB-INF
其中,ROOT目錄在"apache-tomcat-9.0.65-windows-x64\webapps\ROOT"
下,表示Tomcat服務器的根目錄。
- goods文件夾存放的是商品列表所用到的數(shù)據(jù)
- 其中goods\img文件夾存放的是商品的圖片資源
-
goods_list_data.json
文件存放的是商品列表的數(shù)據(jù),具體如下所示
[
{"id":1,"count":"5.4萬","goodsName":"富士拍立得相機","goodsPic":"/img/polaroid.png"},
{"id":2,"count":"5.3萬","goodsName":"格蘭仕微波爐","goodsPic":"/img/microwave_oven.png"},
{"id":3,"count":"1.4萬","goodsName":"新國標電動車","goodsPic":"/img/electric_vehicle.png"},
{"id":4,"count":"1.6萬","goodsName":"官方訂制投影儀","goodsPic":"/img/projector.png"},
{"id":5,"count":"0.4萬","goodsName":"美的35L烤箱","goodsPic":"/img/oven.png"},
{"id":6,"count":"3.3萬","goodsName":"兒童學習桌","goodsPic":"/img/learning_table.png"}
]
啟動tomcat后,可訪問http://localhost:8080/goods/goods_list_data.json
展示信息
2.創(chuàng)建項目
- 打開Android Studio,并創(chuàng)建一個新的Android項目。
- 命名項目并選擇適當?shù)哪繕薃PI級別和設備類型。
- 創(chuàng)建一個新的空白活動(Empty Activity)。
3.在AndroidManifest.xml中聲明網絡權限
在 AndroidManifest.xml 文件中添加以下權限聲明,以便應用可以訪問網絡:
<uses-permission android:name="android.permission.INTERNET" />
由于網絡安全策略導致的問題,即不允許在明文(非加密)的情況下與 localhost 進行通信。這通常涉及到網絡安全配置,特別是在 Android 9.0(API級別28)及更高版本中引入了更嚴格的網絡安全策略;因此我們還需要進行配置網絡安全配置文件
解決此問題的方法之一是使用 HTTPS 協(xié)議而不是 HTTP,因為 HTTPS 是加密的。
如果在本地測試應用,可以使用 Android 的網絡安全配置文件
來允許明文通信。
- 在
res/xml
文件夾中創(chuàng)建一個名為network_security_config.xml
的網絡安全配置文件。如果該文件夾不存在,請手動創(chuàng)建。
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
<certificates src="user" />
</trust-anchors>
</base-config>
</network-security-config>
- 在
AndroidManifest.xml
文件中,將這個網絡安全配置文件應用于你的應用。在<application>
元素內添加android:networkSecurityConfig
屬性,如下所示:
<application
android:networkSecurityConfig="@xml/network_security_config"
<!-- 其他屬性和元素 -->
>
<!-- 其他元素 -->
</application>
這將允許你的應用在本地開發(fā)和測試過程中與 localhost 進行明文通信。但請注意,在生產環(huán)境中,強烈建議使用 HTTPS 以確保數(shù)據(jù)的安全傳輸。
如果你使用的是模擬器或真機設備,請確保重新構建和部署應用,以使配置生效。此外,如果你的服務器正在本地運行,請確保服務器端口和地址正確。
4.添加依賴庫
在app/build.gradle
文件中添加OkHttp、Glide、Gson依賴庫。
implementation("com.squareup.okhttp3:okhttp:4.9.1")
implementation("com.squareup.okhttp3:logging-interceptor:4.9.1")
implementation("com.google.code.gson:gson:2.8.8")
implementation("com.github.bumptech.glide:glide:4.12.0")
annotationProcessor("com.github.bumptech.glide:compiler:4.12.0")
進行同步
等待安裝依賴……
5.創(chuàng)建一個XML布局文件
在res/layout
文件夾中創(chuàng)建一個布局文件,例如activity_main.xml
,用于顯示商品數(shù)據(jù)。
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>
創(chuàng)建一個XML布局文件用于顯示商品項
在res/layout
文件夾中創(chuàng)建一個布局文件,例如item_goods.xml
,用于顯示每個商品項。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:id="@+id/goodsImageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="centerCrop" />
<TextView
android:id="@+id/goodsNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp" />
</LinearLayout>
6.創(chuàng)建一個Java Bean類
創(chuàng)建一個Goods
類,用于表示商品數(shù)據(jù)。
public class Goods {
private int id;
private String count;
private String goodsName;
private String goodsPic;
// Getters and setters
}
7.創(chuàng)建一個適配器類
創(chuàng)建一個自定義適配器類GoodsAdapter
,用于將商品數(shù)據(jù)綁定到RecyclerView中。
public class GoodsAdapter extends RecyclerView.Adapter<GoodsAdapter.ViewHolder> {
private List<Goods> goodsList;
private Context context;
public GoodsAdapter(Context context, List<Goods> goodsList) {
this.context = context;
this.goodsList = goodsList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_goods, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Goods goods = goodsList.get(position);
holder.goodsNameTextView.setText(goods.getGoodsName());
// Load and display image using Glide
Glide.with(context)
.load(goods.getGoodsPic())
.into(holder.goodsImageView);
}
@Override
public int getItemCount() {
if (goodsList != null) {
return goodsList.size();
} else {
return 0; // 返回0表示沒有數(shù)據(jù)
}
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView goodsNameTextView;
ImageView goodsImageView;
ViewHolder(View itemView) {
super(itemView);
goodsNameTextView = itemView.findViewById(R.id.goodsNameTextView);
goodsImageView = itemView.findViewById(R.id.goodsImageView);
}
}
}
8.實現(xiàn)網絡加載數(shù)據(jù)
在MainActivity.java
中實現(xiàn)網絡加載商品數(shù)據(jù)的功能。請確保你的goods_list_data.json
文件位于app/src/main/assets
文件夾下。
package com.leo.network;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private GoodsAdapter adapter;
private List<Goods> goodsList;
private static final int MSG_UPDATE_DATA = 1;
private Handler msgHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (msg.what == MSG_UPDATE_DATA) {
adapter.notifyDataSetChanged();
}
return true;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new GoodsAdapter(this, goodsList);
recyclerView.setAdapter(adapter);
// Fetch data from the network
fetchGoodsData();
}
private void fetchGoodsData() {
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://10.0.2.2:8080/goods/goods_list_data.json")
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String jsonData = response.body().string();
Log.d("Network", "Data fetched successfully: " + jsonData);
Gson gson = new Gson();
Goods[] goodsArray = gson.fromJson(jsonData, Goods[].class);
// 補全圖片URL
for (Goods goods : goodsArray) {
goods.setGoodsPic("http://10.0.2.2:8080//goods" + goods.getGoodsPic());
}
goodsList = Arrays.asList(goodsArray);
msgHandler.sendEmptyMessage(MSG_UPDATE_DATA);
// 切換到主線程以更新UI
runOnUiThread(new Runnable() {
@Override
public void run() {
// 設置RecyclerView的適配器
adapter = new GoodsAdapter(MainActivity.this, goodsList);
recyclerView.setAdapter(adapter);
}
});
}
} catch (IOException e) {
e.printStackTrace();
Log.e("Network", "Error fetching data: " + e.getMessage());
}
}
}).start();
}
}
替換"URL_TO_YOUR_JSON_DATA"
為你的本地JSON文件的路徑,例如:http://localhost:8080/goods/goods_list_data.json
。
注意,如果你是本地部署的tomcat,需要在Android默認的虛擬器中訪問,需要改為“
10.0.2.2
”
以下是對代碼的一些說明:
-
在
fetchGoodsData()
方法中創(chuàng)建了一個新的線程來執(zhí)行網絡請求。這是一個良好的實踐,因為它確保網絡請求不會阻塞主線程,以避免應用的響應性問題。 -
在網絡請求成功后使用 Gson 庫將 JSON 數(shù)據(jù)解析為
Goods
對象的數(shù)組,并補全了圖片的URL。這確保了 Glide 能夠正確加載圖片。 -
使用
Handler
來更新UI,因為 UI更新必須在主線程中執(zhí)行。 -
在網絡請求失敗時,通過
Log.e
打印了錯誤消息,這有助于調試和問題排查。文章來源:http://www.zghlxwxcb.cn/news/detail-721233.html
實現(xiàn)效果文章來源地址http://www.zghlxwxcb.cn/news/detail-721233.html
到了這里,關于Android應用:實現(xiàn)網絡加載商品數(shù)據(jù)【OKHttp、Glide、Gson】的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!