org.litepal.LitePal Java Examples

The following examples show how to use org.litepal.LitePal. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PlayerService.java    From Yuan-SxMusic with Apache License 2.0 6 votes vote down vote up
private void saveLocalSongInfo(int current) {
    //将歌曲的信息保存起来
    mLocalSongList = LitePal.findAll(LocalSong.class);
    Song song = new Song();
    LocalSong localSong = mLocalSongList.get(current);
    song.setPosition(current);
    song.setSongName(localSong.getName());
    song.setSinger(localSong.getSinger());
    song.setDuration(localSong.getDuration());
    song.setUrl(localSong.getUrl());
    song.setImgUrl(localSong.getPic());
    song.setSongId(localSong.getSongId());
    song.setQqId(localSong.getQqId());
    song.setOnline(false);
    song.setListType(Constant.LIST_TYPE_LOCAL);
    FileUtil.saveSong(song);
}
 
Example #2
Source File: UpdateUsingSaveMethodTest.java    From LitePal with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateM2OAssociationsOnMSide() {
	init();
	s1.setClassroom(c1);
	s2.setClassroom(c1);
	assertTrue(c1.save());
	assertTrue(c2.save());
	assertTrue(s1.save());
	assertTrue(s2.save());
	s1.setClassroom(c2);
	s2.setClassroom(c2);
	Calendar calendar = Calendar.getInstance();
	calendar.clear();
	calendar.set(1989, 7, 7, 0, 0, 0);
	s2.setBirthday(calendar.getTime());
	assertTrue(s1.save());
	assertTrue(s2.save());
	assertEquals(c2.get_id(), getForeignKeyValue(studentTable, classroomTable, s1.getId()));
	assertEquals(c2.get_id(), getForeignKeyValue(studentTable, classroomTable, s2.getId()));
	Student student2 = LitePal.find(Student.class, s2.getId());
	calendar.clear();
	calendar.set(1989, 7, 7, 0, 0, 0);
	assertEquals(calendar.getTimeInMillis(), student2.getBirthday().getTime());
}
 
Example #3
Source File: AddCountyActivity.java    From DongWeather with Apache License 2.0 6 votes vote down vote up
/**
 * 显示当前选择的省的所有城市
 */
public void queryCity(){
    titleText.setText(currentProvince.getProvinceName());
    cityList = LitePal.where("provinceId = ?", String.valueOf(currentProvince.getProvinceCode())).find(City.class);
    if (cityList.size() > 0) {
        dataList.clear();
        for(City city : cityList){
            dataList.add(city.getCityName());
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(0);
        currentLevel = LEVEL_CITY;
    }else {
        int provinceCode = currentProvince.getProvinceCode();
        String adress = baseAdress + "/" + provinceCode;
        showProgressDialog();
        queryForService(adress, LEVEL_CITY);
    }
}
 
Example #4
Source File: FeedFolderListManageFragment.java    From Focus with GNU General Public License v3.0 6 votes vote down vote up
private void createRecyclerView() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);

        feedFolders = LitePal.order("ordervalue").find(FeedFolder.class);
        //更新顺序
        for (int i = 0; i < feedFolders.size() ; i++) {
            feedFolders.get(i).setOrderValue(i+1);
            feedFolders.get(i).save();
        }
        //更新
        adapter = new FeedFolderListAdapter(feedFolders,getActivity());
        adapter.bindToRecyclerView(recyclerView);
        if (feedFolders.size() == 0){
            adapter.setEmptyView(R.layout.simple_empty_view,recyclerView);
        }

    }
 
Example #5
Source File: PlayerService.java    From Yuan-SxMusic with Apache License 2.0 6 votes vote down vote up
private void saveLoveInfo(int current) {
    mLoveList = orderList(LitePal.findAll(Love.class));
    Love love = mLoveList.get(current);
    Song song = new Song();
    song.setPosition(current);
    song.setSongId(love.getSongId());
    song.setQqId(love.getQqId());
    song.setSongName(love.getName());
    song.setSinger(love.getSinger());
    song.setUrl(love.getUrl());
    song.setImgUrl(love.getPic());
    song.setListType(Constant.LIST_TYPE_LOVE);
    song.setOnline(love.isOnline());
    song.setDuration(love.getDuration());
    song.setMediaId(love.getMediaId());
    song.setDownload(love.isDownload());
    FileUtil.saveSong(song);
}
 
Example #6
Source File: SumSampleActivity.java    From LitePal with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View view) {
	int result = 0;
	switch (view.getId()) {
	case R.id.sum_btn1:
		result = LitePal.sum(Singer.class, "age", Integer.TYPE);
		mResultText.setText(String.valueOf(result));
		break;
	case R.id.sum_btn2:
		try {
			result = LitePal.where("age > ?", mAgeEdit.getText().toString()).sum(
					Singer.class, "age", Integer.TYPE);
			mResultText.setText(String.valueOf(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
		break;
	default:
	}
}
 
Example #7
Source File: CountSampleActivity.java    From LitePal with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View view) {
	int result = 0;
	switch (view.getId()) {
	case R.id.count_btn1:
		result = LitePal.count(Singer.class);
		mResultText.setText(String.valueOf(result));
		break;
	case R.id.count_btn2:
		try {
			result = LitePal.where("age > ?", mAgeEdit.getText().toString()).count(
					Singer.class);
			mResultText.setText(String.valueOf(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
		break;
	default:
	}
}
 
Example #8
Source File: AlbumSongFragment.java    From Yuan-SxMusic with Apache License 2.0 6 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    getBundle();
    EventBus.getDefault().register(this);
    View view = null;
    if (mType == ALBUM_SONG) {
        view = inflater.inflate(R.layout.fragment_album_recycler, container, false);
        mRecycle = view.findViewById(R.id.normalView);
        LitePal.getDatabase();
    } else {
        view = inflater.inflate(R.layout.fragment_album_song, container, false);
        mScrollView = view.findViewById(R.id.scrollView);
        mDescTv = view.findViewById(R.id.tv_desc);
        mNameTv = view.findViewById(R.id.tv_album_name);
        mLanguageTv = view.findViewById(R.id.tv_language);
        mCompany = view.findViewById(R.id.tv_company);
        mPublicTimeTv = view.findViewById(R.id.tv_public_time);
        mTypeTv = view.findViewById(R.id.tv_album_type);
    }
    mLoading = view.findViewById(R.id.avi);
    mLoadingTv = view.findViewById(R.id.tv_loading);
    mNetworkErrorIv = view.findViewById(R.id.iv_network_error);

    return view;
}
 
Example #9
Source File: FeedListManageFragment.java    From Focus with GNU General Public License v3.0 6 votes vote down vote up
private void setRecyclerView(){
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(linearLayoutManager);

    feedList = LitePal.where("feedfolderid = ?", String.valueOf(mFeedFolderId)).find(Feed.class);

    //更新顺序
    for (int i = 0; i < feedList.size() ; i++) {
        feedList.get(i).setOrderValue(i+1);
        feedList.get(i).save();
    }


    //获取未读数目
    for (int i = 0;i<feedList.size();i++){
        int num = LitePal.where("feedid = ?", String.valueOf(feedList.get(i).getId())).count(FeedItem.class);
        feedList.get(i).setUnreadNum(num);
    }

    adapter = new FeedListManageAdapter(feedList,getActivity());
    adapter.bindToRecyclerView(recyclerView);

    if (feedList.size()==0){
        adapter.setEmptyView(R.layout.simple_empty_view,recyclerView);
    }
}
 
Example #10
Source File: RequestFeedListDataService.java    From Focus with GNU General Public License v3.0 6 votes vote down vote up
private void getFeedItems(String url){
            //将本地数据库的内容合并到列表中
            //找到当前feed url 本地数据库的内容
            List<Feed> tempList = LitePal.where("url = ?" ,url).find(Feed.class);
            if (tempList.size()>0){
                Feed temp = tempList.get(0);
//                ALog.d(temp);
                List<FeedItem> tempFeedItemList = LitePal.where("feedid = ?", String.valueOf(temp.getId())).find(FeedItem.class);
//                ALog.d("本地数据库信息url" + url + "订阅名称为"+ temp.getName() + "文章数目" + tempFeedItemList.size());

                //设置badguy
                for (int i = 0;i<tempFeedItemList.size();i++){
                    tempFeedItemList.get(i).setBadGuy(temp.isBadGuy());
                    tempFeedItemList.get(i).setChina(temp.isChina());
                }
                eList.addAll(tempFeedItemList);
            }
        }
 
Example #11
Source File: DeleteTest.java    From LitePal with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteAllCascadeO2OAssociations() {
	createStudentsTeachersWithIdCard();
	int affectedRows = LitePal.deleteAll(Student.class, "id = ?", String.valueOf(jude.getId()));
	assertEquals(2, affectedRows);
	assertNull(getStudent(jude.getId()));
	assertNull(getIdCard(judeCard.getId()));
	affectedRows = LitePal.deleteAll(IdCard.class, "id = ?", roseCard.getId() + "");
	assertEquals(2, affectedRows);
	assertNull(getStudent(rose.getId()));
	assertNull(getIdCard(roseCard.getId()));
	affectedRows = LitePal.deleteAll(Teacher.class, "id = ?", "" + john.getId());
	assertEquals(2, affectedRows);
	assertNull(getTeacher(john.getId()));
	assertNull(getIdCard(johnCard.getId()));
	affectedRows = LitePal.deleteAll(IdCard.class, "id=?", "" + mikeCard.getId());
	assertEquals(1, affectedRows);
	assertNull(getIdCard(mikeCard.getId()));
}
 
Example #12
Source File: SaveAllTest.java    From LitePal with Apache License 2.0 6 votes vote down vote up
@Test
public void testSaveAllWithM2OOnManySide() {
	Classroom classroom = new Classroom();
	classroom.setName("English room");
	List<Student> studentList = new ArrayList<Student>();
	for (int i = 0; i < 50; i++) {
		Student student = new Student();
		student.setName("Tom");
		student.setAge(new Random().nextInt(20));
		student.setClassroom(classroom);
		studentList.add(student);
	}
	assertTrue(LitePal.saveAll(studentList));
	classroom.save();
	List<Student> list = LitePal.where(classroomTable + "_id = ?",
			String.valueOf(classroom.get_id())).find(Student.class);
	assertEquals(50, list.size());
}
 
Example #13
Source File: TaskAddHtml.java    From pe-protector-moe with GNU General Public License v3.0 6 votes vote down vote up
public TaskAddHtml(WebView webview, HttpFinishCallBack callBack) {
    this.callBack = callBack;
    List<MapConfigBean> list = LitePal.findAll(MapConfigBean.class);
    List<String> name = new ArrayList<>();
    for (MapConfigBean m : list) {
        name.add(m.name);
    }
    webview.loadUrl("file:///android_asset/html/task.html");
    webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.loadUrl(String.format("javascript:onLoad(\'%s\')", JSON.toJSONString(name)));
        }
    });
}
 
Example #14
Source File: FeedListManageFragment.java    From Focus with GNU General Public License v3.0 6 votes vote down vote up
private void setRecyclerView(){
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(linearLayoutManager);

    feedList = LitePal.where("feedfolderid = ?", String.valueOf(mFeedFolderId)).find(Feed.class);

    //更新顺序
    for (int i = 0; i < feedList.size() ; i++) {
        feedList.get(i).setOrderValue(i+1);
        feedList.get(i).save();
    }


    //获取未读数目
    for (int i = 0;i<feedList.size();i++){
        int num = LitePal.where("feedid = ?", String.valueOf(feedList.get(i).getId())).count(FeedItem.class);
        feedList.get(i).setUnreadNum(num);
    }

    adapter = new FeedListManageAdapter(feedList,getActivity());
    adapter.bindToRecyclerView(recyclerView);

    if (feedList.size()==0){
        adapter.setEmptyView(R.layout.simple_empty_view,recyclerView);
    }
}
 
Example #15
Source File: UpdateUsingSaveMethodTest.java    From LitePal with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateGenericData() {
    Classroom classroom = new Classroom();
    classroom.setName("Classroom origin");
    classroom.getNews().add("n");
    classroom.getNews().add("e");
    classroom.getNews().add("w");
    classroom.getNumbers().add(1);
    classroom.getNumbers().add(2);
    classroom.getNumbers().add(3);
    classroom.save();
    classroom.setName("Classroom update");
    classroom.getNews().add("s");
    classroom.getNumbers().clear();
    classroom.save();
    Classroom c = LitePal.find(Classroom.class, classroom.get_id());
    assertEquals("Classroom update", c.getName());
    assertEquals(4, classroom.getNews().size());
    assertEquals(0, classroom.getNumbers().size());
    StringBuilder builder = new StringBuilder();
    for (String s : classroom.getNews()) {
        builder.append(s);
    }
    assertEquals("news", builder.toString());
}
 
Example #16
Source File: DbHelperImpl.java    From Yuan-SxMusic with Apache License 2.0 6 votes vote down vote up
@Override
public void insertAllAlbumSong(List<AlbumSong.DataBean.ListBean> songList) {
    LitePal.deleteAll(OnlineSong.class);
    for (int i = 0; i < songList.size(); i++) {
        AlbumSong.DataBean.ListBean song = songList.get(i);
        OnlineSong onlineSong = new OnlineSong();
        onlineSong.setId(i + 1);
        onlineSong.setName(song.getSongname());
        onlineSong.setSinger(song.getSinger().get(0).getName());
        onlineSong.setSongId(song.getSongmid());
        onlineSong.setDuration(song.getInterval());
        onlineSong.setPic(Api.ALBUM_PIC + song.getAlbummid()+Api.JPG);
        onlineSong.setUrl(null);
        onlineSong.setLrc(null);
        onlineSong.save();
    }
}
 
Example #17
Source File: UpdateUsingUpdateMethodTest.java    From LitePal with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateToDefaultValueWithInstanceUpdate() {
	Student s = new Student();
	s.setToDefault("age");
	s.setToDefault("name");
	s.setToDefault("birthday");
	int affectedStudent = s.update(student.getId());
	assertEquals(1, affectedStudent);
	Student newStudent = LitePal.find(Student.class, student.getId());
	assertNull(newStudent.getBirthday());
	assertNull(newStudent.getName());
	assertEquals(0, newStudent.getAge());
	Teacher t = new Teacher();
	t.setAge(45);
	t.setTeachYears(5);
	t.setTeacherName("John");
	t.setToDefault("teacherName");
	t.setToDefault("age");
	int affectedTeacher = t.update(teacher.getId());
	assertEquals(1, affectedTeacher);
	Teacher newTeacher = getTeacher(teacher.getId());
	assertEquals(22, newTeacher.getAge());
	assertEquals("", newTeacher.getTeacherName());
	assertEquals(5, newTeacher.getTeachYears());
}
 
Example #18
Source File: QueryMathTest.java    From LitePal with Apache License 2.0 6 votes vote down vote up
@Test
public void testMax() {
	int result = LitePal.max(Student.class, "age", Integer.TYPE);
	int realResult = -100;
	Cursor cursor = LitePal.findBySQL("select max(age) from " + studentTable);
	if (cursor.moveToFirst()) {
		realResult = cursor.getInt(0);
	}
	cursor.close();
	assertEquals(realResult, result);
	result = LitePal.where("age < ?", "20").max(studentTable, "age", Integer.TYPE);
	cursor = LitePal.findBySQL("select max(age) from " + studentTable + " where age < ?", "20");
	if (cursor.moveToFirst()) {
		realResult = cursor.getInt(0);
	}
	cursor.close();
	assertEquals(realResult, result);
}
 
Example #19
Source File: DownloadService.java    From Yuan-SxMusic with Apache License 2.0 6 votes vote down vote up
private void postDownloadEvent(DownloadInfo downloadInfo) {
    //如果需要下载的表中有该条歌曲,则添加到下载队列后跳过
    List<DownloadInfo> downloadInfoList =
            LitePal.where("songId = ?",downloadInfo.getSongId()).find(DownloadInfo.class,true);
    if (downloadInfoList.size() != 0){
        DownloadInfo historyDownloadInfo = downloadInfoList.get(0);
        historyDownloadInfo.setStatus(Constant.DOWNLOAD_WAIT);
        historyDownloadInfo.save();
        EventBus.getDefault().post(new DownloadEvent(Constant.DOWNLOAD_PAUSED,historyDownloadInfo));
        downloadQueue.offer(historyDownloadInfo);
        return;
    }

    position = LitePal.findAll(DownloadInfo.class).size();
    downloadInfo.setPosition(position);
    downloadInfo.setStatus(Constant.DOWNLOAD_WAIT); //等待
    downloadInfo.save();
    downloadQueue.offer(downloadInfo);//将歌曲放到等待队列中
    EventBus.getDefault().post(new DownloadEvent(Constant.TYPE_DOWNLOAD_ADD));
}
 
Example #20
Source File: UserPreference.java    From Focus with GNU General Public License v3.0 6 votes vote down vote up
public static void updateOrSaveValueByKeyAsync(final String key, final String value, final FindMultiCallback<UserPreference> callback){
    LitePal.where("key = ?", key).limit(0).findAsync(UserPreference.class).listen(new FindMultiCallback<UserPreference>() {
        @Override
        public void onFinish(List<UserPreference> list) {
            if (list.size() > 0) {//缓存中有该值
                UserPreference temp = list.get(0);
                temp.setValue(value);
                temp.save();
                //修改缓存中键值对
                if (map.containsKey(key)) {
                    map.remove(key);
                    map.put(key, value);
                }
            } else {
                setValueByKey(key, value);
            }

            callback.onFinish(list);
        }
    });
}
 
Example #21
Source File: TransactionTest.java    From LitePal with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionForUpdate() {
    Teacher teacher = new Teacher();
    teacher.setTeacherName("Tony");
    teacher.setTeachYears(3);
    teacher.setAge(23);
    teacher.setSex(false);
    Assert.assertTrue(teacher.save());
    LitePal.beginTransaction();
    ContentValues values = new ContentValues();
    values.put("TeachYears", 13);
    int rows = LitePal.update(Teacher.class, values, teacher.getId());
    Assert.assertEquals(1, rows);
    Teacher teacherFromDb = LitePal.find(Teacher.class, teacher.getId());
    Assert.assertEquals(13, teacherFromDb.getTeachYears());
    // not set transaction successful
    LitePal.endTransaction();
    teacherFromDb = LitePal.find(Teacher.class, teacher.getId());
    Assert.assertEquals(3, teacherFromDb.getTeachYears());
}
 
Example #22
Source File: UserPreference.java    From Focus with GNU General Public License v3.0 5 votes vote down vote up
public static void initCacheMap(){
    map.clear();
    LitePal.findAllAsync(UserPreference.class).listen(new FindMultiCallback<UserPreference>() {
        @Override
        public void onFinish(List<UserPreference> list) {
            for (UserPreference userPreference:list){
                map.put(userPreference.getKey(),userPreference.getValue());
            }
        }
    });
}
 
Example #23
Source File: QueryEagerTest.java    From LitePal with Apache License 2.0 5 votes vote down vote up
@Test
public void testEagerFindFirst() {
	resetData();
	Student s1 = LitePal.findFirst(Student.class);
	assertNull(s1.getClassroom());
	s1 = LitePal.findFirst(Student.class, true);
	assertNotNull(s1);
}
 
Example #24
Source File: App.java    From 12306XposedPlugin with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 数据库管理
 */
private void registerDatabaseManager() {
    LitePal.initialize(this);
    LitePal.registerDatabaseListener(new DatabaseListener() {
        @Override
        public void onCreate() {

        }

        @Override
        public void onUpgrade(int oldVersion, int newVersion) {

        }
    });
}
 
Example #25
Source File: PlayerService.java    From Yuan-SxMusic with Apache License 2.0 5 votes vote down vote up
private void saveOnlineSongInfo(int current) {
    mSongList = LitePal.findAll(OnlineSong.class);
    Song song = new Song();
    song.setPosition(current);
    song.setSongId(mSongList.get(current).getSongId());
    song.setSongName(mSongList.get(current).getName());
    song.setSinger(mSongList.get(current).getSinger());
    song.setDuration(mSongList.get(current).getDuration());
    song.setUrl(mSongList.get(current).getUrl());
    song.setImgUrl(mSongList.get(current).getPic());
    song.setOnline(true);
    song.setListType(Constant.LIST_TYPE_ONLINE);
    song.setMediaId(mSongList.get(current).getMediaId());
    FileUtil.saveSong(song);
}
 
Example #26
Source File: App.java    From Yuan-WanAndroid with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    mApp = this;
    LitePal.initialize(this);
    initBugly();
    initLeakCanary();
    mAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
}
 
Example #27
Source File: UpdateUsingUpdateMethodTest.java    From LitePal with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateWithStaticUpdateButWrongClass() {
	ContentValues values = new ContentValues();
	values.put("TEACHERNAME", "Toy");
	try {
           LitePal.update(Object.class, values, teacher.getId());
	} catch (SQLiteException e) {
	}
}
 
Example #28
Source File: CollectionFragment.java    From Yuan-SxMusic with Apache License 2.0 5 votes vote down vote up
@Subscribe(threadMode = ThreadMode.MAIN )
public void onMessageEvent(SongCollectionEvent songCollectionEvent){
    mLoveList.clear();
    mLoveList.addAll(orderList(LitePal.findAll(Love.class)));
    mAdapter.notifyDataSetChanged();
    if(songCollectionEvent.isLove()){//定位歌曲
        if (FileUtil.getSong() != null) {
            mManager.scrollToPositionWithOffset(FileUtil.getSong().getPosition() + 4, mRecycler.getHeight());
        }
    }
}
 
Example #29
Source File: AddTaskActivity.java    From 12306XposedPlugin with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 恢复数据
 */
private void restoreData() {
    if (targetId > 0) {
        LitePal.where("id=?", String.valueOf(targetId))
                .findFirstAsync(TaskDao.class).listen(new FindCallback<TaskDao>() {
            @Override
            public void onFinish(final TaskDao taskDao) {
                if (taskDao != null) {
                    passengerMap = new HashMap<>();
                    List<Passenger> users = taskDao.getPassengerList();
                    final List<String> userNameList = new ArrayList<>();
                    for (Passenger user : users) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("user_name", user.getName());
                            jsonObject.put("id_no", user.getId());
                            jsonObject.put("mobile_no", user.getPhone());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        userNameList.add(user.getName());
                        passengerMap.put(user.getName(), jsonObject);
                    }
                    startStation.setText(taskDao.getFromStationName());
                    endStation.setText(taskDao.getToStationName());
                    selectTimeText.setText(Utils.listToString(taskDao.getTrainDate()));
                    trainListText.setText(Utils.listToString(taskDao.getTrainList()));
                    uidText.setText(taskDao.getUid());
                    pwdText.setText(taskDao.getPwd());
                    selectUserText.setText(Utils.listToString(userNameList));
                    seatTypeText.setText(taskDao.getType());
                }
            }
        });
    }
}
 
Example #30
Source File: PlayerService.java    From Yuan-SxMusic with Apache License 2.0 5 votes vote down vote up
private void saveToHistoryTable() {

        final Song song = FileUtil.getSong();
        LitePal.where("songId=?", song.getSongId()).findAsync(HistorySong.class)
                .listen(new FindMultiCallback<HistorySong>() {
                    @Override
                    public void onFinish(List<HistorySong> list) {
                        if (list.size() == 1) {
                            LitePal.deleteAll(HistorySong.class, "songId=?", song.getSongId());
                        }
                        final HistorySong history = new HistorySong();
                        history.setSongId(song.getSongId());
                        history.setQqId(song.getQqId());
                        history.setName(song.getSongName());
                        history.setSinger(song.getSinger());
                        history.setUrl(song.getUrl());
                        history.setPic(song.getImgUrl());
                        history.setOnline(song.isOnline());
                        history.setDuration(song.getDuration());
                        history.setMediaId(song.getMediaId());
                        history.setDownload(song.isDownload());
                        history.saveAsync().listen(new SaveCallback() {
                            @Override
                            public void onFinish(boolean success) {
                                if (success) {
                                    //告诉主界面最近播放的数目需要改变
                                    EventBus.getDefault().post(new SongListNumEvent(Constant.LIST_TYPE_HISTORY));
                                    if (LitePal.findAll(HistorySong.class).size() > Constant.HISTORY_MAX_SIZE) {
                                        LitePal.delete(HistorySong.class, LitePal.findFirst(HistorySong.class).getId());
                                    }
                                }
                            }
                        });

                    }
                });

    }