Android應用之個人應用軟件開發(3)【SQLite數據庫及理財功能實現】 – Android移動開發技術文章_手機開發 Android移動開發教學課程

Android給我們提供Sqlite這種輕量級數據庫,並提供瞭一些數據操作訪問的類庫.如:SQLiteOpenHelper 主要是處理打開、創建、更新等方法的類庫。

  有onCreate() onOpen() onUpgarde(db,int ,int) 等方法,還有幾個重要的和常用的類也要說一下,就是SqliteDataBase,提供操作SQLite的增、查、刪、改等基本方法。還有就是ContentValues ,用來維持當前已打開的數據庫的相關數據,當然也提供瞭增、查、刪、改,隻不過是在當前數據中。那麼先實現創建,和提供的一些自定義的接口,方便我們以後使用,引用方便。

 一些數據字段的都放在這個接口中:

publicinterfacePublicDataCost {
    //定義數據庫名稱
    String DATABASE_NAME = "ZisouBaseDate";
    intDATABASE_VERSION = 1;
   
    //路徑地址
    String DB_PATH =
        "/data/data/Zisou.Soft.mini/databases";
    String PATH = "/databases";
    String DB_NAME = "zisoubasedate.db";
   
    //定義共享優先數據及基礎字段
    String MY_RMBCost ="MY_RMBCost";
    String TodayTime ="TodayTime";

    //Sqlite數據庫基礎字段
    //公有字段
    String ID = "id";
    //TodaySpend表結構
    String Tb_Name_1 = "TodaySpend";                      
    String Field_1_1 = "Morning";    
    String Field_1_2 = "Noon";        
    String Field_1_3 = "Night";     
    String Field_1_4 = "OtherSpend";
    String Field_1_5 = "DailySpend";
    String Field_1_6 = "DateTimes";
}

importandroid.content.Context;
importandroid.database.sqlite.SQLiteDatabase;
importandroid.database.sqlite.SQLiteOpenHelper;
importandroid.view.View.OnClickListener;
publicclassSqliteCommen extendsSQLiteOpenHelper {

    //定義增,改,刪,清除字段
    OnClickListener dbl_add = null;
    OnClickListener dbl_update = null;
    OnClickListener dbl_delete = null;

    publicSqliteCommen(Context context) {
        super(context, PublicDataCost.DATABASE_NAME, null, PublicDataCost.DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }
   
    @Override
    publicvoidonCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String sql = "CREATE TABLE " + PublicDataCost.Tb_Name_1 + " ("
        + PublicDataCost.ID  + " INTEGER primary key autoincrement, "
        + PublicDataCost.Field_1_1 + " text not null, "
        + PublicDataCost.Field_1_2 + " text not null, "
        + PublicDataCost.Field_1_3 + " text not null, "
        + PublicDataCost.Field_1_4 + " text not null, "
        + PublicDataCost.Field_1_5 + " text not null, "
        + PublicDataCost.Field_1_6 + " text not null "
        + ");";
        db.execSQL(sql);
    }
    @Override
    publicvoidonUpgrade(SQLiteDatabase db, intoldVersion, intnewVersion) {
        // TODO Auto-generated method stub
       
    }
}

寫好簡單的基本的數據庫的基本方法,在的程序中也要使用到一些必不可少的方法,那可以通用寫在Commen類裡面。

    SqliteCommen sqlc;

    privatebooleanaddflag = false;

    privateintspinnerid;
    sqlc =  new SqliteCommen(this);
    SQLiteDatabase db = sqlc.getReadableDatabase();

將dbl_add的監聽事件註冊,在這裡需要考慮什麼時候需要添加,什麼時候需要修改,那就需要兩個條件,一個就是標識,和修改的ID值,當通過Sprinner下拉表傳遞過來的值將其綁定綁定在EeitView控件上,然後標識Button.setText()值為“修改”。addflag = true 來判斷修改和刪除。

        sqlc.dbl_add = newOnClickListener() {

            publicvoidonClick(View v) {
              if(addflag == false)
              {
                 //添加
                 Cursor c = db.query(PublicDataCost.Tb_Name_1, AllFeild, "DateTimes='" + str + "'", null, null, null, null);
                 if(c.getCount()>0)
                 {
                    Toast.makeText( todayspend.this, "今天已經添加賬單,你可以修改今日賬單!", Toast.LENGTH_SHORT).show();
                 }
                 else
                 {
                     ContentValues cv = newContentValues();
                     cv.put( PublicDataCost.Field_1_1 , tv_Morning.getText().toString());
                     cv.put( PublicDataCost.Field_1_2 , tv_noon.getText().toString());
                     cv.put( PublicDataCost.Field_1_3 , tv_Night.getText().toString());
                     cv.put( PublicDataCost.Field_1_4 , tv_OtherSpend.getText().toString());
                     cv.put( PublicDataCost.Field_1_5 , tv_DailySpend.getText().toString());
                     cv.put( PublicDataCost.Field_1_6 , str);
                     SQLiteDatabase db = sqlc.getReadableDatabase();
                     db.insert(PublicDataCost.Tb_Name_1, null, cv);
                     db.close();
                     Toast.makeText( todayspend.this, "添加成功!", Toast.LENGTH_SHORT).show();
                     onCreate(savedInstanceState);
                 }
                 c.close();
              }
              else
              {
                  //修改
                  ContentValues cv = newContentValues();
                  cv.put( PublicDataCost.Field_1_1 , tv_Morning.getText().toString());
                  cv.put( PublicDataCost.Field_1_2 , tv_noon.getText().toString());
                  cv.put( PublicDataCost.Field_1_3 , tv_Night.getText().toString());
                  cv.put( PublicDataCost.Field_1_4 , tv_OtherSpend.getText().toString());
                  cv.put( PublicDataCost.Field_1_5 , tv_DailySpend.getText().toString());
                  String sqlwhere =  PublicDataCost.ID + " = " + spinnerid;
                  SQLiteDatabase db = sqlc.getReadableDatabase();
                  db.update(PublicDataCost.Tb_Name_1, cv, sqlwhere ,null);
                  db.close();
                  onCreate(savedInstanceState);
                  Toast.makeText( todayspend.this, "修改成功!", Toast.LENGTH_SHORT).show();
                 
              }
            }
        };

然後就是Spinner的綁定和註冊瞭,先將數據庫裡面的日期取出來,在SetAdapter中綁定,R.layout.simple_dropdown_item_1line,當然也可以自己定義裡面的東西,比如圖文結合的下拉列表,在綁定的同時也把Spinner中的setSelection默認選擇值給賦值一下。顯示從庫中出來的最後一條數據。最後再註冊事件中將spinnerid = Integer.parseInt(c.getString(0));賦值,以便修改時候用到。

//將事件綁定到按鈕
        bt_addspend.setOnClickListener(sqlc.dbl_add);
        //綁定列表
        Cursor c = db.query( PublicDataCost.Tb_Name_1 , newString[] {PublicDataCost.Field_1_6}, null, null, null, null, null);
        c.moveToFirst();
        CharSequence[] cslist = newCharSequence[c.getCount()];
        for(inti=0;i<cslist.length;i++)
        {
            cslist[i]=c.getString(0);
            c.moveToNext();
        }
        c.close();
        Spinner sp = (Spinner)findViewById(R.id.spinner1);
        sp.setAdapter(newArrayAdapter<CharSequence>(this,android.R.layout.simple_dropdown_item_1line,cslist));
        sp.setSelection(cslist.length-1);
        //註冊事件
        sp.setOnItemSelectedListener(newOnItemSelectedListener() {
            publicvoidonItemSelected(AdapterView<?> parent ,View view, intposition, longid){
                String todaydatetime = ((Spinner)parent).getSelectedItem().toString();
                Cursor c = db.query(PublicDataCost.Tb_Name_1, AllFeild, "DateTimes='" + todaydatetime + "'", null, PublicDataCost.Field_1_6, null, PublicDataCost.Field_1_6);
                c.moveToFirst();
                spinnerid = Integer.parseInt(c.getString(0));
                tv_Morning.setText(c.getString(1));
                tv_noon.setText(c.getString(2));
                tv_Night.setText(c.getString(3));
                tv_OtherSpend.setText(c.getString(4));
                tv_DailySpend.setText(c.getString(5));
                c.close();
            }

            publicvoidonNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
               
            }
        });

然後最後就是將今日和昨日的理財信息給顯示出來,我就貼一下全部的代碼吧:

View Code

importandroid.app.Activity;
importandroid.content.ContentValues;
importandroid.content.SharedPreferences;
importandroid.database.Cursor;
importandroid.database.sqlite.SQLiteDatabase;
importandroid.os.Bundle;
importandroid.text.format.Time;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.AdapterView;
importandroid.widget.ArrayAdapter;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.Spinner;
importandroid.widget.TextView;
importandroid.widget.Toast;
importandroid.widget.AdapterView.OnItemSelectedListener;

publicclasstodayspend extendsActivity {
   
   
    SqliteCommen sqlc;//SQLiteOpenHelper
    privatebooleanaddflag = false; //標識
    privateintspinnerid;
   
    publicvoidonCreate(finalBundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.todayspend);
        sqlc =  newSqliteCommen(this);
        finalTextView vt_qdt = (TextView)findViewById(R.id.tv_qdt);
        finalSQLiteDatabase db = sqlc.getReadableDatabase();
        finalEditText tv_Morning = (EditText)findViewById(R.id.tv_Morning);
        finalEditText tv_noon = (EditText)findViewById(R.id.tv_noon);
        finalEditText tv_Night = (EditText)findViewById(R.id.tv_Night);
        finalEditText tv_OtherSpend = (EditText)findViewById(R.id.tv_OtherSpend);
        finalEditText tv_DailySpend = (EditText)findViewById(R.id.tv_DailySpend);
        finalButton bt_addspend = (Button)findViewById(R.id.bt_addspend);
        finalButton bt_qiandao2 = (Button)findViewById(R.id.bt_qd2);
        finalSharedPreferences my_rmb_data = getSharedPreferences(PublicDataCost.MY_RMBCost, 0);
        finalString nowtime = my_rmb_data.getString(PublicDataCost.TodayTime, "").toString();
        TextView jrzkx_0 = (TextView)findViewById(R.id.jrzkx_0);
        TextView jrzkx_01 = (TextView)findViewById(R.id.jrzkx_01);
        TextView jrzkx_02 = (TextView)findViewById(R.id.jrzkx_02);
        TextView jrzkx_03 = (TextView)findViewById(R.id.jrzkx_03);
        TextView Zrzkx_0 = (TextView)findViewById(R.id.zrzkx_0);
        TextView Zrzkx_01 = (TextView)findViewById(R.id.zrzkx_01);
        TextView Zrzkx_02 = (TextView)findViewById(R.id.zrzkx_02);
        TextView Zrzkx_03 = (TextView)findViewById(R.id.zrzkx_03);
       
        Time t = newTime();
        t.setToNow();
        intyesterday = t.monthDay – 1 ;
        intlastmonth = t.month + 1 ;
        String laststrday = "";
        laststrday= t.year + "年" +  lastmonth + "月" + yesterday +"日";
        finalString str =  t.year + "年" + lastmonth + "月" + t.monthDay + "日"; 
          
           if(nowtime.equals(str)==true)
        {
               vt_qdt.setText("日期:"+ nowtime +"已簽到!");
               bt_qiandao2.setBackgroundResource(R.drawable.yqd);
        }
        else
        {
            vt_qdt.setText("日期:"+ str);
            bt_qiandao2.setBackgroundResource(R.drawable.qd);
        }
       
        //簽到功能
        bt_qiandao2.setOnClickListener(newOnClickListener() {
            publicvoidonClick(View v) {
                // TODO Auto-generated method stub
                SharedPreferences my_rmb_data = getSharedPreferences(PublicDataCost.MY_RMBCost, 0);
                if(my_rmb_data.getString(PublicDataCost.TodayTime, "").toString().equals(str)==true)
                 {
                    Toast.makeText( todayspend.this, "今日已簽到!", Toast.LENGTH_SHORT).show();
                 }
                 else
                 {
                       my_rmb_data.edit()
                       .putString(PublicDataCost.TodayTime, str)
                       .commit();
                       vt_qdt.setText("日期:"+ str +"已簽到!");
                       bt_qiandao2.setBackgroundResource(R.drawable.yqd);
                       Toast.makeText( todayspend.this, "簽到成功!", Toast.LENGTH_SHORT).show();
                       onCreate(savedInstanceState);
                 }
            }
        });
       
        finalString[] AllFeild =
        {  
            PublicDataCost.ID,
            PublicDataCost.Field_1_1,
            PublicDataCost.Field_1_2,
            PublicDataCost.Field_1_3,
            PublicDataCost.Field_1_4,
            PublicDataCost.Field_1_5,
            PublicDataCost.Field_1_6
        };
       
        //實例化增 事件
        sqlc.dbl_add = newOnClickListener() {
            publicvoidonClick(View v) {
              if(addflag == false)
              {
                 //添加
                 Cursor c = db.query(PublicDataCost.Tb_Name_1, AllFeild, "DateTimes='" + str + "'", null, null, null, null);
                 if(c.getCount()>0)
                 {
                    Toast.makeText( todayspend.this, "今天已經添加賬單,你可以修改今日賬單!", Toast.LENGTH_SHORT).show();
                 }
                 else
                 {
                     ContentValues cv = newContentValues();
                     cv.put( PublicDataCost.Field_1_1 , tv_Morning.getText().toString());
                     cv.put( PublicDataCost.Field_1_2 , tv_noon.getText().toString());
                     cv.put( PublicDataCost.Field_1_3 , tv_Night.getText().toString());
                     cv.put( PublicDataCost.Field_1_4 , tv_OtherSpend.getText().toString());
                     cv.put( PublicDataCost.Field_1_5 , tv_DailySpend.getText().toString());
                     cv.put( PublicDataCost.Field_1_6 , str);
                     SQLiteDatabase db = sqlc.getReadableDatabase();
                     db.insert(PublicDataCost.Tb_Name_1, null, cv);
                     db.close();
                     Toast.makeText( todayspend.this, "添加成功!", Toast.LENGTH_SHORT).show();
                     onCreate(savedInstanceState);
                 }
                 c.close();
              }
              else
              {
                  //修改
                  ContentValues cv = newContentValues();
                  cv.put( PublicDataCost.Field_1_1 , tv_Morning.getText().toString());
                  cv.put( PublicDataCost.Field_1_2 , tv_noon.getText().toString());
                  cv.put( PublicDataCost.Field_1_3 , tv_Night.getText().toString());
                  cv.put( PublicDataCost.Field_1_4 , tv_OtherSpend.getText().toString());
                  cv.put( PublicDataCost.Field_1_5 , tv_DailySpend.getText().toString());
                  String sqlwhere =  PublicDataCost.ID + " = " + spinnerid;
                  SQLiteDatabase db = sqlc.getReadableDatabase();
                  db.update(PublicDataCost.Tb_Name_1, cv, sqlwhere ,null);
                  db.close();
                  onCreate(savedInstanceState);
                  Toast.makeText( todayspend.this, "修改成功!", Toast.LENGTH_SHORT).show();
                 
              }
            }
        };
        //將事件綁定到按鈕
        bt_addspend.setOnClickListener(sqlc.dbl_add);
        //綁定列表
        Cursor c = db.query( PublicDataCost.Tb_Name_1 , newString[] {PublicDataCost.Field_1_6}, null, null, null, null, null);
        c.moveToFirst();
        CharSequence[] cslist = newCharSequence[c.getCount()];
        for(inti=0;i<cslist.length;i++)
        {
            cslist[i]=c.getString(0);
            c.moveToNext();
        }
        c.close();
        Spinner sp = (Spinner)findViewById(R.id.spinner1);
        sp.setAdapter(newArrayAdapter<CharSequence>(this,android.R.layout.simple_dropdown_item_1line,cslist));
        sp.setSelection(cslist.length-1);
        //註冊事件
        sp.setOnItemSelectedListener(newOnItemSelectedListener() {
            publicvoidonItemSelected(AdapterView<?> parent ,View view, intposition, longid){
                String todaydatetime = ((Spinner)parent).getSelectedItem().toString();
                Cursor c = db.query(PublicDataCost.Tb_Name_1, AllFeild, "DateTimes='" + todaydatetime + "'", null, PublicDataCost.Field_1_6, null, PublicDataCost.Field_1_6);
                c.moveToFirst();
                spinnerid = Integer.parseInt(c.getString(0));
                tv_Morning.setText(c.getString(1));
                tv_noon.setText(c.getString(2));
                tv_Night.setText(c.getString(3));
                tv_OtherSpend.setText(c.getString(4));
                tv_DailySpend.setText(c.getString(5));
                c.close();
            }

            publicvoidonNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
               
            }
        });
       
        //理財信息顯示及處理
        Cursor c2 = db.query( PublicDataCost.Tb_Name_1, AllFeild , "DateTimes='" + str + "'" , null, null, null, null);
        c2.moveToFirst();
        if(c2.getCount()>0)
        {
            intlastspend = Integer.parseInt(c2.getString(1))+Integer.parseInt(c2.getString(2))+Integer.parseInt(c2.getString(3))+Integer.parseInt(c2.getString(4))+Integer.parseInt(c2.getString(5));
            jrzkx_01.setText("早:" + c2.getString(1) + " 中:"+ c2.getString(2)+" 晚:"+c2.getString(3));
            jrzkx_02.setText("購置:"+ c2.getString(4)+"  日常:"+c2.getString(5));
            jrzkx_03.setText("今日總消費金額:"+ lastspend);
            bt_addspend.setText("修   改");
            addflag = true;
        }
        else{
            jrzkx_0.setText("今日未記賬");
            jrzkx_01.setText("");
            jrzkx_02.setText("");
            jrzkx_03.setText("");
        }
        c2.close();

        if(yesterday>0)
        {
            Cursor c3 = db.query( PublicDataCost.Tb_Name_1, AllFeild , "DateTimes='" + laststrday + "'" , null, null, null, null);
            c3.moveToFirst();
            if(c3.getCount()>0)
            {
                intlastspend = Integer.parseInt(c3.getString(1))+Integer.parseInt(c3.getString(2))+Integer.parseInt(c3.getString(3))+Integer.parseInt(c3.getString(4))+Integer.parseInt(c3.getString(5));
                Zrzkx_01.setText("早:" + c3.getString(1) + " 中:"+ c3.getString(2)+" 晚:"+c3.getString(3));
                Zrzkx_02.setText("購置:"+ c3.getString(4)+"  日常:"+c3.getString(5));
                Zrzkx_03.setText("昨日總消費金額:"+ lastspend);
            }
            else{
                Zrzkx_0.setText("昨日未記賬");
                Zrzkx_01.setText("");
                Zrzkx_02.setText("");
                Zrzkx_03.setText("");
            }
            c3.close();
        }
        else
        {
            Zrzkx_0.setText("昨日未記賬");
            Zrzkx_01.setText("");
            Zrzkx_02.setText("");
            Zrzkx_03.setText("");
        }
       
    }

   
}

代碼寫好瞭最後跑起來看一下效果:

 

 哈哈,然後就可以一目瞭然的看到很清晰的理財數據,操作也方便,也達到瞭我們預期想要的功能(記錄前一天的理財信息,一鍵添加,修改,進行理財查詢和對比)。

 接下來就是做一個彈入彈出式菜單列表,來對這些功能進行詳細的統一管理存放的欄目菜單。

 希望和大傢多多相互學習更多的安卓開發方面的相關知識

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。