code example for writing a simple Android weather application _android

Source: Internet
Author: User
Tags getmessage throwable

This article introduced the simple Weather app mainly uses rxandroid, the MVP, the retrofit realization, first looks at the effect:
Home Page Content:

Right column weather list:

Left column City list

First look at the activity main code (using MVP mode):

Call the presenter method to get the data Mmainpresenter = new Mainpresenterimpl (this); 
Mmainpresenter.getplacedata (); 

Mmainpresenter.getweatherdata ("Chengdu"); 
  Displays the home page and the right column weather data public void Setupweatherdata (Weatherresponse weatherresponse) {if (weatherresponse = = null) return; 
  Settitletext (Dateutils.getweekday (weatherresponse.date)); if (weatherresponse.results!= null && weatherResponse.results.size () > 0) {weatherresult result = Weathe 
    RResponse.results.get (0); 
    Mtvcity.settext (GetString (r.string.city, result.currentcity)); 
 
    Mtvpm25.settext (GetString (R.STRING.PM25, RESULT.PM25)); 
    Mweatherdataadapter.setdata (Result.weather_data); 
 
    Mweatherdataadapter.notifydatasetchanged (); 
    Mweatherextraadapter.setdata (Result.index); 
  Mweatherextraadapter.notifydatasetchanged (); 
    }//Show left column city list @Override public void Setupplacedata (list<place> placelist) {if (placelist = = null) { 
  Return 
  } mplaceadapter.setdata (Placelist); Mplaceadapter. notifydatasetchanged (); 

 }

Take a look at how to apply Rxjava, rxandroid get data in presenter

Get Weather data @Override public void Getweatherdata (String place) {if (textutils.isempty) {return; 
  } mmainview.showprogress (); Servicemanager.getinstance (). Getapiservice (). Getweatherinfo (Place, Constants.baidu_ak). Subscribeon ( Schedulers.io ()). Observeon (Androidschedulers.mainthread ()). Subscribe (New subscriber<weatherresponse> 
          () {@Override public void oncompleted () {LOG.E (TAG, "oncompleted"); 
        Mmainview.hideprogress (); 
          @Override public void OnError (Throwable e) {log.e (TAG, E.getmessage (), E); 
        Mmainview.hideprogress (); @Override public void OnNext (Weatherresponse weatherresponse) {Mmainview.setupweatherdat 
        A (Weatherresponse); 
} 
      }); Public interface Apiservice {/* @GET ("service/getipinfo.php") call<getipinforesponse> Getipinfo (@Query (" IP ") String IP); */@GET (" Service/getipinfo.php ") observable<getipinforesponse> Getipinfo (@Query (" IP ") String IP); http://api.map.baidu.com/telematics/v3/weather?location=%E6%88%90%E9%83%BD&output=json&ak= MPDGJ92WUYVRMYAUDQS1XWCF @GET ("/telematics/v3/weather?output=json") observable<weatherresponse> 
Getweatherinfo (@Query ("location") string location, @Query ("AK") string AK); 

 }

As mentioned above, we use the retrofit framework to get weather data through the Baidu API, which automatically returns observable objects.
So how do we get a list of cities in a local file through Rxjava? (I put the city list in a file as a JSON string for ease of demonstration)

@Override public void Getplacedata () {placerepository repository = new Placerepository (); Repository.getplacelist (Baseapplication.getinstance ()). Subscribeon (Schedulers.io ()). Observeon (AndroidSched Ulers.mainthread ()). Subscribe (New subscriber<list<place>> () {@Override public void 
        OnNext (list<place> places) {Mmainview.setupplacedata (places); @Override public void oncompleted () {} @Override public void OnError (Throwable e) 
{ 
 
        } 
      }); 
    public class Placerepository {public observable<list<place>> getplacelist (final context) { Return Observable.create (New observable.onsubscribe<list<place>> () {@Override public void C All (subscriber<? Super list<place>> Subscriber) {try {Assetmanager Assertmanager = Conte 
          Xt.getassets (); InputStreamInputStream = Assertmanager.open ("place"); 
          Bytearrayoutputstream OutStream = new Bytearrayoutputstream (); 
          byte[] data = new byte[1024]; 
          int count =-1; 
          while (count = Inputstream.read (data,0, 1024))!=-1) {outstream.write (data, 0, count); 
          String json = new String (Outstream.tobytearray (), "UTF-8"); 
          Gson Gson = new Gsonbuilder (). Create (); 
          list<place> placelist = Gson.fromjson (JSON, new typetoken<list<place>> () {}.gettype ()); 
        Subscriber.onnext (placelist); 
        catch (Exception e) {subscriber.onerror (e); 
      } subscriber.oncompleted (); 
  } 
    }); 

 } 
}

Through the above code, we can complete the function of the interface, is not omitted handler callback,new Thread () These operations, which is why Rxjava is used to solve callback hell.

"In the activity, respectively, to get the weather data and the city list method, then the question is, if the data show the process Dialog, when should I end it, write flag judgment?" “

The most direct and most violent method is to call two interfaces directly in a single method, how do you use Rxjava to implement it?

This problem can be implemented using the Rxjava merge operator, so the name incredible is the two interface observable synthesized one, nonsense does not say directly on the code:

@Override public void Getplaceandweatherdata (String place) {mmainview.showprogress (); 
  Placerepository repository = new Placerepository (); 
  Context context = baseapplication.getinstance (); 
  Observable placeobservable = repository.getplacelist (context); Observable weatherobservable = Servicemanager.getinstance (). Getapiservice (). Getweatherinfo (Place, Constants.BAIDU_ 
  AK); Observable.merge (placeobservable, weatherobservable). Subscribeon (Schedulers.io ()). Observeon (AndroidSchedul  Ers.mainthread ()). Subscribe (New subscriber<object> () {@Override public void oncompleted () 
        {mmainview.hideprogress (); 
          @Override public void OnError (Throwable e) {mlogger.error (E.getmessage (), E); 
        Mmainview.hideprogress (); @Override public void OnNext (Object obj) {if (obj instanceof List) {MMAINV Iew.setupplacedata ((list<place>) obj); 
          else if (obj instanceof weatherresponse) {mmainview.setupweatherdata (weatherresponse) obj); 
} 
        } 
      }); 

 }


In this way, it is very ingenious to solve the problem of how to show the process Dialog when the data is taken, when to end and how to write flag judgment.

If the code looks uncomfortable, you can use a lambda to make the code look very small, but Android studio doesn't currently support lambda, and if you want to use it, install the plugin Retrolambda and the JDK uses JDK version 8.

GitHub Source Address: https://github.com/mickyliu945/CommonProj

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.