Android 향상 의 SQLite 페이지 읽 기 실현 방법

9120 단어 AndroidSQLite
일반적으로 안 드 로 이 드 자체 에는 내장 형 시스템 에 자주 사용 되 는 SQLite 가 포함 되 어 있어 개발 자 스스로 이식 하고 설치 하 는 시간 을 면 할 수 있 습 니 다.SQLite 는 대부분의 SQLite 표준 을 지원 하고 자주 사용 하 는 SQL 명령 을 SQLite 에서 사용 할 수 있 습 니 다.그 밖 에 안 드 로 이 드 는 SQLite 데이터베이스 에 대한 조작 을 간소화 하 는 일련의 사용자 정의 방법 을 제공 합 니 다.그러나 크로스 플랫폼 에 필요 한 프로그램 은 표준 SQL 문 구 를 사용 하 는 것 을 권장 합 니 다.여러 플랫폼 에서 이식 하기 쉽 기 때 문 입 니 다.
먼저 본 프로그램 이 실 행 된 결과 도 를 붙 입 니 다.

본 사례 프로그램 은 주로 SQLite 의 기본 적 인 용법 을 설명 했다.예 를 들 어 데이터 베 이 스 를 만 들 고 SQL 명령 으로 데이터 시트 를 조회 하 며 데 이 터 를 삽입 하고 데이터 베 이 스 를 닫 으 며 GridView 를 사용 하여 페이지 표시 줄(GridView 에 관 한 용법)을 실현 하여 데 이 터 를 페이지 별로 표시 하 는 데 사용 했다.
페이지 표시 줄 의 pagebots.xml 소스 코드 는 다음 과 같 습 니 다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="wrap_content" android:paddingBottom="4dip"
 android:layout_width="fill_parent">
 <TextView android:layout_width="wrap_content"
 android:layout_below="@+id/ItemImage" android:layout_height="wrap_content"
 android:text="TextView01" android:layout_centerHorizontal="true"
 android:id="@+id/ItemText">
 </TextView>
</RelativeLayout> 

main.xml 의 원본 코드 는 다음 과 같 습 니 다.

<?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">
 <Button android:layout_height="wrap_content"
 android:layout_width="fill_parent" android:id="@+id/btnCreateDB"
 android:text="     "></Button>
 <Button android:layout_height="wrap_content"
 android:layout_width="fill_parent" android:text="        " android:id="@+id/btnInsertRec"></Button>
 <Button android:layout_height="wrap_content" android:id="@+id/btnClose"
 android:text="     " android:layout_width="fill_parent"></Button>
 <EditText android:text="@+id/EditText01" android:id="@+id/EditText01"
 android:layout_width="fill_parent" android:layout_height="256dip"></EditText>
 <GridView android:id="@+id/gridview" android:layout_width="fill_parent"
 android:layout_height="32dip" android:numColumns="auto_fit"
 android:columnWidth="40dip"></GridView>
</LinearLayout>

Java 프로그램 원본 코드 는 다음 과 같 습 니 다.

package com.testSQLite; 
import java.util.ArrayList; 
import java.util.HashMap; 
import android.app.Activity; 
import android.database.Cursor; 
import android.database.SQLException; 
import android.database.sqlite.SQLiteDatabase; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.GridView; 
import android.widget.SimpleAdapter; 
public class testSQLite extends Activity { 
  /** Called when the activity is first created. */ 
  Button btnCreateDB, btnInsert, btnClose; 
  EditText edtSQL;//       
  SQLiteDatabase db; 
  int id;//      id    ,     
  static final int PageSize=10;//   ,        
  private static final String TABLE_NAME = "stu"; 
  private static final String ID = "id"; 
  private static final String NAME = "name"; 
  SimpleAdapter saPageID;//        
  ArrayList<HashMap<String, String>> lstPageID;//        , PageSize        
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    btnCreateDB = (Button) this.findViewById(R.id.btnCreateDB); 
    btnCreateDB.setOnClickListener(new ClickEvent()); 
    btnInsert = (Button) this.findViewById(R.id.btnInsertRec); 
    btnInsert.setOnClickListener(new ClickEvent()); 
    btnClose = (Button) this.findViewById(R.id.btnClose); 
    btnClose.setOnClickListener(new ClickEvent()); 
    edtSQL=(EditText)this.findViewById(R.id.EditText01); 
    GridView gridview = (GridView) findViewById(R.id.gridview);//      
    //       ,       
    lstPageID = new ArrayList<HashMap<String, String>>(); 
    //       ImageItem <====>        ,       
    saPageID = new SimpleAdapter(testSQLite.this, //       
        lstPageID,//      
        R.layout.pagebuttons,//XML   
        new String[] { "ItemText" }, 
        new int[] { R.id.ItemText }); 
 
    //        
    gridview.setAdapter(saPageID); 
    //        
    gridview.setOnItemClickListener(new OnItemClickListener(){ 
      @Override 
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
          long arg3) { 
        LoadPage(arg2);//              
      } 
    }); 
  } 
  class ClickEvent implements View.OnClickListener { 
    @Override 
    public void onClick(View v) { 
      if (v == btnCreateDB) { 
        CreateDB(); 
      } else if (v == btnInsert) { 
        InsertRecord(16);//  16    
        RefreshPage(); 
      }else if (v == btnClose) { 
        db.close(); 
      } 
    } 
  } 
  /* 
   *     ID      
   * SQL:Select * From TABLE_NAME Limit 9 Offset 10; 
   *    TABLE_NAME     ,  10 , 9  
   */ 
  void LoadPage(int pageID) 
  { 
    String sql= "select * from " + TABLE_NAME +  
    " Limit "+String.valueOf(PageSize)+ " Offset " +String.valueOf(pageID*PageSize); 
    Cursor rec = db.rawQuery(sql, null); 
    setTitle("         :"+String.valueOf(rec.getCount())); 
    //        
    String title = ""; 
    int colCount = rec.getColumnCount(); 
    for (int i = 0; i < colCount; i++) 
      title = title + rec.getColumnName(i) + "   "; 
    //         
    String content=""; 
    int recCount=rec.getCount(); 
    for (int i = 0; i < recCount; i++) {//        
      rec.moveToPosition(i); 
      for(int ii=0;ii<colCount;ii++)//              
      { 
        content=content+rec.getString(ii)+"   "; 
      } 
      content=content+"/r/n"; 
    } 
     
    edtSQL.setText(title+"/r/n"+content);//     
    rec.close(); 
  } 
  /* 
   *              
   */ 
  void CreateDB() { 
    //          
    db = SQLiteDatabase.create(null); 
    Log.e("DB Path", db.getPath()); 
    String amount = String.valueOf(databaseList().length); 
    Log.e("DB amount", amount); 
    //       
    String sql = "CREATE TABLE " + TABLE_NAME + " (" + ID 
        + " text not null, " + NAME + " text not null " + ");"; 
    try { 
      db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); 
      db.execSQL(sql); 
    } catch (SQLException e) {} 
  } 
  /* 
   *   N    
   */ 
  void InsertRecord(int n) { 
    int total = id + n; 
    for (; id < total; id++) { 
      String sql = "insert into " + TABLE_NAME + " (" + ID + ", " + NAME 
          + ") values('" + String.valueOf(id) + "', 'test');"; 
      try { 
        db.execSQL(sql); 
      } catch (SQLException e) { 
      } 
    } 
  } 
  /* 
   *          
   */ 
  void RefreshPage() 
  { 
    String sql = "select count(*) from " + TABLE_NAME; 
    Cursor rec = db.rawQuery(sql, null); 
    rec.moveToLast(); 
    long recSize=rec.getLong(0);//     
    rec.close(); 
    int pageNum=(int)(recSize/PageSize) + 1;//      
     
    lstPageID.clear(); 
    for (int i = 0; i < pageNum; i++) { 
      HashMap<String, String> map = new HashMap<String, String>(); 
      map.put("ItemText", "No." + String.valueOf(i));
      lstPageID.add(map); 
    } 
    saPageID.notifyDataSetChanged(); 
  } 
}

관심 이 있 는 독 자 는 이 인 스 턴 스 코드 를 테스트 하여 여러분 이 안 드 로 이 드 프로젝트 개발 을 하 는 데 참고 역할 을 할 수 있 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기