Android将list数据通过LitePal保存到本地(集合保存到本地)

有时候我们需要将list集合保存到本地,自己写起来太麻烦,就找到了强大的框架LItePal,git地址  https://github.com/LitePalFramework/LitePal

本文来自:http://blog.csdn.net/elinavampire/article/details/40621751

导入jar包就可以使用了,直接上代码:

package com.sdufe.litepal;

import java.util.ArrayList;
import java.util.List;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;

import com.sdufe.litepal.model.Student;

/**
 * @author 子墨
 *
 * 2014-10-30
 */
public class MainActivity extends Activity {

	private SQLiteDatabase db;
	private List<Student> list;
	private Student student;
	private TextView mInformation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mInformation = (TextView) findViewById(R.id.student_information);
		// 生成student表
		db = Connector.getDatabase();
		
		initDate();
		
		//保存
		DataSupport.saveAll(list);
		
		//查找
		student = DataSupport.find(Student.class, 3);
		mInformation.setText("姓名:" + student.getName() + "学号:"
				+ student.getNumber() + "性别:" + student.getSex());
		
		//更新
		student=new Student();
		student.setName("吸血鬼");
		student.update(4);
		
		//删除
		DataSupport.delete(Student.class, 4);
	}

	/**
	 * 表中数据赋值
	 */
	private void initDate() {

		list.add(new Student(5, "20100854213", "klaus", "男"));
		list.add(new Student(6, "20100854213", "klaus", "男"));
		list.add(new Student(7, "20100854213", "klaus", "男"));
		list.add(new Student(8, "20100854213", "klaus", "男"));
		list.add(new Student(9, "20100854213", "klaus", "男"));
	}

}

都很简单,主要是人家源码太强大,直接抓来用就好,我的list保存主要是通过saveall实现


还有一点要注意的就是在assets文件夹下新建litepal.xml,不要忘记去配置它:

<?xml version="1.0" encoding="utf-8"?>
<litepal>
	<!-- 数据库库名 -->
    <dbname value="students" >
    </dbname>
	<!-- 版本号 -->
    <version value="1" >
    </version>

    <list>
        <mapping class="com.sdufe.litepal.model.Student"></mapping>
    </list>

</litepal>

代码地址:http://download.csdn.net/detail/elinavampire/8101117

你可能感兴趣的:(Android将list数据通过LitePal保存到本地(集合保存到本地))