Search code examples
javaandroidandroid-studioonstart

I'm Trying To add this on A onStart method


I'm trying to put this code in a onStart method. I tried several things but can't seem to find a way... if I put it on a onStart method the error is:

cannot return value from a method with a void result type

I did try changing it into a int, any ideas?

I tried to do public int onStart... method, but didn't work out very well

Note: I'm to new to Android, this my seem a obvious answer to you, but unfortunately not to me.

thanks in advance!!

public  String getGiphyViews() {
    String id_image = "qi6Yrko";
    String source = "";

    try {
        URL url = new URL("http://imgur.com/" + id_image);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        InputStream in = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        StringBuilder str = new StringBuilder();

        String line;
        while((line = reader.readLine()) != null) {
            if (line.contains("views")) {
                str.append(line);
            }
        }

        in.close();

        source = str.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String views = source.split("<span class=\"views-" + id_image  + "\">")[1].split("<")[0];

    TextView t = (TextView) findViewById(R.id.views);
    assert t != null;
    t.setText(views);

    return views;
}

Solution

  • You can not change the onStart method return type from void to int. This method is part of the life cycle of any Android Activity. With implementing this method, you basically override the parent method. And when you override a method, you are always obligated to keep the same return type, method name and arguments. There is no way around it. So it would help if you explain why you would even want this to return anything? I would suggest, in case you need some value from the Activity, that you save the value inside the Activity and then pass the value with a getter method.

    For further explanation please check the Android documentation.