android从数据库类中传递变量

时间:2015-04-07 07:00:29

标签: java android sqlite sqliteopenhelper

我正在尝试将从数据库(extends sqliteOpenHelper)内部获取的一些值传递给另一个类。但是我使用游标从该数据库获取数据,该数据为其他活动提供空值。

这是我的数据库: 它里面有默认值,插入

public class DatabaseMaster extends SQLiteOpenHelper {
    SQLiteDatabase db;

    private static final String LOG = "DatabaseHelper";
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "Rates";

    // Table Names

    public static final String KEY_ER_ID = "er_id";
    public static final String KEY_ER_USEDORNEW = "Used_or_New";
    public static final String KEY_ER_TENOR = "ER_tenor";
    public static final String KEY_ER_RATE = "ER_rate";
    // Asuransi rate
    public static final String KEY_AS_ID = "as_id";
    public static final String KEY_AS_REGIONAL = "regional";
    public static final String KEY_AS_TENOR = "AS_tenor";
    public static final String KEY_AS_TLO = "TLO";
    public static final String KEY_AS_COMPREHENSIVE = "Comprehensive";
    public static final String KEY_AS_COMBINE = "Combine";

    public static final String TABLE_EFFECTIVE_RATE = "effective_rate";
    public static final String TABLE_ASURANSI_RATE = "asuransi_rate";

    public DatabaseMaster(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        try {
            db.beginTransaction();

            db.execSQL("CREATE TABLE " + TABLE_EFFECTIVE_RATE + " ("
                    + KEY_ER_ID + " INTEGER PRIMARY KEY, " + KEY_ER_USEDORNEW
                    + " TEXT NOT NULL, " + KEY_ER_TENOR + " INTEGER,"
                    + KEY_ER_RATE + " REAL)");

            db.execSQL("CREATE TABLE " + TABLE_ASURANSI_RATE + " (" + KEY_AS_ID
                    + " INTEGER PRIMARY KEY, " + KEY_AS_REGIONAL + " INTEGER, "
                    + KEY_AS_TENOR + " INTEGER," + KEY_AS_TLO + " REAL,"
                    + KEY_AS_COMPREHENSIVE + " REAL," + KEY_AS_COMBINE
                    + " REAL)");

            // Inserts pre-defined departments
            InsertERs(db);
            insertASs(db);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_EFFECTIVE_RATE);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ASURANSI_RATE);
        // db.execSQL("DROP TRIGGER IF EXISTS er_id_trigger");
        // db.execSQL("DROP TRIGGER IF EXISTS er_id_trigger22");

        // db.execSQL("DROP TRIGGER IF EXISTS as_id_trigger");
        // db.execSQL("DROP TRIGGER IF EXISTS as_id_trigger22");

        onCreate(db);

    }

    void AddERrate(EntryEffectiveRate EER) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues valuesER = new ContentValues();
        valuesER.put(KEY_ER_ID, EER.getERId());
        valuesER.put(KEY_ER_USEDORNEW, EER.getERKondisi());
        valuesER.put(KEY_ER_TENOR, EER.getERTenor());
        valuesER.put(KEY_ER_RATE, EER.getERrate());
        // values.put(KEY_CREATED_AT, getDateTime());

        // insert row
        // long er_id =
        db.insert(TABLE_EFFECTIVE_RATE, null, valuesER);
        // db.close();
        // return er_id;

    }

    int getERCount() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cur = db.rawQuery("Select * from " + TABLE_EFFECTIVE_RATE, null);
        int x = cur.getCount();
        cur.close();
        return x;
    }

    Cursor getAllERates() {
        SQLiteDatabase db = this.getWritableDatabase();

        // Cursor cur=
        // db.rawQuery("Select "+colID+" as _id , "+colName+", "+colAge+" from "+employeeTable,
        // new String [] {});
        // Cursor cur= db.rawQuery("SELECT * FROM "+viewEmps,null);
        Cursor cur = db.rawQuery("Select " + KEY_ER_ID + " as _id, "
                + KEY_ER_USEDORNEW + ", " + KEY_ER_TENOR + ", " + KEY_ER_RATE
                + ", " + " from " + TABLE_EFFECTIVE_RATE, new String[] {});
        cur.close();
        return cur;

    }

    public List<EntryEffectiveRate> getAllEffectiveRates() {
        List<EntryEffectiveRate> EffectiveRates = new ArrayList<EntryEffectiveRate>();
        String selectQuery = "SELECT  * FROM " + TABLE_EFFECTIVE_RATE;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                EntryEffectiveRate ergt = new EntryEffectiveRate();
                ergt.setERId(c.getInt(c.getColumnIndex(KEY_ER_ID)));
                ergt.setERKondisi(c.getString(c
                        .getColumnIndex(KEY_ER_USEDORNEW)));
                ergt.setERTenor(c.getInt(c.getColumnIndex(KEY_ER_TENOR)));
                ergt.setERRate(c.getDouble(c.getColumnIndex(KEY_ER_RATE)));

                // add
                EffectiveRates.add(ergt);
            } while (c.moveToNext());
        }
        // db.close();
        c.close();
        return EffectiveRates;
    }

    public int updateEntryEffectiveRate(EntryEffectiveRate er) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ER_ID, er.getERId());
        values.put(KEY_ER_USEDORNEW, er.getERKondisi());
        values.put(KEY_ER_TENOR, er.getERTenor());
        values.put(KEY_ER_RATE, er.getERrate());
        // values.put(KEY_CREATED_AT, getDateTime());

        // updating row
        return db.update(TABLE_EFFECTIVE_RATE, values, KEY_ER_ID + " = ?",
                new String[] { String.valueOf(er.getERId()) });
    }

    //
    public void deleteEntryEffectiveRate(long er_id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_EFFECTIVE_RATE, KEY_ER_ID + " = ?",
                new String[] { String.valueOf(er_id) });
    }

    void AddASrate(EntryAsuransiRate EAR) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues valuesAS = new ContentValues();
        valuesAS.put(KEY_AS_ID, EAR.getASId());
        valuesAS.put(KEY_AS_REGIONAL, EAR.getASzona());
        valuesAS.put(KEY_AS_TENOR, EAR.getAStenor());
        valuesAS.put(KEY_AS_TLO, EAR.getAStlo());
        valuesAS.put(KEY_AS_COMPREHENSIVE, EAR.getAScomp());
        valuesAS.put(KEY_AS_COMBINE, EAR.getAScomb());
        // values.put(KEY_CREATED_AT, getDateTime());

        // insert row
        // long er_id =
        db.insert(TABLE_ASURANSI_RATE, null, valuesAS);
        // db.close();
        // return er_id;

    }

    Cursor getAllASrates() {
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cur = db.rawQuery("Select " + KEY_AS_ID + " as _id, "
                + KEY_AS_REGIONAL + ", " + KEY_AS_TENOR + ", " + KEY_AS_TLO
                + ", " + KEY_AS_COMPREHENSIVE + ", " + KEY_AS_COMBINE + ", "
                + " from " + TABLE_ASURANSI_RATE, new String[] {});
        cur.close();
        return cur;
    }

    int getASCount() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cur = db.rawQuery("Select * from " + TABLE_ASURANSI_RATE, null);
        int x = cur.getCount();
        cur.close();
        return x;
    }

    public List<EntryAsuransiRate> getAllAsuransiRates() {
        List<EntryAsuransiRate> AsuransiRates = new ArrayList<EntryAsuransiRate>();
        String selectQuery = "SELECT  * FROM " + TABLE_ASURANSI_RATE;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {

                EntryAsuransiRate asgt = new EntryAsuransiRate();
                asgt.setASId(c.getInt(c.getColumnIndex(KEY_AS_ID)));
                asgt.setASzona(c.getInt(c.getColumnIndex(KEY_AS_REGIONAL)));
                asgt.setAStenor(c.getInt(c.getColumnIndex(KEY_AS_TENOR)));
                asgt.setAStlo(c.getDouble(c.getColumnIndex(KEY_AS_TLO)));
                asgt.setAScomp(c.getDouble(c
                        .getColumnIndex(KEY_AS_COMPREHENSIVE)));
                asgt.setAScomb(c.getDouble(c.getColumnIndex(KEY_AS_COMBINE)));
                // add
                AsuransiRates.add(asgt);
            } while (c.moveToNext());
        }
        // db.close();
        c.close();
        return AsuransiRates;
    }

    public int updateEntryAsuransiRate(EntryAsuransiRate EAR) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues valuesAS = new ContentValues();
        valuesAS.put(KEY_AS_ID, EAR.getASId());
        valuesAS.put(KEY_AS_REGIONAL, EAR.getASzona());
        valuesAS.put(KEY_AS_TENOR, EAR.getAStenor());
        valuesAS.put(KEY_AS_TLO, EAR.getAStlo());
        valuesAS.put(KEY_AS_COMPREHENSIVE, EAR.getAScomp());
        valuesAS.put(KEY_AS_COMBINE, EAR.getAScomb());
        // values.put(KEY_CREATED_AT, getDateTime());

        // updating row
        return db.update(TABLE_ASURANSI_RATE, valuesAS, KEY_AS_ID + " = ?",
                new String[] { String.valueOf(EAR.getASId()) });
    }

    //
    public void deleteEntryAsuransiRate(long as_id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_ASURANSI_RATE, KEY_AS_ID + " = ?",
                new String[] { String.valueOf(as_id) });
    }

    void InsertERs(SQLiteDatabase db) {
        try {
            db.beginTransaction();
            ContentValues cv = new ContentValues();

            cv.put(KEY_ER_ID, 1);
            cv.put(KEY_ER_USEDORNEW, "Baru");
            cv.put(KEY_ER_TENOR, 12);
            cv.put(KEY_ER_RATE, 12.1);
            db.insert(TABLE_EFFECTIVE_RATE, KEY_ER_ID, cv);

            cv.put(KEY_ER_ID, 2);
            cv.put(KEY_ER_USEDORNEW, "Baru");
            cv.put(KEY_ER_TENOR, 24);
            cv.put(KEY_ER_RATE, 12.2);
            db.insert(TABLE_EFFECTIVE_RATE, KEY_ER_ID, cv);

            cv.put(KEY_ER_ID, 3);
            cv.put(KEY_ER_USEDORNEW, "Baru");
            cv.put(KEY_ER_TENOR, 36);
            cv.put(KEY_ER_RATE, 12.3);
            db.insert(TABLE_EFFECTIVE_RATE, KEY_ER_ID, cv);

            cv.put(KEY_ER_ID, 4);
            cv.put(KEY_ER_USEDORNEW, "Baru");
            cv.put(KEY_ER_TENOR, 48);
            cv.put(KEY_ER_RATE, 12.4);
            db.insert(TABLE_EFFECTIVE_RATE, KEY_ER_ID, cv);

            cv.put(KEY_ER_ID, 5);
            cv.put(KEY_ER_USEDORNEW, "Baru");
            cv.put(KEY_ER_TENOR, 60);
            cv.put(KEY_ER_RATE, 12.5);
            db.insert(TABLE_EFFECTIVE_RATE, KEY_ER_ID, cv);

            cv.put(KEY_ER_ID, 6);
            cv.put(KEY_ER_USEDORNEW, "Baru");
            cv.put(KEY_ER_TENOR, 12);
            cv.put(KEY_ER_RATE, 12.6);
            db.insert(TABLE_EFFECTIVE_RATE, KEY_ER_ID, cv);

            cv.put(KEY_ER_ID, 7);
            cv.put(KEY_ER_USEDORNEW, "Baru");
            cv.put(KEY_ER_TENOR, 24);
            cv.put(KEY_ER_RATE, 12.7);
            db.insert(TABLE_EFFECTIVE_RATE, KEY_ER_ID, cv);

            cv.put(KEY_ER_ID, 8);
            cv.put(KEY_ER_USEDORNEW, "Baru");
            cv.put(KEY_ER_TENOR, 36);
            cv.put(KEY_ER_RATE, 12.8);
            db.insert(TABLE_EFFECTIVE_RATE, KEY_ER_ID, cv);

            cv.put(KEY_ER_ID, 9);
            cv.put(KEY_ER_USEDORNEW, "Baru");
            cv.put(KEY_ER_TENOR, 48);
            cv.put(KEY_ER_RATE, 12.9);
            db.insert(TABLE_EFFECTIVE_RATE, KEY_ER_ID, cv);

            cv.put(KEY_ER_ID, 10);
            cv.put(KEY_ER_USEDORNEW, "Baru");
            cv.put(KEY_ER_TENOR, 60);
            cv.put(KEY_ER_RATE, 13);
            db.insert(TABLE_EFFECTIVE_RATE, KEY_ER_ID, cv);
            // db.insert(TABLE_EFFECTIVE_RATE, KEY_ER_ID, cv);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        // db.close();

    }

    void insertASs(SQLiteDatabase db) {
        try {
            db.beginTransaction();

            ContentValues cv = new ContentValues();

            cv.put(KEY_AS_ID, 1);
            cv.put(KEY_AS_REGIONAL, 1);
            cv.put(KEY_AS_TENOR, 12);
            cv.put(KEY_AS_TLO, 1.00);
            cv.put(KEY_AS_COMPREHENSIVE, 2.00);
            cv.put(KEY_AS_COMBINE, 3.00);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 2);
            cv.put(KEY_AS_REGIONAL, 1);
            cv.put(KEY_AS_TENOR, 24);
            cv.put(KEY_AS_TLO, 1.01);
            cv.put(KEY_AS_COMPREHENSIVE, 2.01);
            cv.put(KEY_AS_COMBINE, 3.01);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 3);
            cv.put(KEY_AS_REGIONAL, 1);
            cv.put(KEY_AS_TENOR, 36);
            cv.put(KEY_AS_TLO, 1.02);
            cv.put(KEY_AS_COMPREHENSIVE, 2.02);
            cv.put(KEY_AS_COMBINE, 3.02);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 4);
            cv.put(KEY_AS_REGIONAL, 1);
            cv.put(KEY_AS_TENOR, 48);
            cv.put(KEY_AS_TLO, 1.03);
            cv.put(KEY_AS_COMPREHENSIVE, 2.03);
            cv.put(KEY_AS_COMBINE, 3.03);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 5);
            cv.put(KEY_AS_REGIONAL, 1);
            cv.put(KEY_AS_TENOR, 60);
            cv.put(KEY_AS_TLO, 1.04);
            cv.put(KEY_AS_COMPREHENSIVE, 2.04);
            cv.put(KEY_AS_COMBINE, 3.04);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 6);
            cv.put(KEY_AS_REGIONAL, 2);
            cv.put(KEY_AS_TENOR, 12);
            cv.put(KEY_AS_TLO, 1.05);
            cv.put(KEY_AS_COMPREHENSIVE, 2.05);
            cv.put(KEY_AS_COMBINE, 3.05);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 7);
            cv.put(KEY_AS_REGIONAL, 2);
            cv.put(KEY_AS_TENOR, 24);
            cv.put(KEY_AS_TLO, 1.06);
            cv.put(KEY_AS_COMPREHENSIVE, 2.06);
            cv.put(KEY_AS_COMBINE, 3.06);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 8);
            cv.put(KEY_AS_REGIONAL, 2);
            cv.put(KEY_AS_TENOR, 36);
            cv.put(KEY_AS_TLO, 1.07);
            cv.put(KEY_AS_COMPREHENSIVE, 2.07);
            cv.put(KEY_AS_COMBINE, 3.07);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 9);
            cv.put(KEY_AS_REGIONAL, 2);
            cv.put(KEY_AS_TENOR, 48);
            cv.put(KEY_AS_TLO, 1.08);
            cv.put(KEY_AS_COMPREHENSIVE, 2.08);
            cv.put(KEY_AS_COMBINE, 3.08);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 10);
            cv.put(KEY_AS_REGIONAL, 2);
            cv.put(KEY_AS_TENOR, 60);
            cv.put(KEY_AS_TLO, 1.09);
            cv.put(KEY_AS_COMPREHENSIVE, 2.09);
            cv.put(KEY_AS_COMBINE, 3.09);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 11);
            cv.put(KEY_AS_REGIONAL, 3);
            cv.put(KEY_AS_TENOR, 12);
            cv.put(KEY_AS_TLO, 1.10);
            cv.put(KEY_AS_COMPREHENSIVE, 2.10);
            cv.put(KEY_AS_COMBINE, 3.10);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 12);
            cv.put(KEY_AS_REGIONAL, 3);
            cv.put(KEY_AS_TENOR, 24);
            cv.put(KEY_AS_TLO, 1.11);
            cv.put(KEY_AS_COMPREHENSIVE, 2.11);
            cv.put(KEY_AS_COMBINE, 3.11);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);
            cv.put(KEY_AS_ID, 13);
            cv.put(KEY_AS_REGIONAL, 3);
            cv.put(KEY_AS_TENOR, 36);
            cv.put(KEY_AS_TLO, 1.12);
            cv.put(KEY_AS_COMPREHENSIVE, 2.12);
            cv.put(KEY_AS_COMBINE, 3.12);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 14);
            cv.put(KEY_AS_REGIONAL, 3);
            cv.put(KEY_AS_TENOR, 48);
            cv.put(KEY_AS_TLO, 1.13);
            cv.put(KEY_AS_COMPREHENSIVE, 2.13);
            cv.put(KEY_AS_COMBINE, 3.13);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            cv.put(KEY_AS_ID, 15);
            cv.put(KEY_AS_REGIONAL, 3);
            cv.put(KEY_AS_TENOR, 60);
            cv.put(KEY_AS_TLO, 1.14);
            cv.put(KEY_AS_COMPREHENSIVE, 2.14);
            cv.put(KEY_AS_COMBINE, 3.14);
            db.insert(TABLE_ASURANSI_RATE, KEY_AS_ID, cv);

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        // db1.close();
    }

    public Cursor getERValues(int index) {

        String from[] = { "KEY_ER_USEDORNEW", "KEY_ER_TENOR", "KEY_ER_RATE" };
        String where = DatabaseMaster.KEY_ER_ID + "=?";
        String[] whereArgs = new String[] { index + "" };
        Cursor cursor = db.query(DatabaseMaster.TABLE_EFFECTIVE_RATE, from,
                where, whereArgs, null, null, null, null);
        return cursor;
    }

    class DataHandler extends Activity {

         public void getData(int id) {

            Cursor c = getERValues(id);

            if (c != null) {
                while (c.moveToNext()) {
                    String UorN = c.getString(c.getColumnIndex("Used_or_New"));
                    int er_t = c.getInt(c.getColumnIndex("ER_tenor"));
                    double er_r = c.getDouble(c.getColumnIndex("ER_rate"));

                    // use these strings as you want
                    Intent Person = new Intent(this, MediatorMaster.class);
                    Person.putExtra("Used_or_New", UorN);
                    Person.putExtra("ER_tenor", er_t);
                    Person.putExtra("ER_rate", er_r);
                    startActivity(Person);
                }
            }
        }
    }

    // closing database
    public void closeDB() {
        SQLiteDatabase db = this.getReadableDatabase();
        if (db != null && db.isOpen())
            db.close();
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        if (!db.isReadOnly()) {
            // Enable foreign key constraints
            db.execSQL("PRAGMA foreign_keys=ON;");
        }

    }

}

另一个假设显示通过意图发送的数据:

public class MediatorMaster extends Activity {

    @Override
    protected void onCreate(Bundle unpack) {
        // TODO Auto-generated method stub
        super.onCreate(unpack);
        setContentView(R.layout.test);

        unpack = getIntent().getExtras();
        //for(){
        if (unpack != null) {
        String UorN = unpack.getString("Used_or_New");
        //int er_t = unpack.getInt("er_t");
        //double er_r = unpack.getDouble("er_r");


        Message.message(this, "Result :"+ UorN + " " /*+ er_t + " " + er_r*/);
        }
        else {
         Message.message(this, "unread datas");
        }


    // }
    }
}

编辑: 我有另一个类,将显示多少条目,并将显示所有数据。我创建了这个以确保数据是否真的存在。

将显示的课程:

public class MainActivity extends Activity {

    // Database Helper
    DatabaseMaster db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    //  SQLiteDatabase db = this.getReadaleDatabase();
        //db = new DatabaseHelper(getApplicationContext());
        db = new DatabaseMaster(getApplicationContext());


        Log.d("Effectiverate Count", " EffectiverateCount: "
                + db.getASCount());


        Log.d("Asuransirate Count", " AsuransirateCount: "
                + db.getERCount());

        // getting all ER
                Log.d("Get ER", "GEtting All ER");

                List<EntryEffectiveRate> allEffectiveRate = db.getAllEffectiveRates();
                for (EntryEffectiveRate ER : allEffectiveRate) {
                    Log.d("ER_ids", String.valueOf(ER.getERId()));
                    Log.d("ER_rates", ER.getERKondisi());
                    Log.d("ER_tenors", String.valueOf(ER.getERTenor()));
                    Log.d("ER_rates", String.valueOf(ER.getERrate()));
                }

                // getting all AS
                Log.d("Get AS", "GEtting All AS");

                List<EntryAsuransiRate> allAsuransiRate = db.getAllAsuransiRates();
                for (EntryAsuransiRate AS : allAsuransiRate) {
                    Log.d("AS_ids", String.valueOf(AS.getASId()));
                    Log.d("AS_tenors", String.valueOf(AS.getAStenor()));
                    Log.d("AS_tlos", String.valueOf(AS.getAStlo()));
                    Log.d("AS_comps", String.valueOf(AS.getAScomp()));
                    Log.d("AS_combs", String.valueOf(AS.getAScomb()));
                }



        // Don't forget to close database connection
        db.closeDB();
}}

其他将成为构造函数的类,定义输入的参数:

    public class EntryAsuransiRate {

        int as_id;
        int ASzona;
        int AStenor;
        double AStlo;
        double AScomp;
        double AScomb;

        // String created_at;

        // constructors
        public EntryAsuransiRate() {
        }

        public EntryAsuransiRate(int ASzona, int AStenor, double AStlo,
                double AScomp, double AScomb) {
            this.ASzona = ASzona;
            this.AStenor = AStenor;
            this.AStlo = AStlo;
            this.AScomp = AScomp;
            this.AScomb = AScomb;
        }

        public EntryAsuransiRate(int as_id, int ASzona, int AStenor, double AStlo,
                double AScomp, double AScomb) {
            this.as_id = as_id;
            this.ASzona = ASzona;
            this.AStenor = AStenor;
            this.AStlo = AStlo;
            this.AScomp = AScomp;
            this.AScomb = AScomb;
        }

        // setters
        public void setASId(int as_id) {
            this.as_id = as_id;
        }

        public void setASzona(int ASzona) {
            this.ASzona = ASzona;
        }

        public void setAStenor(int AStenor) {
            this.AStenor = AStenor;
        }

        public void setAStlo(double AStlo) {
            this.AStlo = AStlo;
        }

        public void setAScomp(double AScomp) {
            this.AScomp = AScomp;
        }

        public void setAScomb(double AScomb) {
            this.AScomb = AScomb;
        }


        // public void setCreatedAt(String created_at){
        // this.created_at = created_at;
        // }

        // getters
        public long getASId() {
            return this.as_id;
        }

        public int getASzona() {
            return this.ASzona;
        }

        public int getAStenor() {
            return this.AStenor;
        }

        public double getAStlo() {
            return this.AStlo;
        }

        public double getAScomp() {
            return this.AScomp;
        }

        public double getAScomb() {
            return this.AScomb;
        }
    }

and
public class EntryEffectiveRate {

    int er_id;
    String ERkondisi;
    int ERtenor;
    double ERrate;
    //String created_at;

    // constructors
    public EntryEffectiveRate() {
    }

    public EntryEffectiveRate(String ERkondisi, int ERtenor, double ERrate) {
        this.ERkondisi = ERkondisi;
        this.ERtenor = ERtenor;
        this.ERrate = ERrate;
    }

    public EntryEffectiveRate(int er_id, String ERkondisi, int ERtenor, double ERrate) {
        this.er_id = er_id;
        this.ERkondisi = ERkondisi;
        this.ERtenor = ERtenor;
        this.ERrate = ERrate;
    }

    // setters
    public void setERId(int er_id) {
        this.er_id = er_id;
    }

    public void setERKondisi(String ERkondisi) {
        this.ERkondisi = ERkondisi;
    }

    public void setERTenor(int ERtenor) {
        this.ERtenor = ERtenor;
    }

    public void setERRate(double ERrate){
        this.ERrate = ERrate;
    }

    //public void setCreatedAt(String created_at){
    //  this.created_at = created_at;
    //}

    // getters
    public long getERId() {
        return this.er_id;
    }

    public String getERKondisi() {
        return this.ERkondisi;
    }

    public int getERTenor() {
        return this.ERtenor;
    }
    public double getERrate(){
        return this.ERrate;
    }
}

执行/运行mainactivity时的logcat结果

04-07 14:35:11.827: D/Effectiverate Count(395):  EffectiverateCount: 15
04-07 14:35:11.837: D/Asuransirate Count(395):  AsuransirateCount: 10
04-07 14:35:11.837: D/Get ER(395): GEtting All ER
04-07 14:35:11.837: E/DatabaseHelper(395): SELECT  * FROM effective_rate
04-07 14:35:11.847: D/ER_ids(395): 1
04-07 14:35:11.867: D/ER_rates(395): Baru
04-07 14:35:11.867: D/ER_tenors(395): 12
04-07 14:35:11.890: D/ER_rates(395): 12.1
04-07 14:35:11.890: D/ER_ids(395): 2
04-07 14:35:11.890: D/ER_rates(395): Baru
04-07 14:35:11.890: D/ER_tenors(395): 24
04-07 14:35:11.890: D/ER_rates(395): 12.2
04-07 14:35:11.890: D/ER_ids(395): 3
04-07 14:35:11.890: D/ER_rates(395): Baru
04-07 14:35:11.890: D/ER_tenors(395): 36
04-07 14:35:11.890: D/ER_rates(395): 12.3
04-07 14:35:11.897: D/ER_ids(395): 4
04-07 14:35:11.897: D/ER_rates(395): Baru
04-07 14:35:11.897: D/ER_tenors(395): 48
04-07 14:35:11.897: D/ER_rates(395): 12.4
04-07 14:35:11.897: D/ER_ids(395): 5
04-07 14:35:11.897: D/ER_rates(395): Baru
04-07 14:35:11.897: D/ER_tenors(395): 60
04-07 14:35:11.897: D/ER_rates(395): 12.5
04-07 14:35:11.897: D/ER_ids(395): 6
04-07 14:35:11.897: D/ER_rates(395): Baru
04-07 14:35:11.897: D/ER_tenors(395): 12
04-07 14:35:11.897: D/ER_rates(395): 12.6
04-07 14:35:11.897: D/ER_ids(395): 7
04-07 14:35:11.934: D/ER_rates(395): Baru
04-07 14:35:11.934: D/ER_tenors(395): 24
04-07 14:35:11.937: D/ER_rates(395): 12.7
04-07 14:35:11.937: D/ER_ids(395): 8
04-07 14:35:11.937: D/ER_rates(395): Baru
04-07 14:35:11.937: D/ER_tenors(395): 36
04-07 14:35:11.937: D/ER_rates(395): 12.8
04-07 14:35:11.937: D/ER_ids(395): 9
04-07 14:35:11.937: D/ER_rates(395): Baru
04-07 14:35:11.937: D/ER_tenors(395): 48
04-07 14:35:11.937: D/ER_rates(395): 12.9
04-07 14:35:11.937: D/ER_ids(395): 10
04-07 14:35:11.937: D/ER_rates(395): Baru
04-07 14:35:11.937: D/ER_tenors(395): 60
04-07 14:35:11.937: D/ER_rates(395): 13.0
04-07 14:35:11.937: D/Get AS(395): GEtting All AS
04-07 14:35:11.937: E/DatabaseHelper(395): SELECT  * FROM asuransi_rate
04-07 14:35:11.947: D/AS_ids(395): 1
04-07 14:35:11.957: D/AS_tenors(395): 12
04-07 14:35:11.957: D/AS_tlos(395): 1.0
04-07 14:35:11.957: D/AS_comps(395): 2.0
04-07 14:35:11.957: D/AS_combs(395): 3.0
.
.
.
04-07 14:35:12.007: D/AS_ids(395): 15
04-07 14:35:12.007: D/AS_tenors(395): 60
04-07 14:35:12.047: D/AS_tlos(395): 1.14
04-07 14:35:12.047: D/AS_comps(395): 2.14
04-07 14:35:12.047: D/AS_combs(395): 3.14
04-07 14:35:16.258: W/KeyCharacterMap(395): No keyboard for id 0
04-07 14:35:16.258: W/KeyCharacterMap(395): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
04-07 14:35:54.967: D/dalvikvm(395): GC_FOR_MALLOC freed 5071 objects / 280936 bytes in 70ms
04-07 14:35:57.150: W/KeyCharacterMap(395): No keyboard for id 0
04-07 14:35:57.150: W/KeyCharacterMap(395): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
04-07 14:42:28.127: W/IInputConnectionWrapper(395): showStatusIcon on inactive InputConnection
04-07 14:42:33.598: D/dalvikvm(395): GC_EXPLICIT freed 1992 objects / 76432 bytes in 55ms

当它运行时,它会给出消息&#34;未读数据&#34;。意味着在尝试getExtras时它获得了空值。我哪里错了? 我想将所有插入的数据传递给新活动(MediatorMaster,现在用于检查附加组件是否到达那里),然后将计算。怎么做?有什么建议吗?

提前致谢

2 个答案:

答案 0 :(得分:2)

在你返回游标之前,你正在关闭游标。

如果您要返回游标,请在调用函数中完成游标后关闭游标。

Cursor getAllASrates() {
    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cur = db.rawQuery("Select " + KEY_AS_ID + " as _id, "
            + KEY_AS_REGIONAL + ", " + KEY_AS_TENOR + ", " + KEY_AS_TLO
            + ", " + KEY_AS_COMPREHENSIVE + ", " + KEY_AS_COMBINE + ", "
            + " from " + TABLE_ASURANSI_RATE, new String[] {});

    //close the cursor in the calling function after finished with it
    //cur.close();
    return cur;
}

这也是:

Cursor getAllERates() {
    SQLiteDatabase db = this.getWritableDatabase();

    // Cursor cur=
    // db.rawQuery("Select "+colID+" as _id , "+colName+", "+colAge+" from "+employeeTable,
    // new String [] {});
    // Cursor cur= db.rawQuery("SELECT * FROM "+viewEmps,null);
    Cursor cur = db.rawQuery("Select " + KEY_ER_ID + " as _id, "
            + KEY_ER_USEDORNEW + ", " + KEY_ER_TENOR + ", " + KEY_ER_RATE
            + ", " + " from " + TABLE_EFFECTIVE_RATE, new String[] {});
    //close the cursor in the calling function after finished with it
    //cur.close();
    return cur;

}

更新

所以,看起来另一段代码存在问题,所以我对其进行了修改并发布在下面。尝试直接访问列,不要使用while循环,因为看起来这个游标只会返回一个结果。

如果“Cursor count:”日志条目的大小为零,那么您的查询不会返回任何数据。

这也显示了你应该关闭光标的位置。

class DataHandler extends Activity {

         public void getData(int id) {

            Cursor c = getERValues(id);

            Log.d(LOG, "Cursor count: " + c.getCount());

            if (c != null) {
                if (c.moveToFirst()) {
                    String UorN = c.getString(0);
                    int er_t = c.getInt(1);
                    double er_r = c.getDouble(2);

                    // use these strings as you want
                    Intent Person = new Intent(this, MediatorMaster.class);
                    Person.putExtra("Used_or_New", UorN);
                    Person.putExtra("ER_tenor", er_t);
                    Person.putExtra("ER_rate", er_r);
                    startActivity(Person);
                }
                else{
                   Log.e(LOG, "Cursor could not moveToFirst ");

                }


            }
            c.close();  //close the cursor here
        }
    }

答案 1 :(得分:1)

几天后,我找到了解决方案。感谢Daniel Nugent,Dev和Prashant Bhoir帮助我解决这个问题。解决方案是使用Array作为临时列表,它将读取特定表中的所有数据(您也可以读取特定列)。例如:

从表中的列获取值/某个值*: *它取决于你插入了多少数据。数组列表将获取所有数据,如果你没有插入任何值,那么它将给出null值。

public List<TheModelClass> getTheValue(String SomeValue) {
        List<TheModelClass> NameOfTheList = new ArrayList<TheModelClass>();
        String selectQuery = "SELECT  * FROM " + TABLE_ONE + " where " + KEY_COLUMN_ONE + " = ?";

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, new String[] {SomeValue});

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                TheModelClass AnythingYouWantToNameThis = new TheModelClass();
                AnythingYouWantToNameThis.setModelValueNumberOne(c.getString(c.getColumnIndex(KEY_COLUMN_ONE)));
                // add
                NameOfTheList.add(AnythingYouWantToNameThis);
            } while (c.moveToNext());
        }
        //always close the cursor after using it cause it may cause memory leak
        c.close();
        return NameOfTheList;
    }

从表中获取值/某些值:

public List<TheModelClass> getAllNameOfTheList() {
        List<TheModelClass> NameOfTheList = new ArrayList<TheModelClass>();
        String selectQuery = "SELECT  * FROM " + TABLE_ONE;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {

                TheModelClass SomeName = new TheModelClass();
                SomeName.setValueNumberOne(c.getString(c.getColumnIndex(KEY_COLUMN_ONE)));
                SomeName.setValueNumberTwo(c.getInt(c.getColumnIndex(KEY_COLUMN_TWO)));
                SomeName.setValueNumberThree(c.getDouble(c.getColumnIndex(KEY_COLUMN_THREE)));
                SomeName.setValueNumberFour(c.getLong(c.getColumnIndex(KEY_COLUMN_FOUR)))
                .
                .
                .
                SomeName.setValueNumberX(c.getSomeDataTypeBasedOnTheTypeYouHaveSetInTheModelClass(c.getColumnIndex(THE_COLUMN)))
                // add
                NameOfTheList.add(SomeName);
            } while (c.moveToNext());
        }
        // db.close();
        c.close();
        return NameOfTheList;
    }

然后在类上调用它(假设这个类是数据库值处理程序) 对于1列:

// Database 
    YourDatabaseClass db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testgetdata);
        db = new YourDatabaseClass(getApplicationContext());
        List<TheModelClass> Anything = db.getValue();
        TheModelClass Value0 = Anything.get(0);
        TheModelClass Value1 = Anything.get(1);
        .
        .
        .
        TheModelClass ValueX = Anything.get(X*);

        String Value0 = Value0.getValue();

        //2nd column
        String Value1 = Value1.getValue();      

        //column X      
        String ValueX = ValueX.getValue();


        Intent person = new Intent(this, NameOfTheClassThatYouWantToHaveThisValues.class);
        Bundle backpack = new Bundle();

        backpack.putString("AKA_47", Value0);

        backpack.putString("Missile", Value1);
        .
        .
        .
        backpack.putString("Anything", ValueX);

        person.putExtras(backpack);
        setResult(RESULT_OK, person);
        startActivity(person);

            // Don't forget to close database connection
        db.closeDB();

对于多个列:     //数据库         YourDatabaseClass db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testgetdata);

        db = new YourDatabaseClass(getApplicationContext());

        List<TheModelClass> Anything = db.getAllDataOfTheList();

        TheModelClass Value0 = Anything.get(0);
        TheModelClass Value1 = Anything.get(1);
        .
        .
        .
        TheModelClass ValueX = Anything.get(X*);
        /*Based on how many row you have, Start with row 0 (zero)
         * whenever TheModelClass Value0 = Anything.get(0); called then you will have
         * column0Value0 column01alue1 column2Value2.........columnXValueX      
         */
         long Value0FromColumn0 = Value0.getId();
        String Value1FromColumn0 = Value0.getName();
        int Value2FromColumn0 = Value0.getPhoneNumber();
        double Value3FromColumn0 = Value0.getETC();

        //2nd column
        long Value0FromColumn1 = Value1.getId();
        String Value1FromColumn1 = Value1.getName();
        int Value2FromColumn1 = Value1.getPhoneNumber();
        double Value3FromColumn1 = Value1.getETC();

        //column X
        long ValueXFromColumnX = ValueX.getId();
        String ValueXFromColumnX = ValueX.getName();
        int ValueXFromColumnX = ValueX.getPhoneNumber();
        double ValueXFromColumnX = ValueX.getETC();

        Intent person = new Intent(this, NameOfTheClassThatYouWantToHaveThisValues.class);
        Bundle backpack = new Bundle();
        backpack.putLong("Pencil", Value0FromColumn0);
        backpack.putString("Book", Value1FromColumn0);
        backpack.putInt("Laptop", Value2FromColumn);
        backpack.putDouble("Nuclear_BOMB", Value3FromColumn0);

        backpack.putLong("Spiderman", Value0FromColumn1);
        backpack.putString("IronMan", Value1FromColumn1);
        backpack.putInt("Hercules", Value2FromColumn1);
        backpack.putDouble("MasterYoda", Value3FromColumn1);
        .
        .
        .
        backpack.putLong("Monkey", ValueXFromColumnX);
        backpack.putString("Dolphin", ValueXFromColumnX);
        backpack.putInt("Alien", ValueXFromColumnX);
        backpack.putDouble("Predator", ValueXFromColumnX);

        person.putExtras(backpack);
        setResult(RESULT_OK, person);
        startActivity(person);

        // Don't forget to close database connection
        db.closeDB();

然后收到另一个班级的价值 多列:

@Override
    protected void onCreate(Bundle bundle) {
        // TODO Auto-generated method stub
        super.onCreate(bundle);
        setContentView(R.layout.test);
        Bundle exploded = this.getIntent().getExtras();
        if (this.getIntent().getExtras() != null) {
            long id0 = exploded.getLong("Pencil");
            String name0 = exploded.getString("Book");
            int phoneNumber0 = exploded.getInt("Laptop");
            double etc0 = exploded.getDouble("Nuclear_BOMB");
            .
            .
            .
            long X = exploded.getLong("X");
            String Y = exploded.getString("Y");
            int Z = exploded.getInt("Z");
            double W = exploded.getDouble("W");     
            }
        else {
            Message.message(this, "unread datas");
        }}

对于一栏:

Bundle exploded = this.getIntent().getExtras();
    if (this.getIntent().getExtras() != null) {
        String something0 = exploded.getString("AKA_47");
        String anything0 = exploded.getString("Missile");
        String whatever0 = exploded.getString("Anything");
        .
        .
        .
        String X = exploded.getString("X"); 
        }
    else {
        Message.message(this, "unread datas");
    }

如果你想知道什么是Message.message,它是一个类。代码:

import android.content.Context;
import android.widget.Toast;

public class Message {
    public static void message(Context context, String message)
    {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }
}

然后你拥有它们。快乐的编码!