调用doInBackground的NoSuchMethodException

时间:2015-06-07 19:20:19

标签: android menu android-asynctask nosuchmethoderror

我是Android的新用户。在menu item中选择操作时,我想调用Myclass扩展AsyncTask中的方法。我想调用的方法是doInBackgroundMyclassMainActivityFragment.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具有受保护的访问权。

请帮助。

以下是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;
    }
}

2 个答案:

答案 0 :(得分:4)

只需删除此行

即可
android:onClick="doInBackground" 

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

答案 1 :(得分:1)

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

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

在你的情况下:

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

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