NoSuchMethodException 用于调用 doInBackground

NoSuchMethodException for calling doInBackground

我是 Android 的新手。在 menu item 中选择一个动作时,我想调用 Myclass extends AsyncTask 中的一个方法。我要调用的方法是 doInBackgroundMyclass 是 class 出现在 MainActivityFragment.java.

我的xml菜单如下:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:title="Refresh"
        android:id="@+id/action_refresh"
        android:label="@string/refresh"
        android:onClick="doInBackground"
        />

</menu>

但是在 运行 应用程序上我得到了 NoSuchMethodException

我尝试在 MainActivity 中调用一个方法,然后从那里调用方法 doInBackground 但它给我错误 doInBackground has protected access.

请帮忙。

这里是MainActivityFragment.java

的完整代码
public  class MainActivityFragment extends Fragment {

    public MainActivityFragment() {
    }

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootview = inflater.inflate(R.layout.fragment_main, container, false);
        ArrayList<String> x = new ArrayList<String>();
        x.add("Today - sunny 88/63");
        x.add("Tomorrow - Foggy 76/43");
        x.add("Weds - cloudy 72/63");
        x.add("Thrus - rainy 64/51");
        x.add("Fri - foggy 70/46");
        x.add("Sat - sunny 76/68");
        ArrayAdapter<String> weather_adapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, x);
        ListView listview = (ListView) rootview.findViewById(R.id.list_view_forecast);
        listview.setAdapter(weather_adapter);



        return rootview;
    }
    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater)
    {
        inflater.inflate(R.menu.forecast_fragment,menu);
    }
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id=item.getItemId();
        if(id==R.id.action_refresh) {
            FetchWeatherTask w=new FetchWeatherTask();
            w.execute();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

class FetchWeatherTask extends AsyncTask
{



    @Override
    protected Object doInBackground(Object[] params) {
        // These two need to be declared outside the try/catch
        // so that they can be closed in the finally block.
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        // Will contain the raw JSON response as a string.
        String forecastJsonStr = null;

        try {
            // Construct the URL for the OpenWeatherMap query
            // Possible parameters are avaiable at OWM's forecast API page, at
            // http://openweathermap.org/API#forecast
            URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");

            // Create the request to OpenWeatherMap, and open the connection
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            forecastJsonStr = buffer.toString();
        } catch (IOException e) {
            Log.e("MainActivityFragment", "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attemping
            // to parse it.
            return null;
        } finally{
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("MainActivityFragment", "Error closing stream", e);
                }
            }
        }

        return null;
    }
}

您需要在MainActivityFragment 中定义一个方法class,您不能在AsyncTask 中使用该方法。 在菜单项上签名是

public boolean methodname(MenuItem item) { 
// actions
}

你的情况:

 public boolean doInBackground(MenuItem item){
     FetchWeatherTask w=new FetchWeatherTask();
     w.execute();
     return true;
}

或者只删除xml中的onclick,onOptionsItemSelected应该会处理它。

只需删除这一行

android:onClick="doInBackground" 

它会 运行 没问题。我 运行 它在我的系统上,你的代码没问题。