2023-11-08 12:50AM
MainActivity 文件代码如下:
package com.example.blogtitles;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static final String API_URL = "https://admin.meiyi.site/api/v1/blogs";
private ListView blogListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
blogListView = findViewById(R.id.blogListView);
// 执行异步任务来获取博客列表
new FetchBlogsTask().execute();
}
private class FetchBlogsTask extends AsyncTask<Void, Void, List<Blog>> {
@Override
protected List<Blog> doInBackground(Void... voids) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(API_URL)
.build();
try {
Response response = client.newCall(request).execute();
String jsonData = response.body().string();
return parseJsonData(jsonData);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(List<Blog> blogs) {
if (blogs != null) {
// 创建适配器
BlogTitleAdapter adapter = new BlogTitleAdapter(MainActivity.this, blogs);
// 设置适配器
blogListView.setAdapter(adapter);
}
}
}
private List<Blog> parseJsonData(String jsonData) {
List<Blog> blogs = new ArrayList<>();
try {
JSONObject json = new JSONObject(jsonData);
JSONArray jsonArray = json.getJSONArray("blogs");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString("title");
// 如果有content字段,解析content
String content = jsonObject.optString("content", "");
Blog blog = new Blog(title, content);
blogs.add(blog);
}
} catch (JSONException e) {
e.printStackTrace();
}
return blogs;
}
private class Blog {
private String title;
private String content;
public Blog(String title, String content) {
this.title = title;
this.content = content;
}
public String getTitle() {
return title;
}
public String getContent() {
return content;
}
}
private class BlogTitleAdapter extends ArrayAdapter<Blog> {
public BlogTitleAdapter(MainActivity context, List<Blog> blogs) {
super(context, 0, blogs);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
}
Blog blog = getItem(position);
TextView titleTextView = convertView.findViewById(android.R.id.text1);
titleTextView.setText(blog.getTitle());
return convertView;
}
}
}
activity_main.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="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/blogListView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
AndroidMainfest.xml文件代码如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.blogtitles">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.BlogTitles"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle(:app)文件的代码如下:
plugins {
id 'com.android.application'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.example.blogtitles"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
// 网络请求库
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
// JSON解析库
implementation 'com.google.code.gson:gson:2.8.8'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
登录
请登录后再发表评论。
评论列表:
目前还没有人发表评论