1. 程式人生 > >Android將list資料通過LitePal儲存到本地(集合儲存到本地)

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