【问题标题】:How to resolve non-static method errors from static context?如何解决静态上下文中的非静态方法错误?
【发布时间】:2016-11-11 13:34:33
【问题描述】:

我得到了这个,实际上它在旧版本中运行,但没有在 Android 2.2 中运行,这是代码......我不知道用什么替换它或有替代方案。 所以我添加了整个代码以便能够理解真实的。我看到它在旧版本的 android studio 上运行的问题。

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String Database_Name= "student.db";
    public static final String Table_Name= "student_table";
    public static final String COL_1= "id";
    public static final String COL_2= "name";
    public static final String COL_3= "surname";
    public static final String COL_4= "marks";

    public DatabaseHelper(Context context){
        super(context, Database_Name,null,1);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table" + Table_Name +  " (id integer primary key auto increment, name text, surname text, marks ineteger)" );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists" + Table_Name);
        onCreate(db);
    }

    public boolean insertData(String name, String surname, String marks){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        ContentValues.put(COL_2,name);
        ContentValues.put(COL_3,surname);
        ContentValues.put(COL_4,marks);

        long result = db.insert(Table_Name, null,contentValues);
        if (result==-1) {
            return false;
        } else {
            return true;
        }
    }
}

【问题讨论】:

    标签: android android-studio static-methods


    【解决方案1】:

    发生此错误是因为您混淆了类的静态和非静态部分。

    举个例子:

    public class Test {
        public String testVariable = "Honk";
    
        public static String methodTest() {
            return testVariable;
        }
    
        public static String methodTest2() {
            Test test = new Test();
            return test.testVariable;
        }
    
        public String methodTest3() {
            return testVariable;
        }
    }
    

    方法测试

    此测试将失败。您正在尝试从静态上下文 methodTest() 获取非静态变量 testVariable

    访问:

    String result = Test.methodTest();
    

    方法测试2

    这会奏效。您正在创建一个新的Test 类实例,您可以正常访问变量testVariable

    访问:

    String result = Test.methodTest2();
    

    方法测试3

    这会奏效。您正在从非静态上下文 methodTest3() 访问非静态变量 testVariable

    访问:

    Test test = new Test(); 
    String result = test.methodTest();
    

    分辨率

    如果没有看到您的其余代码,很难给您建议更改的内容。您在问题中提供的代码不太可能是罪魁祸首。

    编辑

    您的问题是您正在静态访问ContentValues 类...

    ContentValues.put(COL_2,name);
    

    您需要使用您创建的变量:contentValues

    【讨论】:

    • 我明白了,但请检查整个代码,我现在已经编辑过了。谢谢
    • 帮我找出问题。哪个确切部分给了你这个错误?
    • 啊,我明白了:ContentValues.put(COL_2,name);。您正在静态访问ContentValues。你需要访问它的实例变量contentValues
    猜你喜欢
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    相关资源
    最近更新 更多