Easy Android App

Source: Internet
Author: User

Introduction

Now to share the end of the work of the Android--Life encyclopedia.
This project is just a big job, do not consider the actual needs, so there are unreasonable design places, please forgive me.
This project has three major functions (because it is the use of the sidebar so it can continue to add functionality inside), the first word query , followed by the weather query , and then the machine chat function. The word query is a free API that uses the scallops word , the weather query is a weather API that uses aggregated data , which requires registration (limited free use), and machine chat is an API that uses the Turing device . So, to summarize, my main work here is not much, mainly to call the API and then perform data analysis and display work.
The IDE used this time is idea (Android studio).
  
  The end of the article will give the source code, but some API interface needs to apply for key

The learning phase before the start of the project
Android Basic Primer http://www.runoob.com/android/android-tutorial.html
Android Provincial Linkage (weather location selection) http://blog.csdn.net/qq_20521573/article/details/51914180
The use of Android fragment http://www.jikexueyuan.com/course/708.html
The HTML source of the machine chat interface http://www.lanrenzhijia.com/js/3930.html
These are the steps I have taken to get started on the project, and I hope it helps

1. Project Preparation Phase 1.1. New Project

Choose the SDK version (Android 4.0), select navigation Drawer activity template, and complete the project creation using the Android Studio (IDEA) new Android project. After the project is built, we will get our basic interface template. Then, just delete the right side and the bottom of the element to get the interface shown

Of course, the use of Android ADT here is also possible, but it seems that the new template is not the same, more ugly (their own Android UI is not very good), so the use of Android Studio.

1.2. Add Dependencies

Because of the need to use the function of the provincial and municipal linkage, so you need to add external dependencies, in the above-mentioned links are detailed, so you need to add in the app folder build.gradle inside dependencies
  

    compile ‘com.contrarywind:Android-PickerView:3.2.5‘//自定义控件    compile ‘com.google.code.gson:gson:2.7‘//解析JSON

When you're done with your preparations, you get to the subject.

2. Word Search function

  Consider the length of the article, so some detailed procedures may be omitted (such as interface modification work, etc.).

When we enter the word and click on the query is required to access the network, the use of asynchronous task mechanism to access the network and to obtain results, some of the code is as follows:
  

//这是继承OnQueryTextListener 的内部类,用于处理搜索框监听事件public class SearchViewClickListener implements SearchView.OnQueryTextListener {        @Override        public boolean onQueryTextSubmit(String s) {            if (!lastSearchResult.equals(s)){//判断上一个结果和目前查询的是否相同                System.out.println("上个结果:"+lastSearchResult);                SearchWordTask task = new SearchWordTask();//新建查询任务                task.execute("https://api.shanbay.com/bdc/search/?word="+s);//访问网络的地址                searchResult.setVisibility(View.VISIBLE);//设置查询结果的TextView可见            }            lastSearchResult = s;//更新最后查询结果            System.out.println("最新结果:"+s);            return true;        }        @Override        public boolean onQueryTextChange(String s) {            return true;        }    }

After accessing the network and then passing back the data I have extracted this feature into a tool class with the following code:

public class Httputil {/** * Gets the data returned after accessing the network * @param urlstring URL * @return String */public static            String Getjsonresult (String urlstring) {try {URL url = new URL (urlstring);            HttpURLConnection conn = (httpurlconnection) url.openconnection ();            Conn.setrequestmethod ("GET");            Conn.setrequestproperty ("Accept", "*/*");            Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent", "mozilla/5.0" (Windows NT 6.1; Win64;            x64) applewebkit/537.36 (khtml, like Gecko) chrome/63.0.3239.84 safari/537.36 ");            InputStream is = Conn.getinputstream ();            byte[] buff = new byte[1024];            int hasread;            StringBuilder result = new StringBuilder ("");            while ((Hasread = Is.read (buff)) > 0) {result.append (new String (buff, 0, hasread));        } return result.tostring ();            } catch (IOException e) {E.printstacktrace ();    } return null; }}

In the above Searchwordtask is an internal class that inherits Asynctask , mainly to achieve access to the English Word query API provided by scallops, some of the code is as follows:

Class Searchwordtask extends Asynctask<string, Void, string> {@Override protected String doin Background (String ... arg0) {//arg0 is the variable parameter passed into the Execute function of Asynctask//here Arg0[0] is "https://api.shanbay.co        M/bdc/search/?word= "+s return Httputil.getjsonresult (Arg0[0]);            } @Override protected void OnPostExecute (String result) {Super.onpostexecute (result); if (result = = NULL | | "". Equals (Result) {Toast.maketext (getactivity), "Query Error!            ", Toast.length_long). Show ();        }else Fillresultforjson (Result);             /** * Parse the results of the query * @param JSON JSON data */private void Fillresultforjson (String JSON) {                try {Jsonobject object = new Jsonobject (JSON); if ("SUCCESS". Equals (Object.getstring ("MSG"))) {final Jsonobject dataObject = object.getjsonobject ("Dat                    A "); ParapHrase.settext ("Basic Interpretation:" +dataobject.getstring ("definition"));                    Final String Uk_audio = dataobject.getstring ("Uk_audio");                    Final String Us_audio = dataobject.getstring ("Us_audio"); Detail.setonclicklistener (New View.onclicklistener () {//If the detailed Interpretation button is clicked then the following page is accessed Override public void OnClick (view view) {webview.setvisibility (View.vis                            ible);                            Webview.loadurl ("https://www.shanbay.com/bdc/mobile/preview/word?word=" +lastsearchresult);                        Webview.setwebviewclient (New Webviewclient ());                    }                    }); The following is the listener event Ukbutton.setonclicklistener when the pronunciation button is clicked (New View.onclicklistener () {@Ove                                Rride public void OnClick (view view) {try { Using UkmediAplayer Play sound Ukmediaplayer = new MediaPlayer ();                                Ukmediaplayer.setaudiostreamtype (Audiomanager.stream_music);                                Ukmediaplayer.setdatasource (Uk_audio); Ukmediaplayer.prepare ();                            This process may take some time, such as reading Ukmediaplayer.start () on the web stream;                            } catch (IOException e) {e.printstacktrace ();                    }                        }                    }); Usbutton.setonclicklistener (New View.onclicklistener () {@Override public vo                    ID OnClick (view view) {//play sound step with above ...});                    Jsonobject pronunciations =dataobject.getjsonobject ("pronunciations");       Ukpronunciation.settext ("English pronunciation: [" +pronunciations.getstring ("UK") + "]");             Uspronunciation.settext ("American pronunciation: [" +pronunciations.getstring ("us") + "]");            }} catch (Jsonexception e) {e.printstacktrace (); }        }    }

The above is the main function of the word query, of course, consider the length of the article can not be analyzed.

3. Weather query function

In the weather query function is more important is the use of the user wrote the provincial and municipal linkage function, please refer to the above link in the article. I will not deal with this in the following, the main point here is to access the aggregated data provided by the API, the effect of this function, such as:
  
  
In the above function of the business code is mainly similar to the above word query, are using an asynchronous query, implemented by the inner class, the code is as follows:
  

 Class Weathertask extends Asynctask<string, Void, string> {@Override protected String Doinbackground (String ... arg0)            {try {return Httputil.getjsonresult (Arg0[0] + urlencoder.encode (arg0[1], "UTF-8"));            } catch (Unsupportedencodingexception e) {e.printstacktrace ();        } return null;            } @Override protected void OnPostExecute (String result) {Super.onpostexecute (result);            if (result! = null) {Parseweatherjson (result); }}/** * Parse based on JSON data * @param result JSON */private void Parseweatherjson (St                Ring result) {try {Jsonobject object = new Jsonobject (result);                    if (Object.getint ("error_code") = = 0) {Jsonobject resultobj = object.getjsonobject ("result");     Jsonobject todayobj = Resultobj.getjsonobject ("Today");               String Weatherresult = "Temperature:" +todayobj.getstring ("Temperature") + "\ n";                    Weatherresult + = "Weather conditions:" +todayobj.getstring ("weather") + "\ n";                    Weatherresult + = "Winds:" +todayobj.getstring ("Wind") + "\ n";                    Weatherresult + + "dressing advice:" +todayobj.getstring ("Dressing_advice");                Todayweather.settext (Weatherresult); }else {todayweather.settext ("Request Error!                ");            }} catch (Jsonexception e) {e.printstacktrace (); }        }    }
4. Machine Chat function

The machine chat function uses the HTML page to carry on the human-computer interaction, therefore, here basically does not involve the Java above question, mainly is loads the HTML page and opens the JavaScript function, the code is as follows:

WebView webView = (WebView) rootView.findViewById(R.id.chat_robot);//加载本地的HTML页面(将文件置于src/main/assets/)       webView.loadUrl("file:///android_asset/chat_robot.html");webView.getSettings().setJavaScriptEnabled(true);webView.setWebChromeClient(new WebChromeClient());

The effect of function implementation
  
Of course, if you use the above chat function need to register the Turing device person to apply for key, the source code will not provide key, so please register yourself.
When receiving the data returned by the Turing man, it will have code to determine what type is returned, so we need to determine the type to parse accordingly (the JS code here is not posted).

5. Summary

This is an Android final work, but not very serious look, and the project is not perfect, for example, after querying the word to do other functions of the operation again return the word query function before the data can not be saved, the user experience is not good. Here of course I also know some solutions to save the current fragment state, but I still lazy. Laziness is really an old enemy.
There is not enough detail on the article, but the main code has been written. I know, sometimes solving a function is not the function itself, but to prevent the feature comes out of the bug, of course, this is my experience.
There is the possibility that I am the object-oriented or understanding of the deviation, for the abstract or do very bad, and then want to look at other people's source code to improve the problem.
  

Project Source has uploaded GitHub and csdn resources, if the resources of a lot of friends use csdn download it. After the download needs to register the corresponding key after filling in, otherwise cannot use, registered address in the introduction has given

Easy Android App

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.