I am writing an application code for Android for working with a SQLite database. I repeatedly come across error warning
Non-static method 'method ()' cannot be referenced from a static context
First: what is the static context ? In my code (for the time being) there is not a single static method, not a single static variable, except that there is only one static constant for logging.
Here are a couple of examples where such a warning appears:
● addNewItem method for adding a new record to the database (belongs to a separate class for working with the database):
public TestDB(Context context) { this.context = context; dbHelper = new testDBHelper (context); } public void addNewItem(String title, String noteText){ db = testDBHelper .getWritableDatabase(context); // здесь ContentValues cv = new ContentValues(); cv.put(testDBHelper .KEY_TITLE, title); cv.put(testDBHelper .KEY_TEXT, noteText); cv.put(testDBHelper .KEY_DATE, new Date().getTime()); db.insert(testDBHelper .TABLE_NAME, null, cv); } ● Saving to the database the values entered in the fields (the code belongs to the Activity with input fields):
String title = editTitle.getText().toString(); String text = editText.getText().toString(); TestDB testDB = new TestDB(AddItemActivity.getApplicationContext()); // здесь testDB.addNewItem(title, note); I admit that at the moment I almost without understanding work with context , therefore I will be grateful for any explanations.
Constructor
public TestDB(Context context) { this.context = context; testDBHelper = new TestDBHelper(context); } in the class to work with the database is available; in Activity with input fields - no.
Contextclass - it says that non-static methods cannot refer to a static environment. ThegetWritableDatabase()method takes no parameters -getWritableDatabase()instead ofgetWritableDatabase(context)- pavlofffaddNewItem()method was added by me. - Bokov GlebgetWritableDatabase()you think that you need to pass an instance of theContextclass to thegetWritableDatabase()method? - pavlofffcontextin the warning was misleading. In the second case, the wrong access to the context; correct will beAddItemActivity.this. Write then, please, in the answer some theoretical comment about the static context, so that I put a check mark on you and this question can be closed. - Bokov Hleb