android 方法不会重写或实现超类型中的方法-对于

643ylb08  于 2023-11-15  发布在  Android
关注(0)|答案(7)|浏览(135)

我已经看过了,但不知道为什么我得到的错误
错误:方法不重写或实现超类型的方法
这突出显示了我在一个方法(子例程?)中的两个@Override。这是我的MainActivity.java-它出现在queryBooks()方法末尾的代码部分-@Override都有红色下划线。

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它的价值,我遵循this教程)。
谢谢你的任何想法!

mv1qrgav

mv1qrgav1#

问题是错误消息所说的:“该方法不覆盖或实现超类型的方法”。您使用Override annotation注解了两个方法,但是,在超类型(JsonHttpResponseHandler)中找不到具有相同签名**(* 即参数 )的方法*。
如果你看一下documentation of JsonHttpResponseHandler,你可以看到所有可用的onSuccess(...)onFailure(...)方法。
下面是你的代码的工作版本(注意方法签名的变化):

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());
        }
    });

字符串
请注意,从Android 6.0(API level 23)开始,Apache库(org.apache.http.*)不再可用。如果要继续使用该库,请参阅行为更改以了解详细信息。
一些个人意见:我不推荐使用 Asynchronous HTTP Library,因为它是建立在过时的(从API level 23中删除)Apache HttpClient之上的,与HttpURLConnection相比,它的性能很差。
此API效率更高,因为它通过透明压缩和响应缓存减少了网络使用,并最大限度地降低了功耗。

nnsrf1az

nnsrf1az2#

解决上述问题的简单方法
错误代码:

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();
}
}

字符串

解决方案:

这里我只是删除了**@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();
}
}

vcudknz3

vcudknz33#

我不确定你使用的是哪个版本的loopj库,但是从这个Javadoc link中,你的onSuccessonFailure方法签名都是不同的。
一定是的,

@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) {}

字符串
请注意您遗漏的headers参数。

gr8qqesn

gr8qqesn4#

您正在学习的教程使用的是1.4.4版的异步Http客户端库。您可能使用的是另一个版本。
在Gradle配置中指定此版本:

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

字符串
或者更改您的定义以反映您正在使用的版本的方法签名,例如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) {
    // ...
}

z9gpfhce

z9gpfhce5#

我在这个例子中遇到了这个问题(代码被简化了):

public interface SomeInterface {
Long getField();
}

@SuperBuilder
public abstract class Parent implements SomeInterface {

private field;

@Override
public Long getField() {
return field;
}

@SuperBuilder(toBuilder = true)
public class Child extends Parent {
//some code here
}

}

字符串
我通过删除Child中的“(toBuilder = true)”解决了这个问题。

4dbbbstv

4dbbbstv6#

为你的类添加一个Java文档,以覆盖或实现超类行为。
不幸的是,我没有来源,这就是我破解我的。
要点是Java文档不仅仅是一个文档,它还是一个通知类的构造的工具,它为getter和setter传递数据,类等等
它以HTML DOCUMENT的形式处理API事务。
希望对一些人有所帮助。

3bygqnnd

3bygqnnd7#

这是Eclipse几十年来一直存在的问题。继续使用add未实现的方法,把你原来的override方法中的代码放到eclipse刚刚生成的新方法中,然后比较这两个方法。你会发现它们是相同的。删除旧的override方法并编译。错误消失。现在把override方法移到你原来的位置,其他开发人员不会被这个变化所迷惑。这是Eclipse这些年来一直没有解决的问题。

相关问题