简体   繁体   English

第一个参数类型错误。 找到:'com.example.sunshine.FetchData',需要:'android.content.Context'

[英]Wrong 1st argument type. Found: 'com.example.sunshine.FetchData', required: 'android.content.Context'

I guess this question is more about understanding context and how to use it properly.我想这个问题更多的是关于理解上下文以及如何正确使用它。 After having googled and "stackoverflowed" a lot I could not find the answer.在谷歌搜索和“stackoverflowed”很多之后,我找不到答案。

Problem:问题:
when using DateUtils.formatDateTime I cannot use "this" as a context.使用 DateUtils.formatDateTime 时,我不能使用“this”作为上下文。 The error message is as described in the title.错误消息如标题中所述。

Application Info:申请资料:
This is a simple weather app retrieving weather information via JSON and displaying it on the screen.这是一个简单的天气应用程序,通过 JSON 检索天气信息并将其显示在屏幕上。

Activities:活动:
- MainActivity.java - MainActivity.java
- FetchData.java - 获取数据.java

MainActivity: displaying the info MainActivity:显示信息
FetchData: getting JSON info from the API, formatting it and sending it back to MainActivity FetchData:从 API 获取 JSON 信息,对其进行格式化并将其发送回 MainActivity

I am using DateUtils.formatDateTime in the FetchData.java activity and using "this" as a context does not work.我在 FetchData.java 活动中使用 DateUtils.formatDateTime 并且使用“this”作为上下文不起作用。 As from my understanding Context provided the "environment" (?) of where the method is being called.根据我的理解 Context 提供了调用方法的“环境”(?)。

  1. Why is the "environment" of FetchData not valid?为什么 FetchData 的“环境”无效?
  2. What content should be provided instead?应该提供什么内容?

Help is much appreciated.非常感谢帮助。 Thank you :)谢谢 :)

Code:代码:

    private ArrayList<String> getWeatherDataFromJson(String forecastJsontStr) throws JSONException {

    ArrayList<String> dailyWeatherInfo = new ArrayList<>();
    int dataCount;
    DateUtils tempDate = new DateUtils();

    JSONObject weatherData = new JSONObject(forecastJsontStr);
    JSONArray threeHourWeatherData = weatherData.getJSONArray(JSON_LIST);

    dataCount = weatherData.getInt("cnt");
    JSONObject tempJSONWeatherData;

    for (int i = 0; i < dataCount; i++) {
        tempJSONWeatherData = threeHourWeatherData.getJSONObject(i);
        tempDate.formatDateTime(this,tempJSONWeatherData.getLong("dt"),
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY |
                        DateUtils.FORMAT_ABBREV_ALL);
    [more code here]
    return dailyWeatherInfo;
}

Edit : I just realized I left out an important detail, namely this activity extends AsyncTask .编辑:我刚刚意识到我遗漏了一个重要的细节,即这个活动扩展了AsyncTask After some further research apparently you provide the context bei adding WeakReference and then adding context in the constructor.经过一些进一步的研究,显然您提供了上下文,即添加WeakReference然后在构造函数中添加上下文。

I added the following code:我添加了以下代码:

private WeakReference<Context> contextWeakReference;

public FetchData (Content context) {
    contextWeakReference = new WeakReference<>();
}
tempDate.formatDateTime(contextWeakReference.get(),tempJSONWeatherData.getLong("dt"),
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY |
                        DateUtils.FORMAT_ABBREV_ALL);

This made the error disappear but I still don't understand why "this" doesn't work.这使错误消失,但我仍然不明白为什么“这个”不起作用。

I am using DateUtils.formatDateTime in the FetchData.java activity and using "this" as a context does not work.我在 FetchData.java 活动中使用 DateUtils.formatDateTime 并且使用“this”作为上下文不起作用。 As from my understanding Context provided the "environment" (?) of where the method is being called.根据我的理解 Context 提供了调用方法的“环境”(?)。

You're incorrect, Context is Android context which is (from documentation ):你错了, Context 是 Android 上下文,它是(来自文档):

Interface to global information about an application environment.有关应用程序环境的全局信息的接口。 This is an abstract class whose implementation is provided by the Android system.这是一个抽象类,其实现由Android系统提供。 It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.它允许访问特定于应用程序的资源和类,以及调用应用程序级操作,例如启动活动、广播和接收意图等。

DateUtils.formatDateTime() needs Context as one of its parameter. DateUtils.formatDateTime()需要 Context 作为其参数之一。 So, you need to pass a context.所以,你需要传递一个上下文。

Android Activity is sub class of Context, so you can use this (which refer to itself) as the context like the following:Android Activity是 Context 的子类,因此您可以使用this (指的是自身)作为上下文,如下所示:

public class MyActivity extends Activity {
     ...
     protected void doSomething() {
        // this refer to the MyActivity instance which is a Context.
        DateUtils.formatDateTime(this, ...);
     }
     ...
 }

You need to pass the Context for every class that is not a Context subclass.您需要为每个不是 Context 子类的类传递 Context 。

You can't use this in AsyncTask because it's not a Context subclass.您不能在AsyncTask 中使用this ,因为它不是 Context 子类。 So, you need to pass the Context using WeakReference to avoid Context leaking , like the following:因此,您需要使用WeakReference传递 Context 以避免Context leaking ,如下所示:

private class AsyncTaskRunner extends AsyncTask<String, String, String> {

     private WeakReference<Context> contextWeakReference;

     public FetchData (Content context) {
        contextWeakReference = new WeakReference<>();
     }

     private void doSomething() {
        // We have the context from the WeakReference
        Context context = contextWeakReference.get();
        DateUtils.formatDateTime(context, ...);
     }
}

Last, you don't need to create a DateUtils object when calling DateUtils.formatDateTime() , so this isn't necessary:最后,在调用DateUtils.formatDateTime()时不需要创建 DateUtils 对象,因此这不是必需的:

DateUtils tempDate = new DateUtils();
tempDate.formatDateTime(...);

You can directly call it because it's a static method:你可以直接调用它,因为它是一个静态方法:

DateUtils.formatDateTime(...);

tempDate.formatDateTime(this,tempJSONWeatherData.getLong("dt"), 而不是 this 你可以传递应用程序的上下文,这指的是类 FetchData

暂无
暂无

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

相关问题 错误的第一个参数类型 - Wrong 1st argument type 错误的第二个参数类型。 找到“java.lang.String”,需要“android.location.Location” - Wrong 2nd argument type. Found 'java.lang.String', required 'android.location.Location' 如何修复 BroadcastReceiver 中的 [找到:'android.content.Context',必需:'androidx.lifecycle.LifecycleOwner']? - How to fix [Found: 'android.content.Context', required: 'androidx.lifecycle.LifecycleOwner' ] in BroadcastReceiver? 不兼容的类型。 必需:android.content.Context找到:java.lang.String - Incompatible types. Required: android.content.Context Found: java.lang.String android.content.Context类型无法解析。 它是从所需的.class文件间接引用的 - The type android.content.Context cannot be resolved. It is indirectly referenced from required .class files 错误的第二个参数类型找到 andriod.content.Dialoginterface.onClicklistener, required andrid.content.Context - wrong second argument type Found andriod.content.Dialoginterface.onClicklistener, required andrid.content.Context Android - 错误的第一个参数类型和“android.supportv4.app.Fragment” - Android - Wrong 1st argument type and ' android.supportv4.app.Fragment' 错误的第二个参数类型。 必需:“ android.support.v4.app.Fragment” - wrong 2nd argument type. required: 'android.support.v4.app.Fragment' 片段数组中“this”的第一个参数类型错误 - Wrong 1st Argument Type Error on "this" in Fragment Array 错误的第一个参数类型Uri / FileProvider Fragment - Wrong 1st argument Type Uri/FileProvider Fragment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM