`
zhengjj_2009
  • 浏览: 149356 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

曾经的笔记——android的学习笔记(共享参数、数据库)

 
阅读更多

一、共享参数

public class PersonService { 
 private Context context;
 public PersonService(Context context){
  this.context = context;
 }
 
 public void save(String username){
  SharedPreferences preferences = context.getSharedPreferences("person", Context.MODE_PRIVATE);
  Editor editor = preferences.edit();//获取编辑器
  editor.putString("username", username);
  editor.commit();//提交
 }
 
 public String query(){
  SharedPreferences preferences = context.getSharedPreferences("person", Context.MODE_PRIVATE);
  return preferences.getString("username", "N/A");
 }

}
==============================================================

SQLite

1) 创建数据库 自动创建数据库

   SQLiteOpenHelper  .getReadableDatabase()或.getWriteableDatabase()

   SQLiteOpenHelper自动创建数据库的原理实现

2) 数据库版本变化

3) 编写代码完成增删改查的操作(两种实现方法)

4) 事务的实现

5) 采用ListView实现数据列表的显示

--------------------------------------------------------------

布局的xml代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"  android:orientation= "vertical"
    android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" >

   <LinearLayout android:orientation= "horizontal"
       android:layout_width="match_parent" android:layout_height="wrap_content" >
  <TextView android:layout_width="120dp"  android:textSize="22sp"
   android:layout_height="50dp" android:text="姓名" /> 
  <TextView android:layout_width="150dp" android:textSize="22sp"
   android:layout_height="50dp" android:text="手机号码" />
 </LinearLayout>
 
    <ListView android:id="@+id/listView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout >

 

item.xml的代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent" android:orientation= "horizontal">
 <TextView android:layout_width="120dp"  android:textSize="22sp"
  android:layout_height="50dp" android:id="@+id/name" /> 
 <TextView android:layout_width="150dp" android:textSize="22sp"
  android:layout_height="50dp" android:id="@+id/phone" />
</LinearLayout>

 

MainActivity.java

public class MainActivity extends Activity {
 private ListView listView = null;
 private PersonService personService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView)this.findViewById(R.id.listView);
        listView.setOnItemClickListener(new ItemClickListener());
        personService = new PersonService(this);
        //show();
        //show2();
        show3();
    }

    private final class ItemClickListener implements OnItemClickListener{
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
   ListView lView = (ListView)parent;
   //自定义适配器
   Person person = (Person) lView.getItemAtPosition(position);
   Toast.makeText(getApplicationContext(), person.getId()+"; "+person.getName()+"; "+person.getPhone(), Toast.LENGTH_LONG).show();
   
   /*Cursor cursor = (Cursor) lView.getItemAtPosition(position);
   int personid = cursor.getInt(cursor.getColumnIndex("_id"));
   Toast.makeText(getApplicationContext(), personid+ "", Toast.LENGTH_LONG).show();*/
  }
    }
   
    private void show() {
  List<Person> list = personService.getScrolledData(0, 20);
  List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
  for(Person person : list){
   HashMap<String, Object> item = new HashMap<String, Object>();
   item.put("name", person.getName());
   item.put("phone", person.getPhone());
   //item.put("amount", person.getAmount());
   item.put("id", person.getId());
   data.add(item);
  }
  SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
    new String[]{"name", "phone", }, new int[]{R.id.name, R.id.phone});
  listView.setAdapter(adapter);  
 }

    private void show2() {
  Cursor cursor = personService.getCursorScrollData(0, 20);
  SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor,
    new String[]{"name", "phone"}, new int[]{R.id.name, R.id.phone});
  listView.setAdapter(adapter);
 }
   
    //自定义适配器
  private void show3() {
   List<Person> persons = personService.getScrolledData(0, 20);
   PersonAdapter adapter = new PersonAdapter(this, persons, R.layout.item);
   listView.setAdapter(adapter);
  }

 -------------------------------------------------------------------------------

DataBaseHelper.java

public class DataBaseHelper extends SQLiteOpenHelper {

 public DataBaseHelper(Context context) {
  //String name 设置数据库名称
  //CursorFactory factory 游标工厂 null则使用系统默认的游标工厂
  //int version 不能为0,最好大于0
  super(context, "peter_person.db", null, 3);
  Log.i("DataBaseHelper", "DataBaseHelper(Context context).....");
 }

 @Override
 public void onCreate(SQLiteDatabase db) {//在数据库第一次创建的时候调用的
  /*适合在此处生成数据库的表结构*/
  Log.i("DataBaseHelper", "onCreate(SQLiteDatabase db) .....");
  db.execSQL("create table person(id integer primary key autoincrement, " +
    "name varchar(20), phone VARCHAR(12) )");  
 }

 @Override
 public void onUpgrade(SQLiteDatabase db,
   int oldVersion, int newVersion) {//数据库版本升级的时候会执行
  db.execSQL("ALTER TABLE person ADD amount integer");

 }

}

------------------------------------

PersonService.java

public class PersonService {
 private DataBaseHelper dbHelper = null;
 public PersonService(Context context){
  dbHelper = new DataBaseHelper(context);
 }
 
 public void save(Person person){
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  db.execSQL("insert into person(name, phone) values(?,?)",
    new Object[]{person.getName(), person.getPhone()});
  db.close();
 }
 
 public void delete(Integer id){
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  db.execSQL("delete from person where id=?", new Object[]{id});
 }
 
 public void update(Person person){
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  db.execSQL("update person set name=?,phone=? where id=?",
    new Object[]{person.getName(), person.getPhone(),  person.getId()});
 }
 
 public Person find(Integer id){
  SQLiteDatabase db = dbHelper.getReadableDatabase();
  Cursor cursor = db.rawQuery("select * from person where id=?", new String[]{id.toString()});
  if(cursor.moveToFirst()){
   id = cursor.getInt(cursor.getColumnIndex("id"));
   //int amount = cursor.getInt(cursor.getColumnIndex("amount"));
   String name = cursor.getString(cursor.getColumnIndex("name"));
   String phone = cursor.getString(cursor.getColumnIndex("phone"));
   return new Person(id, name, phone,0);
  }
  cursor.close();
  return null;
 }
 
 public long getCount(){
  SQLiteDatabase db = dbHelper.getReadableDatabase();
  Cursor cursor = db.rawQuery("select count(*) from person", null);
  cursor.moveToFirst();
  long result = cursor.getLong(0);
  cursor.close();
  return result;
 }
 
 public List<Person> getScrolledData(int offset, int maxResult){
  List<Person> persons = new ArrayList<Person>();
  SQLiteDatabase db = dbHelper.getReadableDatabase();
  Cursor cursor = db.rawQuery("select * from person order by id asc limit ?,?",
    new String[]{String.valueOf(offset), String.valueOf(maxResult)});
  while(cursor.moveToNext()){
   int personid = cursor.getInt(cursor.getColumnIndex("id"));
   //int amount = cursor.getInt(cursor.getColumnIndex("amount"));
   String name = cursor.getString(cursor.getColumnIndex("name"));
   String phone = cursor.getString(cursor.getColumnIndex("phone"));
   persons.add(new Person(personid, name, phone, 0));
  }
  cursor.close();
  return persons;
 }
 
 /**
  * 分页获取记录
  * @param offset 跳过前面多少条记录
  * @param maxResult 每页获取多少条记录
  * @return
  */
 public Cursor getCursorScrollData(int offset, int maxResult){
  SQLiteDatabase db = dbHelper.getReadableDatabase();
  Cursor cursor = db.rawQuery("select id as _id,name,phone from person order by id asc limit ?,?",
    new String[]{String.valueOf(offset), String.valueOf(maxResult)});
  return cursor;
 }

}

-------------------------------------------------------

OtherPersonService.java

public class OtherPersonService {
 private DataBaseHelper dbOpenHelper;

 public OtherPersonService(Context context) {
  this.dbOpenHelper = new DataBaseHelper(context);
 }
 /**
  * 添加记录
  * @param person
  */
 public void save(Person person){
  SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
  ContentValues values = new ContentValues();
  values.put("name", person.getName());
  values.put("phone", person.getPhone());
  //values.put("amount", person.getAmount());
  db.insert("person", null, values);
 }
 /**
  * 删除记录
  * @param id 记录ID
  */
 public void delete(Integer id){
  SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
  db.delete("person", "id=?", new String[]{id.toString()});
 }
 /**
  * 更新记录
  * @param person
  */
 public void update(Person person){
  SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
  ContentValues values = new ContentValues();
  values.put("name", person.getName());
  values.put("phone", person.getPhone());
  //values.put("amount", person.getAmount());
  db.update("person", values, "id=?", new String[]{person.getId().toString()});
 }
 /**
  * 查询记录
  * @param id 记录ID
  * @return
  */
 public Person find(Integer id){
  SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
  Cursor cursor = db.query("person", null, "id=?", new String[]{id.toString()}, null, null, null);
  
  if(cursor.moveToFirst()){
   int personid = cursor.getInt(cursor.getColumnIndex("id"));
   //int amount = cursor.getInt(cursor.getColumnIndex("amount"));
   String name = cursor.getString(cursor.getColumnIndex("name"));
   String phone = cursor.getString(cursor.getColumnIndex("phone"));
   return new Person(personid, name, phone, 0);
  }
  cursor.close();
  return null;
 }
 /**
  * 分页获取记录
  * @param offset 跳过前面多少条记录
  * @param maxResult 每页获取多少条记录
  * @return
  */
 public List<Person> getScrollData(int offset, int maxResult){
  List<Person> persons = new ArrayList<Person>();
  SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
  Cursor cursor = db.query("person", null, null, null, null, null,
    "id asc", offset+ ","+ maxResult);
  
  while(cursor.moveToNext()){
   int personid = cursor.getInt(cursor.getColumnIndex("id"));
   //int amount = cursor.getInt(cursor.getColumnIndex("amount"));
   String name = cursor.getString(cursor.getColumnIndex("name"));
   String phone = cursor.getString(cursor.getColumnIndex("phone"));
   persons.add(new Person(personid, name, phone, 0));
  }
  cursor.close();
  return persons;
 }
 /**
  * 获取记录总数
  * @return
  */
 public long getCount(){
  SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
  Cursor cursor = db.query("person", new String[]{"count(*)"}, null, null, null, null, null);
  cursor.moveToFirst();
  long result = cursor.getLong(0);
  cursor.close();
  return result;
 }
}

-----------------------------------------------------

PersonAdapter.java

public class PersonAdapter extends BaseAdapter {
 private List<Person> persons;//在绑定的数据
 private int resource;//绑定的条目界面
 private LayoutInflater inflater;//布局填充器
 
 public PersonAdapter(Context context, List<Person> persons, int resource) {
  this.persons = persons;
  this.resource = resource;
  inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 }

 @Override
 public int getCount() {
  return persons.size();//数据总数
 }

 @Override
 public Object getItem(int position) {
  return persons.get(position);
 }

 @Override
 public long getItemId(int position) {
  return position;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  TextView nameView = null;
  TextView phoneView = null;
  //TextView amountView = null;
  if(convertView==null){
   convertView = inflater.inflate(resource, null);//生成条目界面对象
   nameView = (TextView) convertView.findViewById(R.id.name);
   phoneView = (TextView) convertView.findViewById(R.id.phone);
   //amountView = (TextView) convertView.findViewById(R.id.amount);
   
   ViewCache cache = new ViewCache();
   cache.nameView = nameView;
   cache.phoneView = phoneView;
   //cache.amountView = amountView;   
   convertView.setTag(cache);
  }else{
   ViewCache cache = (ViewCache) convertView.getTag();
   nameView = cache.nameView;
   phoneView = cache.phoneView;
   //amountView = cache.amountView;
  }
  Person person = persons.get(position);
  //下面代码实现数据绑定
  nameView.setText(person.getName());
  phoneView.setText(person.getPhone());
  //amountView.setText(person.getAmount().toString());
  
  return convertView;
 }
 
 private final class ViewCache{
  public TextView nameView;
  public TextView phoneView;
  //public TextView amountView;
 }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics