Android studio 实现新闻展示列表,并实现增删改查的具体代码
时间: 2024-03-13 19:42:58 浏览: 150
好的,以下是一个简单的 Android Studio 实现新闻展示列表和增删改查的示例代码:
1. 创建一个 News 类,包含新闻的标题、内容和发布时间等属性。
```java
public class News {
private int id;
private String title;
private String content;
private String time;
// 构造方法
public News(int id, String title, String content, String time) {
this.id = id;
this.title = title;
this.content = content;
this.time = time;
}
// getter 和 setter 方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
```
2. 创建一个数据库帮助类 DBHelper,用于创建和管理数据库和数据表。
```java
public class DBHelper 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"; // id 列名
private static final String COLUMN_TITLE = "title"; // title 列名
private static final String COLUMN_CONTENT = "content"; // content 列名
private static final String COLUMN_TIME = "time"; // time 列名
// 创建数据表的 SQL 语句
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_TITLE + " TEXT, " +
COLUMN_CONTENT + " TEXT, " +
COLUMN_TIME + " TEXT)";
// 构造方法
public DBHelper(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 IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
3. 创建一个 NewsDAO 类,用于对数据库进行增删改查操作。
```java
public class NewsDAO {
private DBHelper dbHelper;
// 构造方法
public NewsDAO(Context context) {
dbHelper = new DBHelper(context);
}
// 添加新闻
public boolean addNews(News news) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_TITLE, news.getTitle());
values.put(DBHelper.COLUMN_CONTENT, news.getContent());
values.put(DBHelper.COLUMN_TIME, news.getTime());
long result = db.insert(DBHelper.TABLE_NAME, null, values);
return result != -1;
}
// 删除新闻
public boolean deleteNews(int id) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
String whereClause = DBHelper.COLUMN_ID + "=?";
String[] whereArgs = {String.valueOf(id)};
int result = db.delete(DBHelper.TABLE_NAME, whereClause, whereArgs);
return result > 0;
}
// 修改新闻
public boolean updateNews(News news) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_TITLE, news.getTitle());
values.put(DBHelper.COLUMN_CONTENT, news.getContent());
values.put(DBHelper.COLUMN_TIME, news.getTime());
String whereClause = DBHelper.COLUMN_ID + "=?";
String[] whereArgs = {String.valueOf(news.getId())};
int result = db.update(DBHelper.TABLE_NAME, values, whereClause, whereArgs);
return result > 0;
}
// 查询新闻列表
public List<News> queryNewsList() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] columns = {DBHelper.COLUMN_ID, DBHelper.COLUMN_TITLE, DBHelper.COLUMN_CONTENT, DBHelper.COLUMN_TIME};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns, null, null, null, null, null);
List<News> newsList = new ArrayList<>();
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_ID));
String title = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_TITLE));
String content = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_CONTENT));
String time = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_TIME));
News news = new News(id, title, content, time);
newsList.add(news);
}
cursor.close();
return newsList;
}
// 查询单个新闻
public News queryNews(int id) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] columns = {DBHelper.COLUMN_ID, DBHelper.COLUMN_TITLE, DBHelper.COLUMN_CONTENT, DBHelper.COLUMN_TIME};
String selection = DBHelper.COLUMN_ID + "=?";
String[] selectionArgs = {String.valueOf(id)};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns, selection, selectionArgs, null, null, null);
News news = null;
if (cursor.moveToFirst()) {
String title = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_TITLE));
String content = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_CONTENT));
String time = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_TIME));
news = new News(id, title, content, time);
}
cursor.close();
return news;
}
}
```
4. 创建一个 NewsAdapter 类,用于将新闻列表数据绑定到 RecyclerView 上。
```java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<News> newsList;
private OnItemClickListener onItemClickListener;
// 构造方法
public NewsAdapter(List<News> newsList) {
this.newsList = newsList;
}
// 设置点击事件监听器
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
// 创建 ViewHolder
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
// 绑定 ViewHolder
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
News news = newsList.get(position);
holder.title.setText(news.getTitle());
holder.content.setText(news.getContent());
holder.time.setText(news.getTime());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(v, position);
}
}
});
}
// 获取新闻列表数量
@Override
public int getItemCount() {
return newsList.size();
}
// ViewHolder 类
static class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView content;
TextView time;
// 构造方法
public ViewHolder(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.tv_title);
content = itemView.findViewById(R.id.tv_content);
time = itemView.findViewById(R.id.tv_time);
}
}
// 点击事件监听器接口
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
}
```
5. 创建一个 NewsListActivity 类,用于展示新闻列表和实现增删改查操作。
```java
public class NewsListActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private NewsAdapter newsAdapter;
private List<News> newsList;
private NewsDAO newsDAO;
// 初始化方法
private void init() {
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
newsList = new ArrayList<>();
newsAdapter = new NewsAdapter(newsList);
newsAdapter.setOnItemClickListener(new NewsAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
// 点击事件处理
}
});
recyclerView.setAdapter(newsAdapter);
newsDAO = new NewsDAO(this);
refreshNewsList();
}
// 刷新新闻列表
private void refreshNewsList() {
newsList.clear();
newsList.addAll(newsDAO.queryNewsList());
newsAdapter.notifyDataSetChanged();
}
// 添加新闻
private void addNews() {
// 弹出对话框,获取新闻标题、内容和发布时间等信息
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("添加新闻");
View view = LayoutInflater.from(this).inflate(R.layout.dialog_add_news, null);
EditText titleEditText = view.findViewById(R.id.et_title);
EditText contentEditText = view.findViewById(R.id.et_content);
EditText timeEditText = view.findViewById(R.id.et_time);
builder.setView(view);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String title = titleEditText.getText().toString();
String content = contentEditText.getText().toString();
String time = timeEditText.getText().toString();
News news = new News(0, title, content, time);
boolean result = newsDAO.addNews(news);
if (result) {
Toast.makeText(NewsListActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
refreshNewsList();
} else {
Toast.makeText(NewsListActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("取消", null);
builder.show();
}
// 删除新闻
private void deleteNews(int id) {
boolean result = newsDAO.deleteNews(id);
if (result) {
Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
refreshNewsList();
} else {
Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
}
}
// 修改新闻
private void updateNews(int id) {
// 弹出对话框,获取新闻标题、内容和发布时间等信息
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("修改新闻");
View view = LayoutInflater.from(this).inflate(R.layout.dialog_update_news, null);
EditText titleEditText = view.findViewById(R.id.et_title);
EditText contentEditText = view.findViewById(R.id.et_content);
EditText timeEditText = view.findViewById(R.id.et_time);
builder.setView(view);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String title = titleEditText.getText().toString();
String content = contentEditText.getText().toString();
String time = timeEditText.getText().toString();
News news = new News(id, title, content, time);
boolean result = newsDAO.updateNews(news);
if (result) {
Toast.makeText(NewsListActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
refreshNewsList();
} else {
Toast.makeText(NewsListActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("取消", null);
builder.show();
}
// onCreate 方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_list);
init();
}
}
```
以上就是一个简单的 Android Studio 实现新闻展示列表和增删改查的示例代码。当然,这只是一个示例,具体的实现方法和代码可能会因为不同的需求而有所不同。
阅读全文