简体   繁体   English

getContext()不存在

[英]getContext() doesn't exist

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. 所以我一直在官方网站上进行Android Developer培训,他们希望我们最终实例化我们的数据库。

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. 但是,我收到了getContext()方法的错误。 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. 所以我搜索了源代码,并且找不到View类中的那个方法。 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! 谢谢!

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: Context的android开发者文档:

https://developer.android.com/reference/android/content/Context.html 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? 什么是Android上的“上下文”?

Thats how I made it 多数民众赞成我是如何做到的

  1. MainActivity 主要活动

    FeedReaderContract contract = new FeedReaderContract(this); FeedReaderContract contract = new FeedReaderContract(this);

  2. I edited the constructor of the class FeedReaderContract 我编辑了FeedReaderContract类的构造函数

    mDbHelper = new FeedReaderDbHelper(getContext()); mDbHelper = new FeedReaderDbHelper(getContext());

  3. The method getContext() 方法getContext()

    public Context getContext() { return context; public Context getContext(){return context; } }

在您的代码中,您使用了geContext()将其更改为getContext()getApplicationContext()或者如果从活动内部调用该对象,则只需传递this

The View class does have a getContext method. View类有一个getContext方法。

You either have a typo, or your code is not located in a non-static method of a sub-class of View. 您要么输入错误,要么您的代码不在View的子类的非静态方法中。

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

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