简体   繁体   中英

Should I use static method or public method … android

I want to create DownloadData class and there implement a method to download the data from my web service !

in this way :

public class DownloadData {

public static string getData("url"){  ..... return data;}

}

so should I declare the method as static and then i could call it by the class name with out create DownloadData object; or to "not" declare it as static and then I should create an object to call the method.

edit: I can't use getData method in several thread if I declare another static fields in this way :

public class DownloadData {
    static int num=0;
    public static string getData("url"){ 
 ..... return data;}

    }

thank you very much

You can declare your method as static if you don't need your class DownloadData to hold any state and you won't need to use an instance of DownloadData class anywhere (eg to pass it as a parameter).

Don't think about a single method in this class, think about how you're going to use the class as a whole.

Note: state can be also stored in static variables but that means you have only set of values. That may be appropriate in some cases but you would need to be careful in a multithreaded environment.

You may want to think about how you will accomplish this. Android recently requires you to do webrequests async now and will error if you don't do it this way. This will limit how you will pull data now.

Download a file with Android, and showing the progress in a ProgressDialog

If you are using json and you have it well organized, I would also recommend taking a look at retrofit http://square.github.io/retrofit/ . It is very easy to implement and saves your a lot of work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM