Android studio 实现新闻界面,并实现增删改查新闻具体代码
时间: 2023-12-30 07:05:03 浏览: 126
Android安卓期末大作业 新闻app 实现注册登录增删改查功能
5星 · 资源好评率100%
以下是一个简单的实现新闻列表界面,并实现增删改查新闻的代码示例,供参考:
1. 布局文件 `activity_main.xml`:
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/news_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 新闻类 `News.java`:
```java
public class News {
private String title;
private String summary;
private String publishTime;
public News(String title, String summary, String publishTime) {
this.title = title;
this.summary = summary;
this.publishTime = publishTime;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getPublishTime() {
return publishTime;
}
public void setPublishTime(String publishTime) {
this.publishTime = publishTime;
}
}
```
3. 接口类 `NewsService.java`:
```java
public interface NewsService {
@GET("news")
Call<List<News>> getNewsList();
}
```
4. 适配器类 `NewsAdapter.java`:
```java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<News> newsList;
public NewsAdapter(List<News> newsList) {
this.newsList = newsList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(newsList.get(position).getTitle());
holder.summary.setText(newsList.get(position).getSummary());
holder.publishTime.setText(newsList.get(position).getPublishTime());
}
@Override
public int getItemCount() {
return newsList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView summary;
TextView publishTime;
ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.news_title);
summary = itemView.findViewById(R.id.news_summary);
publishTime = itemView.findViewById(R.id.news_publish_time);
}
}
}
```
5. 新闻列表界面 `MainActivity.java`:
```java
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private NewsAdapter newsAdapter;
private List<News> newsList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.news_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
newsAdapter = new NewsAdapter(newsList);
recyclerView.setAdapter(newsAdapter);
// 请求服务器端的新闻数据
NewsService newsService = RetrofitClient.getRetrofit().create(NewsService.class);
Call<List<News>> call = newsService.getNewsList();
call.enqueue(new Callback<List<News>>() {
@Override
public void onResponse(Call<List<News>> call, Response<List<News>> response) {
newsList.addAll(response.body());
newsAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(Call<List<News>> call, Throwable t) {
Toast.makeText(MainActivity.this, "请求失败:" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
```
6. 数据库帮助类 `DatabaseHelper.java`:
```java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "news.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "news";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_TITLE = "title";
private static final String COLUMN_CONTENT = "content";
private static final String COLUMN_PUBLISH_TIME = "publish_time";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_TITLE + " TEXT NOT NULL, "
+ COLUMN_CONTENT + " TEXT NOT NULL, "
+ COLUMN_PUBLISH_TIME + " TEXT NOT NULL)";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
}
```
7. 内容提供器类 `NewsProvider.java`:
```java
public class NewsProvider extends ContentProvider {
private static final String AUTHORITY = "com.example.news.provider";
private static final String TABLE_NAME = "news";
private static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME);
private static final int NEWS_DIR = 1;
private static final int NEWS_ITEM = 2;
private DatabaseHelper databaseHelper;
private SQLiteDatabase db;
private static final UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, TABLE_NAME, NEWS_DIR);
uriMatcher.addURI(AUTHORITY, TABLE_NAME + "/#", NEWS_ITEM);
}
@Override
public boolean onCreate() {
databaseHelper = new DatabaseHelper(getContext());
db = databaseHelper.getWritableDatabase();
return true;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection,
@Nullable String selection, @Nullable String[] selectionArgs,
@Nullable String sortOrder) {
Cursor cursor = null;
switch (uriMatcher.match(uri)) {
case NEWS_DIR:
cursor = db.query(TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
break;
case NEWS_ITEM:
String newsId = uri.getPathSegments().get(1);
cursor = db.query(TABLE_NAME, projection, COLUMN_ID + "=?",
new String[] { newsId }, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
switch (uriMatcher.match(uri)) {
case NEWS_DIR:
return "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + TABLE_NAME;
case NEWS_ITEM:
return "vnd.android.cursor.item/vnd." + AUTHORITY + "." + TABLE_NAME;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
Uri uriReturn = null;
switch (uriMatcher.match(uri)) {
case NEWS_DIR:
case NEWS_ITEM:
long newId = db.insert(TABLE_NAME, null, values);
uriReturn = Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME + "/" + newId);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
return uriReturn;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
int deletedRows = 0;
switch (uriMatcher.match(uri)) {
case NEWS_DIR:
deletedRows = db.delete(TABLE_NAME, selection, selectionArgs);
break;
case NEWS_ITEM:
String newsId = uri.getPathSegments().get(1);
deletedRows = db.delete(TABLE_NAME, COLUMN_ID + "=?",
new String[] { newsId });
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
return deletedRows;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values,
@Nullable String selection, @Nullable String[] selectionArgs) {
int updatedRows = 0;
switch (uriMatcher.match(uri)) {
case NEWS_DIR:
updatedRows = db.update(TABLE_NAME, values, selection, selectionArgs);
break;
case NEWS_ITEM:
String newsId = uri.getPathSegments().get(1);
updatedRows = db.update(TABLE_NAME, values, COLUMN_ID + "=?",
new String[] { newsId });
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
return updatedRows;
}
}
```
8. 在 `AndroidManifest.xml` 中注册内容提供器:
```xml
<manifest ...>
<application ...>
<provider
android:name=".NewsProvider"
android:authorities="com.example.news.provider"
android:exported="true" />
</application>
</manifest>
```
以上是一个简单的实现新闻列表界面,并实现增删改查新闻的代码示例,具体实现还需根据实际需求进行调整和完善。
阅读全文