简体   繁体   中英

Java- Make Cursor variable static in a method

I've created a mySQL database with java and what I'm trying to do is to let the class have only one instance of the 'Cursor c' variable that is in the 'getData()' method. This is so that anytime the getData() method is called, the cursor can continue reading the database from where it left off, rather than start from the beginning.

I tried taking the 'Cursor c' out of the method and making it static but then it causes other problems.

Could you show me how to do it properly?

    public class SQLClass {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "IncomeName";
    public static final String KEY_AMOUNT = "IncomeAmount";

    private static String DATABASE_NAME = "MoneyTracker";
    private static String DATABASE_TABLE = "IncomeTable";
    private static int DATABASE_VERSION = 1;


    private DbHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper{

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

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL("CREATE TABLE " + DATABASE_TABLE + "(" + KEY_ROWID + "         INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + KEY_NAME + " TEXT NOT NULL, " + KEY_AMOUNT + " TEXT NOT NULL);");
        }//end onCreate method 

        @Override
        public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
            // TODO Auto-generated method stub
            db.execSQL("DROP IF EXISTS " + DATABASE_NAME);
            onCreate(db);
        }//end onUpgrade method

    }//end class DbHelper

    public SQLClass (Context c){
        ourContext = c;
    }//end constructor SQLClass

    public SQLClass open()throws SQLException{
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }//end method open

    public void close(){
        ourHelper.close();
    }//end method close

    public long createEntry(String name, String amount) {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_AMOUNT, amount);
        return ourDatabase.insert(DATABASE_TABLE, null, cv);
    }


    public String[] getData() {
        // TODO Auto-generated method stub
        String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_AMOUNT};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String[] result = new String[]{"","",""};

        int iRow = c.getColumnIndex(KEY_ROWID);
        int iName = c.getColumnIndex(KEY_NAME);
        int iAmount = c.getColumnIndex(KEY_AMOUNT);


            c.moveToNext();
            result[0] = c.getString(iRow);
            result[1] = c.getString(iName);
            result[2] = c.getString(iAmount);

        return result;
    }//end method getData
}//end class SQLClass

Here is a classic java example how to access static field in non-static class methods:

public class MyClass {

        private static int staticCursor;

        {  // Initialize 
            staticCursor = 1;
        }

        public int getData(){
            int retval;
            retval = MyClass.staticCursor;
            MyClass.staticCursor++;
            return retval;
        }

        public static void main(String[] args) {

            MyClass myClass1 = new MyClass();
            MyClass myClass2 = new MyClass();
            MyClass myClass3 = new MyClass();

            System.out.println( myClass1.getData() );
            System.out.println( myClass2.getData() );
            System.out.println( myClass3.getData() );
            System.out.println( myClass1.getData() );
      }
    }

run results:
====================
1
2
3
4

However if you plan to share your cursor variable between many class instances running in multithreaded environment, you need a carefully thought-out synchronization and initialization stuff, sharing cursor between threads can cause hard to diagnose errors.

Thanks you helped me understand how to access static fields in non-static methods but that was not what i was looking for. Maybe I didn't ask the right question. Anyway i manage to solve the problem by making getData() take an argument, int position, to be used as the current position of the cursor and changed c.moveToNext() to c.moveToPosition(position)

        public String[] getData(int position) {
    // TODO Auto-generated method stub
    String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_AMOUNT};
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String[] result = new String[]{"","",""};

    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iAmount = c.getColumnIndex(KEY_AMOUNT);


    c.moveToPosition(position);
    if (!c.isAfterLast()){
    result[0] = c.getString(iRow);
    result[1] = c.getString(iName);
    result[2] = c.getString(iAmount);

    }else if(c.isAfterLast()){
    result[0] = "false";

    }

    return result;
}//end method getData

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM