说明:一个数据库的框架
(1)添加引用
def room_version = "2.2.5" implementation "androidx.room:room-runtime:$room_version" annotationProcessor "androidx.room:room-compiler:$room_version" implementation 'androidx.recyclerview:recyclerview:1.1.0' implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
(2)主界面
package com.example.sqlitedemo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.sqlitedemo.adapter.BuyListAdapter;
import com.example.sqlitedemo.model.BuyItem;
import com.example.sqlitedemo.viewmodel.MainViewModel;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private MainViewModel mainViewModel;
private BuyListAdapter adapter;
private Button btn_main;
private int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);
mainViewModel.getAllDataItemsFromViewModel().observe(this,
new Observer<List<BuyItem>>() {
@Override
public void onChanged(List<BuyItem> buyItems) {
//设置数据源
adapter.updateAdapter(buyItems);
}
});
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new BuyListAdapter(this);
recyclerView.setAdapter(adapter);
btn_main = findViewById(R.id.btn_main);
btn_main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addItem();
}
});
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
mainViewModel.removeItemFromDB(adapter.getCurrentBuyItem(viewHolder.getAdapterPosition()));
}
}).attachToRecyclerView(recyclerView);
}
private void addItem() {
count++;
BuyItem buyItem = new BuyItem();
buyItem.setName("序号"+count);
buyItem.setAmount("时段"+count);
buyItem.setPath("视频源"+count);
buyItem.setChannel("节目通道"+count);
buyItem.setTimestamp(String.valueOf(System.currentTimeMillis()/1000).toString());
mainViewModel.insertItemDB(buyItem);
}
}
(3)model
package com.example.sqlitedemo.model;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "buy_item_table")
public class BuyItem {
@ColumnInfo(name = "id")
@PrimaryKey(autoGenerate = true)
private int mId;
@ColumnInfo(name = "name")
private String mName;
@ColumnInfo(name = "amount")
private String mAmount;
@ColumnInfo(name = "path")
private String mPath;
@ColumnInfo(name = "channel")
private String mChannel;
@ColumnInfo(name = "time")
private String mTimestamp;
public int getId() {
return mId;
}
public void setId(int mId) {
this.mId = mId;
}
public String getName() {
return mName;
}
public void setName(String mName) {
this.mName = mName;
}
public String getAmount() {
return mAmount;
}
public void setAmount(String mAmount) {
this.mAmount = mAmount;
}
public String getPath() {
return mPath;
}
public void setPath(String mPath) {
this.mPath = mPath;
}
public String getChannel() {
return mChannel;
}
public void setChannel(String mChannel) {
this.mChannel = mChannel;
}
public String getTimestamp() {
return mTimestamp;
}
public void setTimestamp(String mTimestamp) {
this.mTimestamp = mTimestamp;
}
}
(4)viewModel
package com.example.sqlitedemo.viewmodel;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.example.sqlitedemo.adapter.BuyListAdapter;
import com.example.sqlitedemo.database.BuyItemsRespository;
import com.example.sqlitedemo.model.BuyItem;
import java.util.List;
public class MainViewModel extends AndroidViewModel {
private BuyListAdapter mAdapter;
private BuyItemsRespository repository;
private LiveData<List<BuyItem>> allDataItems;
public MainViewModel(@NonNull Application application) {
super(application);
repository = BuyItemsRespository.getInstance(application);
allDataItems = repository.getAllItemsFromRepo();
}
public LiveData<List<BuyItem>> getAllDataItemsFromViewModel() {
return allDataItems;
}
public void insertItemDB(BuyItem buyItem) {
repository.insertItem(buyItem);
}
public void removeItemFromDB(BuyItem buyItem) {
repository.removeItem(buyItem);
}
}
(5)Dao 增加 修改 删除,注解方式,反射数据库参数
package com.example.sqlitedemo.database;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import com.example.sqlitedemo.model.BuyItem;
import java.util.List;
@Dao
public interface BuyItemDao {
@Insert
void insertItemToDB(BuyItem buyItem);
@Delete
void removeItemFromDB(BuyItem buyItem);
@Query("SELECT * FROM buy_item_table ORDER BY name DESC")
LiveData<List<BuyItem>> getAllItemsFromDB();
}
(6)DB,创建数据库 设置数据库版本,每次更新数据库,或者增加和减少字段的时候,都需要升级数据库版本,不然会报错
package com.example.sqlitedemo.database;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.example.sqlitedemo.model.BuyItem;
@Database(entities = {BuyItem.class},version = 1)
public abstract class BuyItemDB extends RoomDatabase {
public static BuyItemDB instance;
public abstract BuyItemDao getBuyItemDao();
public static synchronized BuyItemDB getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(),
BuyItemDB.class,
"buy_items_database").fallbackToDestructiveMigration().build();
}
return instance;
}
}
(7)异步处理数据库的增加和删除操作
package com.example.sqlitedemo.database;
import android.app.Application;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import com.example.sqlitedemo.model.BuyItem;
import java.util.List;
public class BuyItemsRespository {
private BuyItemDao buyItemDao;
private LiveData<List<BuyItem>> listFromDB;
private static BuyItemsRespository mInstance = null;
public BuyItemsRespository(Application application) {
BuyItemDB database = BuyItemDB.getInstance(application);
buyItemDao = database.getBuyItemDao();
listFromDB = buyItemDao.getAllItemsFromDB();
}
public static BuyItemsRespository getInstance(Application application) {
if (mInstance == null) {
mInstance = new BuyItemsRespository(application);
}
return mInstance;
}
public LiveData<List<BuyItem>> getAllItemsFromRepo() {
return listFromDB;
}
public void insertItem(BuyItem buyItem) {
new InsertBuyItemAsyncTask(buyItemDao).execute(buyItem);
}
public void removeItem(BuyItem buyItem) {
new RemoveBuyItemAsyncTask(buyItemDao).execute(buyItem);
}
private static class InsertBuyItemAsyncTask extends AsyncTask<BuyItem, Void, Void> {
private BuyItemDao buyItemDao;
public InsertBuyItemAsyncTask(BuyItemDao buyItemDao) {
this.buyItemDao = buyItemDao;
}
@Override
protected Void doInBackground(BuyItem... buyItems) {
buyItemDao.insertItemToDB(buyItems[0]);
return null;
}
}
private static class RemoveBuyItemAsyncTask extends AsyncTask<BuyItem, Void, Void> {
private BuyItemDao buyItemDao;
public RemoveBuyItemAsyncTask(BuyItemDao buyItemDao) {
this.buyItemDao = buyItemDao;
}
@Override
protected Void doInBackground(BuyItem... buyItems) {
buyItemDao.removeItemFromDB(buyItems[0]);
return null;
}
}
}
(8)RecycleView适配器
package com.example.sqlitedemo.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.sqlitedemo.R;
import com.example.sqlitedemo.model.BuyItem;
import java.util.ArrayList;
import java.util.List;
public class BuyListAdapter extends RecyclerView.Adapter<BuyListAdapter.BuyListViewHolder> {
private List<BuyItem> mList = new ArrayList<>();
private BuyItem currentBuyItem;
private Context mContext;
public BuyListAdapter(Context mContext) {
this.mContext = mContext;
}
public class BuyListViewHolder extends RecyclerView.ViewHolder {
public TextView nameTv;
public TextView countTv;
public TextView pathTv;
public TextView channelTv;
View view;
public BuyListViewHolder(@NonNull View itemView) {
super(itemView);
nameTv = itemView.findViewById(R.id.textview_name_item);
countTv = itemView.findViewById(R.id.textview_amount_item);
pathTv = itemView.findViewById(R.id.textview_path_item);
channelTv = itemView.findViewById(R.id.textview_channel_item);
view = itemView;
}
}
@NonNull
@Override
public BuyListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.buy_item, parent, false);
return new BuyListViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull BuyListViewHolder holder, int position) {
currentBuyItem = mList.get(position);
holder.nameTv.setText(currentBuyItem.getName());
holder.countTv.setText(String.valueOf(currentBuyItem.getAmount()));
holder.itemView.setTag(currentBuyItem.getId());
holder.pathTv.setText(currentBuyItem.getPath());
holder.channelTv.setText(currentBuyItem.getChannel());
holder.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mContext,
"" + currentBuyItem.getId(),
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return mList.size();
}
public void updateAdapter(List<BuyItem> newList) {
this.mList = newList;
notifyDataSetChanged();
}
public BuyItem getCurrentBuyItem(int position) {
return mList.get(position);
}
}
end