getContext() doesn't exist

一笑奈何 提交于 2019-12-05 17:24:39

问题


So I have been going through the Android Developer training on the official site and there is a point where they want us to finally instantiate our database.

So they tell us to use this snippet of code:

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());

However, I'm getting an error for the getContext() method. It states that it cannot find a symbol for that method.

So I searched the source and that method in the View class just cannot be found. Is this a deprecated method? And if this isn't an option, is there any other way we can grab the context of a view?

Thank you!


回答1:


The line of code you pass is:

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(geContext());


It should work if you substitute for any of these code lines :

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());

Or

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getApplicationContext());

Or

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(this);


The android developer documentation of the Context:

https://developer.android.com/reference/android/content/Context.html

You might found helpful too look in this question, that explains what is Context for:

What is 'Context' on Android?




回答2:


In your code you have used geContext() change it to getContext() or getApplicationContext() or if calling the object from inside an activity simply pass this




回答3:


The View class does have a getContext method.

You either have a typo, or your code is not located in a non-static method of a sub-class of View.




回答4:


Thats how I made it

  1. MainActivity

    FeedReaderContract contract = new FeedReaderContract(this);

  2. I edited the constructor of the class FeedReaderContract

    mDbHelper = new FeedReaderDbHelper(getContext());

  3. The method getContext()

    public Context getContext() { return context; }



来源:https://stackoverflow.com/questions/25587265/getcontext-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!