简体   繁体   English

Java-在方法中将Cursor变量设为静态

[英]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. 我已经用Java创建了一个mySQL数据库,而我想做的就是让该类在'getData()'方法中只有'Cursor c'变量的一个实例。 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. 这样一来,只要调用getData()方法,游标就可以从中断处继续读取数据库,而不是从头开始。

I tried taking the 'Cursor c' out of the method and making it static but then it causes other problems. 我尝试将“ Cursor c”从方法中删除,使其固定为静态,但随后导致其他问题。

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: 这是一个经典的Java示例,如何在非静态类方法中访问静态字段:

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) 无论如何,我设法通过使getData()接受参数int position作为游标的当前位置并将c.moveToNext()更改为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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