Java 方法不会覆盖或实现来自超类型的方法 - 对于 Override

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32217737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:10:40  来源:igfitidea点击:

method does not override or implement a method from a supertype - for Override

javaandroid

提问by BruceWayne

I have looked all around but can't figure out why I'm getting the error

我环顾四周,但不明白为什么我收到错误

error: method does not override or implement a method from a supertype

错误:方法没有覆盖或实现来自超类型的方法

This highlights the two @Overrides I have in a method (subroutine?). Here's my MainActivity.java- the part of the code it occurs in the queryBooks()method at the end - the @Overrides are both underlined red.

这突出了@Override我在方法(子程序?)中的两个s。这是我的MainActivity.java- 它出现在最后queryBooks()方法中的代码部分- @Overrides 都带有红色下划线。

package com.example.batman.myapplication;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.view.MenuItemCompat;
//import android.support.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    TextView mainTextView;
    EditText mainEditText;
    ListView mainListView;
    ArrayAdapter mArrayAdapter;
//  ArrayList<String> mNameList = new ArrayList<String>();
    ArrayList mNameList = new ArrayList();
    android.support.v7.widget.ShareActionProvider mShareActionProvider;

    // This is for internet stuff
    private static final String QUERY_URL = "http://openlibrary.org/search.json?q=";


    // Setting up the storage of data
    private static final String PREFS = "prefs";
    private static final String PREF_NAME = "name";
    SharedPreferences mSharedPreferences;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 1. Access the TextView defined in layout XML
        // and then set its text
        mainTextView = (TextView) findViewById(R.id.main_textview);
//      mainTextView.setText("Set in Java!");

        Button mainButton;
        mainButton = (Button) findViewById(R.id.main_button);
        mainButton.setOnClickListener(this);

        // 3.  Access the EditText defined in layout XML
        mainEditText = (EditText) findViewById(R.id.main_edittext);

        // 4. Access the ListView
        mainListView = (ListView) findViewById(R.id.main_listview);
        // Create an ArrayAdapter for the ListView
        mArrayAdapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1,
                mNameList);
        // Set the ListView to use the ArrayAdapter
        mainListView.setAdapter(mArrayAdapter);

        // 5. Set this activity to react to list items being pressed
        mainListView.setOnItemClickListener(this);

        // 7. Greet the user, or ask for their name if new
        displayWelcome();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu.
        // Adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        // Access the Share Item defined in menu XML
        MenuItem shareItem = menu.findItem(R.id.menu_item_share);

        // Access the object responsible for
        // putting together the sharing submenu
        if (shareItem != null) {
            mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
        }

        // Create an Intent to share your content
        setShareIntent();

        return true;
    }

    private void setShareIntent() {

        if (mShareActionProvider != null) {

            // create an Intent with the contents of the TextView
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Android Development");
            shareIntent.putExtra(Intent.EXTRA_TEXT, mainTextView.getText());

            // Make sure the provider knows
            // it should work with that Intent
            mShareActionProvider.setShareIntent(shareIntent);
        }
    }

    @Override
    public void onClick(View v) {
//      // Take what was typed into the EditText
//      // and use in TextView
//      mainTextView.setText(mainEditText.getText().toString() + ".");
//
//      // Also add that value to the list shown in the ListView
//      mNameList.add(mainEditText.getText().toString());
//      mArrayAdapter.notifyDataSetChanged();
//      // 6. The text you'd like to share has changed,
//      // and you need to update
//      setShareIntent();
//
//      if(v == mainEditText) {
//          mainEditText.setText("");
//      }

        // 9. Take what was typed into the EditText and use in search
        // (the above is commented out, per tutorial part 3 - this takes its place as input
        queryBooks(mainEditText.getText().toString());
//      mainEditText.setText("");
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        // Log the item's position and contents
        // to the console in Debug
        Log.d("My Application", position + ": " + mNameList.get(position));
    }

    public void displayWelcome() {

        // Access the device's key-value storage
        mSharedPreferences = getSharedPreferences(PREFS, MODE_PRIVATE);

        // Read the user's name,
        // or an empty string if nothing found
        String name = mSharedPreferences.getString(PREF_NAME, "");

        if (name.length() > 0) {

            // If the name is valid, display a Toast welcoming them
            Toast.makeText(this, "Welcome back, " + name + "!", Toast.LENGTH_LONG).show();
        } else {

            // otherwise, show a dialog to ask for their name
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("Hello!");
            alert.setMessage("What is your name?");

            // Create EditText for entry
            final EditText input = new EditText(this);
            alert.setView(input);

            // Make an "OK" button to save the name
            alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int whichButton) {

                    // Grab the EditText's input
                    String inputName = input.getText().toString();

                    // Put it into memory (don't forget to commit!)
                    SharedPreferences.Editor e = mSharedPreferences.edit();
                    e.putString(PREF_NAME, inputName);
                    e.commit();

                    // Welcome the new user
                    Toast.makeText(getApplicationContext(), "Welcome, " + inputName + "!", Toast.LENGTH_LONG).show();
                }
            });
        // Make a "Cancel" button
        // that simply dismisses the alert
                    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {}
                    });

            alert.show();
    }
    }

    // Internet stuff
    private void queryBooks(String searchString) {

        // Prepare your search string to be put in a URL
        // It might have reserved characters or something
        String urlString = "";
        try {
            urlString = URLEncoder.encode(searchString, "UTF-8");
        } catch (UnsupportedEncodingException e) {

            // if this fails for some reason, let the user know why
            e.printStackTrace();
            Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

        // Create a client to perform networking
        AsyncHttpClient client = new AsyncHttpClient();

        // Have the client get a JSONArray of data
        // and define how to respond
        client.get(QUERY_URL + urlString,
                new JsonHttpResponseHandler() {

                    @Override // THIS METHOD DOES NOT OVERRIDE METHOD FROM ITS SUPERCLASS ??
                    public void onSuccess(JSONObject jsonObject) {
                        // Display a "Toast" message
                        // to announce your success
                        Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();

                        // 8. For now, just log results
                        Log.d("omg android", jsonObject.toString());
                    }

                    @Override // THIS METHOD DOES NOT OVERRIDE METHOD FROM ITS SUPERCLASS ??
                    public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                        // Display a "Toast" message
                        // to announce the failure
                        Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();

                        // Log error message
                        // to help solve any problems
                        Log.e("omg android", statusCode + " " + throwable.getMessage());
                    }
                });
    }
} // end class

(For what it's worth, I'm following thistutorial).

(对于它的价值,我正在关注教程)。

Thanks for any thoughts!

感谢您的任何想法!

采纳答案by Gergely K?r?ssy

The problem is what the error message is saying: "the method does not override or implement a method from a supertype". You annotated both methods with the Override annotation, however, no method with the same signature(i.e. the parameters) can be found in the supertype (JsonHttpResponseHandler).

问题在于错误消息所说的内容:“该方法没有覆盖或实现来自超类型的方法”。您使用Override 注释对这两个方法进行了注释,但是,在超类型 ( ) 中找不到具有相同签名即参数)的方法JsonHttpResponseHandler

If you take a look at the documentation of JsonHttpResponseHandler, you can see all the available onSuccess(...)and onFailure(...)methods.

如果您查看JsonHttpResponseHandler文档,您可以看到所有可用的onSuccess(...)onFailure(...)方法。

Here is the working version of your code (note that changes in the method signatures):

这是您的代码的工作版本(请注意方法签名的更改):

client.get(QUERY_URL + urlString,
    new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, org.apache.http.Header[] headers, JSONObject jsonObject) {
            // Display a "Toast" message
            // to announce your success
            Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();

            // 8. For now, just log results
            Log.d("omg android", jsonObject.toString());
        }

        @Override
        public void onFailure(int statusCode, org.apache.http.Header[] headers, Throwable throwable, JSONObject error) {
            // Display a "Toast" message
            // to announce the failure
            Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();

            // Log error message
            // to help solve any problems
            Log.e("omg android", statusCode + " " + throwable.getMessage());
        }
    });

Note that starting from Android 6.0 (API level 23) the Apache library (org.apache.http.*) is not available anymore. If you want to continue using that, see Behavior Changesfor more information.

请注意,从 Android 6.0(API 级别 23)开始,Apache 库 (org.apache.http.*) 不再可用。如果您想继续使用它,请参阅行为更改以获取更多信息。

Some personal opinion: I wouldn't recommend using the Asynchronous HTTP Libraryas it's built on top of the obsolete (and from API level 23, removed) Apache HttpClient, which has poor performance compared to HttpURLConnection. Quote from the Android developers about HttpURLConnection:

一些个人意见:我不建议使用异步 HTTP 库,因为它建立在过时的(从 API 级别 23 开始,已删除) Apache 之上,HttpClientHttpURLConnection. 来自 Android 开发者的报价HttpURLConnection

This API is more efficient because it reduces network use through transparent compression and response caching, and minimizes power consumption.

此 API 更高效,因为它通过透明压缩和响应缓存减少了网络使用,并最大限度地降低了功耗。

回答by Codebender

I am not sure which version of loopjlibrary you are using, but from this Javadoc link, your onSuccessand onFailuremethod signatures are both different.

我不确定您使用的是哪个版本的loopj库,但是从这个Javadoc 链接,您的onSuccessonFailure方法签名都不同。

They have to be,

他们必须是,

@Override
public void onSuccess(int statusCode,
                      org.apache.http.Header[] headers,
                      org.json.JSONObject response) {}

@Override
public void onFailure(int statusCode,
                      org.apache.http.Header[] headers,
                      java.lang.Throwable throwable,
                      org.json.JSONObject errorResponse) {}

Note the headersparameter you have missed.

请注意headers您遗漏的参数。

回答by Esteban Herrera

The tutorial you're following uses version 1.4.4 of the Asynchronous Http Client library. You're probably using another version.

您正在学习的教程使用异步 Http 客户端库的 1.4.4 版。您可能正在使用另一个版本。

Either specify this version on your Gradle configuration:

在您的 Gradle 配置中指定此版本:

dependencies {
    ...
    compile 'com.loopj.android:android-async-http:1.4.4'
    ...
}

Or change your definition to reflect the method signatures of the version you're using, for example for 1.4.8 (latest):

或者更改您的定义以反映您正在使用的版本的方法签名,例如 1.4.8(最新):

@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
    // ...
}

@Override
public void onFailure(int statusCode,
                  org.apache.http.Header[] headers,
                  java.lang.Throwable throwable,
                  org.json.JSONObject errorResponse) {
    // ...
}

回答by seka

Easy solutionto fixed above issue

解决上述问题的简单解决方案

Wrong code:

错误代码:

public class BatteryStatusPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    List<NativeModule> modules = new ArrayList<>();

    modules.add(new BatteryStatusModule(reactContext));

    return modules;
}

@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
    return Collections.emptyList();
}

@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
}
}

Solution:

解决方案:

Here i just removed @override

在这里我刚刚删除了@override

public class BatteryStatusPackage implements ReactPackage {

public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    List<NativeModule> modules = new ArrayList<>();

    modules.add(new BatteryStatusModule(reactContext));

    return modules;
}

public List<Class<? extends JavaScriptModule>> createJSModules() {
    return Collections.emptyList();
}

public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
}
}