Android平方Lite关闭ps异常关闭问题,怎么解决

安卓LitePal数据库框架初始化问题及其他异常
关于LitePal数据库框架的使用和导入,这里就不写了,给个链接,写的很详细,简单,粗暴:http://blog.csdn.net/mofeel_/article/details/
下面说一下我遇到的初始化异常问题,有时候你按照链接的步骤一步一步做好后,但是就是给你抱异常:Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
这个异常,空指针,找又找不到,写法和导入都是正确的,这是为什么呢??其实在我们自己写的MyApplication中,继承LitePalApplication时,在onCreate方法中初始化的时候,写的是:
LitePal.initialize(this);
就在这里,在寻找的时候表示找不到这个引用,具体什么原因就不知道了,这里不可以改变一下写法,让MyApplication重新继承Application,然后写成这样
LitePal.initialize(getBaseContext());
一般情况下这种问题是可以解决的,当然还有其他问题,就只有自行百度了,这里是我遇到的问题和解决方法,记录下。
还有一个问题,就是你更改了你的数据databesa类后,就会报异常,这个异常就不写出来了,你只要知道你更该了数据库besa类后,有两个解决方案,
1.卸载掉原来的测试APP,然后重新加载;
2.在LitePa.xm文件中,将&version
/& 改成 2,就可以解决,这些事我遇到的问题和解决方法
如有不足的请指出,谢谢
没有更多推荐了,博客分类:
ormlite的资料真少,网上很难找,就干脆自己看些api,以前以为这些api什马的很难,看下来之后觉得也不怎么困难。找了些操作数据库的类的用法,所以做了一个登录注册的小例子。
首先是登录相关的类
package com.
import java.sql.SQLE
import java.util.ArrayL
import java.util.L
import com.cng.dao.UsersD
import com.cng.model.UsersE
import com.cng.utils.DataH
import com.j256.ormlite.android.apptools.OrmLiteBaseA
import com.j256.ormlite.dao.D
import android.R.
import android.app.A
import android.content.I
import android.os.B
import android.view.V
import android.view.View.OnClickL
import android.widget.B
import android.widget.EditT
import android.widget.T
public class OrmliteLoginDemoActivity extends OrmLiteBaseActivity&DataHelper& {
private EditT
private EditT
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
handlerbtn();
public void initView()
username=(EditText)findViewById(R.id.username);
password=(EditText)findViewById(R.id.password);
submit=(Button)findViewById(R.id.submit);
register=(Button)findViewById(R.id.register);
public void handlerbtn()
submit.setOnClickListener(new OnClickListener()
public void onClick(View v)
String usernameString=username.getText().toString();
String passwordString=password.getText().toString();
UsersDao usersDao=new UsersDao();
List&UsersEntity& userlist=new ArrayList&UsersEntity&();
Dao&UsersEntity, Integer& userDao=getHelper().getUserDataDao();
userlist=usersDao.findUser(userDao,usernameString, passwordString);
} catch (SQLException e)
e.printStackTrace();
if(userlist==null||userlist.size()&=0)
alert("用户名或密码错误");
alert("欢迎登录");
Intent intent =new Intent();
intent.setClass(OrmliteLoginDemoActivity.this, welcom.class);
startActivity(intent);
register.setOnClickListener(new OnClickListener()
public void onClick(View v)
Intent intent =new Intent();
intent.setClass(OrmliteLoginDemoActivity.this, register.class);
startActivity(intent);
public void alert(String str)
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
然后是注册的
package com.
import java.sql.SQLE
import java.util.L
import com.cng.dao.UsersD
import com.cng.model.UsersE
import com.cng.utils.DataH
import com.j256.ormlite.android.apptools.OrmLiteBaseA
import com.j256.ormlite.dao.D
import android.app.A
import android.os.B
import android.view.V
import android.view.View.OnClickL
import android.widget.B
import android.widget.EditT
import android.widget.T
public class register extends OrmLiteBaseActivity&DataHelper&
private EditText register_
private EditText register_
private EditText register_
private Button register_
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
initview();
handlerbtn();
public void initview()
register_username=(EditText)findViewById(R.id.register_username);
register_password=(EditText)findViewById(R.id.register_password);
register_repassword=(EditText)findViewById(R.id.register_repassword);
register_btn=(Button)findViewById(R.id.register_btn);
public void handlerbtn()
register_btn.setOnClickListener(new OnClickListener()
public void onClick(View v)
String usernameString=register_username.getText().toString();
String passwordString=register_password.getText().toString();
String repasswordString=register_repassword.getText().toString();
if(usernameString.equals(""))
register_username.setError("请输入用户名");
if(passwordString.equals(""))
register_password.setError("请输入密码");
if(repasswordString.equals(""))
register_repassword.setError("请重复密码");
if(!repasswordString.equals(passwordString))
register_repassword.setError("重复密码与原密码不一致");
UsersDao userDao=new UsersDao();
Dao&UsersEntity, Integer& userentitydao=getHelper().getUserDataDao();
List&UsersEntity& userlist=userDao.findUser(userentitydao, usernameString);
if(userlist==null||userlist.size()&=0)
userDao.addsuer(userentitydao, usernameString, passwordString);
alert("注册成功");
alert("此账户已经被注册");
register_username.setText("");
} catch (SQLException e)
e.printStackTrace();
public void alert(String str)
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
最后欢迎界面
package com.
import android.app.A
import android.os.B
public class welcom extends Activity
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.welcom);
再是数据库映射的实体类
package com.cng.
import java.io.S
import com.j256.ormlite.field.DatabaseF
import android.R.
public class UsersEntity implements Serializable
private static final long serialVersionUID = -2135028L;
@DatabaseField(generatedId=true)
@DatabaseField
@DatabaseField
public UsersEntity(){}
public UsersEntity(int id, String username, String password)
this.username =
this.password =
public int getId()
public String getPassword()
public String getUsername()
public void setId(int id)
public void setPassword(String password)
this.password =
public void setUsername(String username)
this.username =
再是操作数据库的类,我按照mvc的模式把操作数据库的类单独分离开了
package com.cng.
import java.sql.SQLE
import java.util.HashM
import java.util.L
import java.util.M
import com.cng.model.UsersE
import com.j256.ormlite.dao.D
public class UsersDao
public List&UsersEntity& findUser(Dao&UsersEntity, Integer& userdao,String username,String password) throws SQLException
Dao&UsersEntity, Integer& userDao =
Map&String, Object& userMap=new HashMap&String, Object&();
userMap.put("username", username);
userMap.put("password", password);
List&UsersEntity& userlistEntities=userDao.queryForFieldValues(userMap);
return userlistEntities==null?null:userlistE
public List&UsersEntity& findUser(Dao&UsersEntity, Integer& userdao,String username) throws SQLException
Dao&UsersEntity, Integer& userDao =
Map&String, Object& userMap=new HashMap&String, Object&();
userMap.put("username", username);
List&UsersEntity& userlistEntities=userDao.queryForFieldValues(userMap);
return userlistEntities==null?null:userlistE
public void addsuer(Dao&UsersEntity, Integer& userdao,String username,String password) throws SQLException
Dao&UsersEntity, Integer& userDao =
UsersEntity usersEntity=new UsersEntity();
usersEntity.setUsername(username);
usersEntity.setPassword(password);
userDao.create(usersEntity);
最后是数据库管理类
package com.cng.
import java.sql.SQLE
import android.content.C
import android.database.sqlite.SQLiteD
import android.util.L
import com.cng.model.UsersE
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenH
import com.j256.ormlite.dao.D
import com.j256.ormlite.support.ConnectionS
import com.j256.ormlite.table.TableU
public class DataHelper extends OrmLiteSqliteOpenHelper
private static final String DATABASE_NAME = "OrmliteLoginDemo.db";
private static final int DATABASE_VERSION = 1;
private Dao&UsersEntity, Integer& userDao =
public DataHelper(Context context)
super(context, DATABASE_NAME, null, DATABASE_VERSION);
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource)
TableUtils.createTable(connectionSource, UsersEntity.class);
} catch (SQLException e)
Log.e(DataHelper.class.getName(), "创建数据库失败", e);
e.printStackTrace();
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int arg2, int arg3)
TableUtils.dropTable(connectionSource, UsersEntity.class, true);
onCreate(db, connectionSource);
} catch (SQLException e)
Log.e(DataHelper.class.getName(), "更新数据库失败", e);
e.printStackTrace();
public void close()
super.close();
public Dao&UsersEntity, Integer& getUserDataDao() throws SQLException
if (userDao == null)
userDao = getDao(UsersEntity.class);
return userD
布局代码如下
&?xml version="1.0" encoding="utf-8" ?&
- &LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&
- &LinearLayout android:layout_marginTop="80dp" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal"&
&TextView android:layout_marginLeft="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="用户名" /&
&EditText android:id="@+id/username" android:layout_marginLeft="10dp" android:layout_width="200dp" android:layout_height="wrap_content" android:hint="请输入用户名" /&
&/LinearLayout&
- &LinearLayout android:layout_marginTop="10dp" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal"&
&TextView android:layout_marginLeft="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密码 " /&
&EditText android:id="@+id/password" android:layout_marginLeft="10dp" android:layout_width="200dp" android:layout_height="wrap_content" android:hint="请输入密码" /&
&/LinearLayout&
- &LinearLayout android:layout_marginTop="10dp" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal"&
&Button android:id="@+id/submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="登录" /&
&Button android:id="@+id/register" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="注册" /&
&/LinearLayout&
&/LinearLayout&
&?xml version="1.0" encoding="utf-8" ?&
- &LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&
- &LinearLayout android:layout_marginTop="80dp" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal"&
&TextView android:layout_marginLeft="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="用户名 " /&
&EditText android:id="@+id/register_username" android:layout_marginLeft="10dp" android:layout_width="200dp" android:layout_height="wrap_content" android:hint="请输入用户名" /&
&/LinearLayout&
- &LinearLayout android:layout_marginTop="10dp" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal"&
&TextView android:layout_marginLeft="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密码  " /&
&EditText android:id="@+id/register_password" android:layout_marginLeft="10dp" android:layout_width="200dp" android:layout_height="wrap_content" android:hint="请输入密码" /&
&/LinearLayout&
- &LinearLayout android:layout_marginTop="10dp" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal"&
&TextView android:layout_marginLeft="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="重复密码" /&
&EditText android:id="@+id/register_repassword" android:layout_marginLeft="10dp" android:layout_width="200dp" android:layout_height="wrap_content" android:hint="重复密码" /&
&/LinearLayout&
- &LinearLayout android:layout_marginTop="10dp" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal"&
&Button android:id="@+id/register_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="注册" /&
&/LinearLayout&
&/LinearLayout&
&?xml version="1.0" encoding="utf-8" ?&
- &LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&
&TextView android:layout_marginLeft="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="欢迎登录" /&
&/LinearLayout&
当然工程里要加入ormlite的基础类包。
这样基于ormlite的登录注册的小例子就完成了。
BTW 我很无聊……盯着看了很久……ORMLite 封装的这个DAO其实已经蛮完备的了,你再加个Dao是会更细致一些。单独分离开的这个UserDao可以换个包换个名改成是service的层,其他的业务逻辑也可以封装进来。而且如果你再分离个数据库操作的层出来,应该输入输出的是object吧,最好不要是一个个参数一个个item的传入传出。= =请问你觉得那些一大堆的findByxxxx()方法应该描述在分离的Dao中还是Service中?额,在学ssh的时候,数据层操作都写在dao层的,也许是思维惯性吧。
浏览: 88083 次
来自: 温州
www.glmei.cn
www.glmei.cn
ducp123 写道 写道bailin_ys ...
。。。我还以为是demo。。。
请问下楼主怎么改变弹出窗口的整体背景色
不是item背景
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'下次自动登录
现在的位置:
& 综合 & 正文
android ORM框架LitePal完全解析(crud)
litepal为何物? 看github上的说明:
LitePal is an Open Source Android library that allows developers to use SQLite database
extremely easy. You can finish most of the database operations without writing even a SQL statement, including create or upgrade tables, crud operations, aggregate functions, etc. The setup of LitePal is quite simple as well, you can integrate it into your
project in less than 5 minutes.
关于litepal本来是不想看的, android本身对SQLite的封装已经很好了,感觉没必要在引入另外一个包来完成数据库操作。
可是,今天看了郭神的博客后,狠狠的鄙视了自己一把! 真是太容易满足了。。也庆幸自己今天看了看。这玩意有什么好的? 这么说吧, 看了litepal后我觉得我以后肯定很少用android原生的了。
首先献上litepal的下载地址(哈,我自己fork的):
下面分段开始我们的litepal之旅吧。
数据库操作,上来肯定是要建表啊。虽然android原生的SQLiteOpenHelper很强大, 但还是得自己去写sql语句, 看看litepal是怎么搞定的:
找到你下载的litepal的downloads目录,将litepal-1.1.1-src.jar复制到你工程的libs目录, 这还没完,还需要小小的配置一下: 打开manifest文件给application节点配置“android:name="org.litepal.LitePalApplication"”。
既然是ORM框架,那肯定需要我们写几个实体类,实体类的类名对应数据库的表的名称,字段对应了数据库中的字段:
public class Person extends DataSupport {
private List&Phone& phones = new ArrayList&Phone&();
public int getId() {
public void setId(int id) {
public String getName() {
public void setName(String name) {
this.name =
public String getGender() {
public void setGender(String gender) {
this.gender =
public List&Phone& getPhones() {
public void setPhones(List&Phone& phones) {
this.phones =
public class Phone extends DataSupport {
private String phoneN
public int getId() {
public void setId(int id) {
public String getPhoneNumber() {
return phoneN
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneN
public Person getPerson() {
public void setPerson(Person person) {
this.person =
两个实体类, 说明一下:
(1) Person中有个List&Phone&和Phone中有个Person表示Person和Phone是1:n的关系, 用litepal就是这么简单的,很轻松的就搞定了表之间的关系,废话一句:我可以说我之前很少用关联表嘛。。。
(2) 实体类继承了DataSupport, 这个类是LitePal中的一个类, 后面它会给我们带来惊喜。
很轻松的搞定了两个实体类,而且注明了之间的关系,接下来还需要一个xml文件来声明它们,要让litepal知道这两个类是要映射到数据中的。
在assert目录创建litepal.xml文件:
&?xml version="1.0" encoding="utf-8"?&
&dbname value="easydb" /&
&version value="1" /&
&mapping class="org.loader.litepaltest1.Phone" /&
&mapping class="org.loader.litepaltest1.Person" /&
&/litepal&
简单的说明一下:dbname是指定数据库名称,这里不需要加.db哦。 version不用想也知道是指定数据库的版本了(那是不是以后修改数据库版本只要该这个值就可以了? 嘿嘿, 必须就是这么简单),还有个list,list节点下有两个mapping仔细观察原来是声明的我们刚开始建立的那两个实体类。
好了,建表这一步就完成了, 只要你的代码有数据库操作, 建表就会自动完成。
2、插入数据
表建立完了, 下一步当然是插入数据了, 马上就会就是litepal对我们的第一次震撼。
Person p = new Person();
p.setName("person1");
p.setGender("male");
Phone phone1 = new Phone();
phone1.setPerson(p);
phone1.setPhoneNumber("123456");
phone1.save();
Phone phone2 = new Phone();
phone2.setPerson(p);
phone2.setPhoneNumber("456789");
phone2.save();
在不知不觉中你已经向Person表中插入了一条数据, 向phone表中插入了2条数据,phone表中的2条数据和person表中那条数据是用对应关系的。我现在要加个表情!!!(可是不知道怎么加。。)如此简单的操作,就是实现了insert操作,让我怎么能不爱上它呢? 但还是要注意一下set完数据别忘了save()一把,save()方法哪来的? 别忘了我们的实体类继承自DataSupport。
插入如此简单, 那更新也肯定很简单。
3.1 使用ContentValues更新特定id的数据:
ContentValues values = new ContentValues();
values.put("name", "newname");
DataSupport.update(Person.class, values, 1);
这段代码将id为1的person的name修改为newname,注意update方法是DataSupport中的一个静态方法。
3.2 使用ContentValues更新特定条件的数据:
ContentValues values = new ContentValues();
values.put("phoneNumber", "11111");
DataSupport.updateAll(Phone.class, values, "id&?", "1");
将id&1的phone的phonenumber修改为11111。
要修改全部数据:
DataSupport.updateAll(Phone.class, values);
不多说了, 一目了然。
如果不习惯使用ContentValues呢? 好办litepal还提供了更加方便的更新操作
3.3 优雅的更新特定id的数据
Phone updatePhone = new Phone();
updatePhone.setPhoneNumber("147852");
updatePhone.update(1);
这里调用对象上的update方法将id为1的phone的phonenumber更新为147852,这种方式是不是有一次震撼到你了? 我是在课堂上看到litepal, 反正当时我是笑出声来了。
3.4 优雅的更新特定条件的数据
Phone updatePhone = new Phone();
updatePhone.setPhoneNumber("256333");
updatePhone.updateAll("id&?", "2");
不多说了, 更新id&2的所有数据。注意一点是这里调用了updateAll方法
3.5 优雅的更新所有数据
Phone updatePhone = new Phone();
updatePhone.setPhoneNumber("111111");
updatePhone.updateAll();
额, 不想多说了, 肯定很清晰。
现在你肯定也想到了删除操作是如何简单了吧, 不过我们还是贴一下吧。
int deleteCount = DataSupport.delete(Person.class, 1);
System.out.println(deleteCount);
删除id为1的person, 这里要多说几句了, 不就删除id是1的person么? 肯定就是1条啊, 获取count是多余的吧? 嘿嘿, 再次证明一下litepal的强大吧, 删除一条数据, litepal会把与该数据关联的其他表中的数据一并删除了,比如现在删除了id为1的Person, 那Phone表中属于Person的数据将全部被删除!! 毕竟那些成为垃圾数据了。
DataSupport.deleteAll(Person.class, "id&?", "1");
DataSupport.deleteAll(Person.class);
这是按条件删除,没什么好说的。
sql语句中最复杂的就是查询了,尤其是多表联合查询(我可以说我现在都不会吗?),但是litepal做其他确是如此简单!!
5.1 震撼的级联操作
List&Phone& phones = DataSupport.where("id&?", "1").order("id").limit(3).find(Phone.class);
for(Phone p : phones) {
System.out.println(p.getPhoneNumber());
!!!!! 这不就在thinkphp中的级联吗!!!我曾经因为做了一个java的这种级联操作类而感到自豪。
5.2 震撼的查询特定id的数据
Phone p = DataSupport.find(Phone.class, 3);
//DataSupport.find(Phone.class, 3, true);
// 关联的表也会查询出来
System.out.println(p.getPhoneNumber());
注意注释了的那句话,第三个参数如果设为true,则关联的表的数据也会被查询出来,强大不!! 那如何获取关联表的数据呢? 很简单p.getPerson().getName()
5.3 震撼的枚举查询(枚举查询是我给它起的名,可能不太确切,说白了就是sql语句的in)
List&Phone& phones = DataSupport.findAll(Phone.class, 3, 4);
//DataSupport.findAll(Phone.class,, true,
3, 4); // 关联的表也会查询出来
for(Phone p : phones) {
System.out.println(p.getPhoneNumber());
同样注意注释了的那句话, 功能和前面的是一样的, 所有查询操作都会有这么一个重载的方法。
5.4 震撼的查询第一条数据
Phone phone = DataSupport.findFirst(Phone.class);
//DataSupport.findFirst(Phone.class, true);
// 关联的表也会查询出来
System.out.println(phone.getPhoneNumber());
查询第一条数据,妈妈再也不用担心我写错order by limit了。
Phone phone = DataSupport.findLast(Phone.class, true);
//Phone p = DataSupport.findFirst(Phone.class, true);
System.out.println(phone.getPhoneNumber());
查询最后一条数据, 不说了, 和上面一样。
5.5 除此之外litepal还给我们提供了一个可以“自由发挥”的方法,也就是自己书写sql语句
Cursor cursor = DataSupport.findBySQL("select * from phone where id=?","3");
for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
System.out.println(cursor.getString(cursor.getColumnIndex("phonenumber")));
cursor.close();
好了,至此litepal的所有基本操作都说的差不多了, 应该很容易上手吧! 还得感谢郭神的博客,要么还真很难了解这么优秀的一款ORM框架。
【上篇】【下篇】

我要回帖

更多关于 window异常关闭 的文章

 

随机推荐