在网络接口 http://192,168.1.100:8080/news/getnewslist 中提供了如下所示的 json 数组格式的返回数据[{“id”:1001,"title":“程序员因写代码太乱被杀告”,“detail":"凶手是死者同事,維护死者代码时完全看不懂而痛下杀手","comment”:16359, ”Image":“http://192.168.1.100:8080/news/images/6.jpg" 请编android写程序,访问该接口获取数据,解折后将数据显示到界面的控件上,同时将数据保存到本地的SQlite数据車中
时间: 2024-04-07 14:29:52 浏览: 154
Open with http://json.parser.online.fr/-crx插件
好的,这是一个比较复杂的问题,需要分步骤来回答,我会尽量详细地解答。
首先,我们需要使用网络请求库来获取该接口返回的数据。这里我推荐使用 Android 中内置的 HttpUrlConnection 或者第三方库 OkHttp,这里我以 OkHttp 为例:
```java
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://192.168.1.100:8080/news/getnewslist")
.build();
Response response = client.newCall(request).execute();
String jsonData = response.body().string(); // 获取响应的 JSON 数据
JSONArray jsonArray = new JSONArray(jsonData); // 将响应的 JSON 数据转换为 Java JSONArray 对象
```
接下来,我们需要将获取到的数据解析,并将其中的信息显示到界面的控件上。这里我假设你使用了 Android 中的布局文件来创建界面,你可以在布局文件中添加 ListView 控件来显示新闻列表,另外可以使用 ImageView 控件来显示图片。具体的布局文件和适配器代码如下:
res/layout/activity_news_list.xml:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/news_list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
```
NewsAdapter.java:
```java
public class NewsAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private List<NewsItem> mData;
public NewsAdapter(Context context, List<NewsItem> data) {
mContext = context;
mData = data;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return mData.get(position).getId();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.news_item, null);
holder = new ViewHolder();
holder.imgView = convertView.findViewById(R.id.news_img);
holder.titleView = convertView.findViewById(R.id.news_title);
holder.detailView = convertView.findViewById(R.id.news_detail);
holder.commentView = convertView.findViewById(R.id.news_comment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
NewsItem item = mData.get(position);
holder.titleView.setText(item.getTitle());
holder.detailView.setText(item.getDetail());
holder.commentView.setText(mContext.getString(R.string.comment_count, item.getComment()));
// 下载图片并显示
Picasso.get().load(item.getImgUrl()).into(holder.imgView);
return convertView;
}
static class ViewHolder {
ImageView imgView;
TextView titleView;
TextView detailView;
TextView commentView;
}
}
```
res/layout/news_item.xml:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="@+id/news_img"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="centerCrop" />
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:paddingLeft="8dp">
<TextView
android:id="@+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="@android:color/black" />
<TextView
android:id="@+id/news_detail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="@android:color/darker_gray" />
<TextView
android:id="@+id/news_comment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="@android:color/black" />
</LinearLayout>
</LinearLayout>
```
接下来,在 Activity 中我们需要对 ListView 控件进行初始化,并为其设置适配器。具体代码如下:
```java
public class NewsListActivity extends AppCompatActivity {
private List<NewsItem> mData = new ArrayList<>();
private NewsAdapter mAdapter;
private ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_list);
mListView = findViewById(R.id.news_list_view);
// 获取新闻列表数据并解析
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://192.168.1.100:8080/news/getnewslist")
.build();
Response response = client.newCall(request).execute();
String jsonData = response.body().string();
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("id");
String title = jsonObject.getString("title");
String detail = jsonObject.getString("detail");
int comment = jsonObject.getInt("comment");
String imgUrl = jsonObject.getString("Image");
mData.add(new NewsItem(id, title, detail, comment, imgUrl));
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
mAdapter = new NewsAdapter(this, mData);
mListView.setAdapter(mAdapter);
}
}
```
最后,我们需要将获取到的数据保存到本地的 SQLite 数据库中。这里我推荐使用 Android 中的 SQLiteOpenHelper 类来操作 SQLite 数据库。具体代码如下:
```java
public class NewsDbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "news.db";
public NewsDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS news ("
+ "id INTEGER PRIMARY KEY,"
+ "title TEXT,"
+ "detail TEXT,"
+ "comment INTEGER,"
+ "img BLOB"
+ ")");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 数据库升级时的处理
}
public void insertNewsList(List<NewsItem> newsList) {
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
for (NewsItem item : newsList) {
// 下载图片并转换为 byte 数组
byte[] imgBytes = downloadImage(item.getImgUrl());
ContentValues values = new ContentValues();
values.put("id", item.getId());
values.put("title", item.getTitle());
values.put("detail", item.getDetail());
values.put("comment", item.getComment());
values.put("img", imgBytes);
db.insertOrThrow("news", null, values);
}
db.setTransactionSuccessful();
} catch (IOException e) {
e.printStackTrace();
} finally {
db.endTransaction();
}
}
private byte[] downloadImage(String imgUrl) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(imgUrl).build();
Response response = client.newCall(request).execute();
return response.body().bytes();
}
}
```
在 Activity 中我们需要创建 NewsDbHelper 对象,并调用其 insertNewsList() 方法将新闻列表数据保存到 SQLite 数据库中。具体代码如下:
```java
public class NewsListActivity extends AppCompatActivity {
private List<NewsItem> mData = new ArrayList<>();
private NewsAdapter mAdapter;
private ListView mListView;
private NewsDbHelper mDbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_list);
mDbHelper = new NewsDbHelper(this);
mListView = findViewById(R.id.news_list_view);
// 获取新闻列表数据并解析
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://192.168.1.100:8080/news/getnewslist")
.build();
Response response = client.newCall(request).execute();
String jsonData = response.body().string();
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("id");
String title = jsonObject.getString("title");
String detail = jsonObject.getString("detail");
int comment = jsonObject.getInt("comment");
String imgUrl = jsonObject.getString("Image");
mData.add(new NewsItem(id, title, detail, comment, imgUrl));
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
mAdapter = new NewsAdapter(this, mData);
mListView.setAdapter(mAdapter);
// 将新闻列表数据保存到 SQLite 数据库中
mDbHelper.insertNewsList(mData);
}
@Override
protected void onDestroy() {
super.onDestroy();
mDbHelper.close();
}
}
```
以上就是我对这个问题的解答,希望能够帮助到你。
阅读全文