Teach you to do Android chat robot

Source: Internet
Author: User

I believe you should know that there is a application called the small yellow chicken!

If you don't know, have you ever seen a chat app that can reply in seconds?

If you still don't see it! So you've always seen a quick response to your public account!

If still .... Turn left on a pro-go


Well, don't say much.

First of all, we should understand the procedure, the procedure is set up by artificial setting up a system,

The robot here is also, the simple principle is that when you enter the keyword, through a set of algorithms,

Find the most matching content in the database and return it to you. This has already been achieved, this tutorial we use others

Have achieved good things to do one?? App to play ~ ~

(Of course if you want to know how to do it, give me a message.) Look at the situation I will be a tutorial to make people how to do this back end of the robot)


First we need to design the program.

Classes that need to be used

Beans

-------Chatmessage.java (The class you created is designed to encapsulate the information in an object when it is accepted and sent)

-------Result.java (Return information class to be used when receiving information)

Until

-------Aiaiuntil.java (The type you create, the tool used to send information and get returned information)


------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- -- ----- ------- ------- ------- -------

Charmessageadapter.java (because it is a chat form application, so the layout needs to be dynamic, the layout referenced here adapter need to inherit Baseadapter)

Mainactivity.java (Program entry, total presentation layer of the program)


The above is the use of all classes, very little.

Why so little, because we borrowed the robot backstage-Turing robot that someone else had written?

You can open the connection and simply see how the API is used.

Request method

API Address: Http://www.tuling123.com/openapi/api

Request method: HTTP GET

Data format: JSON


The data returned are JSON. and whether or not the return succeeds returns a code to determine whether the return succeeds


Here we write the code, first of all the objects that encapsulate the information.

chatmessage. Java's

Packaging com.www.xiaoaiai.com.bean; import java.util.Date; public class Chatmessage {private string name; private strings msg; private type type; private time date; public chatmessage () {} Public Chatmessage (String music msg, type type, date) {this.msg = msg; this.type = type; this.date = date;} Defines the enumeration definition type//enumeration is used to differentiate the data type Public enumeration type {incoming, outcoming} public string GetName () {returned name;} Public invalid SetName (string name) {this.name = name;} public string getmsg () {return msg;} Public invalid setmsg (String music msg) {this.msg = msg;} GetType () {return type of the public type;} Public invalid Settype (type type) {This.type = type;} Open Date getdate () {return date;} Public invalid setdate (date) {this.date = date;}}
The following is the information result class

Packaging com.www.xiaoaiai.com.bean;/* * *  @author Srain_zhou * In order to send a dialog object to the server requires a mapping object */public class Result {//Here Note the beginning of the letter group Good lowercase, Because the returned result key is the private explanatory code of the small Xie, the private string text; public explanatory reference code () {return code;} Public invalid Setcode (int code) {this.code = code;} GetText () {Returns text for the public string;} Public invalid SetText (string literal) {this.text = text;}}
The following is the core Exchange class, which can be understood as DAO

Aiaiuntil.java

Com.www.xiaoaiai.com.until, import java.io.ByteArrayOutputStream, import java.io.IOException, import Java.io.InputStream; Import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; Import java.net.URLEncoder; import java.util.Date; import Com.google.gson.Gson; import com.www.xiaoaiai.com.bean.ChatMessage; Import com.www.xiaoaiai.com.bean.ChatMessage.Type; import com.www.xiaoaiai.com.bean.Result; public class Aiaiuntil {// Connect the Turing man's interface private static last string url = "Htt??p://www.tuling123.com/openapi/api";//own Apikey private static last string api_key = "The thrill of the development of a app_key experience to apply yourself!" ";///Send a message to get the message returned public static Chatmessage SendMessage (String music msg) {//Create an Encapsulated information object chatmessage chatmessage = new Chatmessage ();// Here's a look at the Doget method string jsonres = Doget (MSG);//Gson is a jar package provided by Google for the main purpose of serializing a Java object as a JSON string, or deserializing a JSON string into a Java object. Serialization is for network transmission Gson Gson = new Gson (); result = NULL; try {//In order to get the return string result = Gson.fromjson (Jsonres,result.class); Chatmessage.setmsg (Result.gettext ());} catch (Exception five) {chatmessage.setmsg ("server Busy");} Chatmessage.setdate (new Date ()); Chatmessage.settype (type.incoming); return chatmessage;} Doget of public static strings (String music msg{String result = "";//splicing URL Here you need to learn more about Turing's request way string url = Setrarams (MSG);//input stream inputstream = null;// Bytearrayoutputstream This class implements an output stream where the data is written to a byte array. Bytearrayoutputstream BAOs = null;//Build the object that sent the request try {Java.net.URL url_net = new Java.net.URL (URL); HttpURLConnection conn = (HttpURLConnection Class) Url_net.openconnection ()//Set read data timeout from host Conn.setreadtimeout (5 * 1000); /Set Connection host timeout Conn.setconnecttimeout (5 * 1000);//Set Connection mode Conn.setrequestmethod ("get");//Get Write stream = Conn.getinputstream ();// Set buffer Integer length = -1;//set buffer 128 byte [] of buf = new byte [128];//bar flow into string class BAOs = new Bytearrayoutputstream ();//judge whether to read it (length = is.? Read (BUF))! =-1) {Baos.write (buf,0, length);} Clears the buffer Baos.flush ();//Converts the stream to a string result = new String (Baos.tobytearray ());} catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace ();} catch (IOException exception e) {//TODO auto-generated catch block E.printstacktrace ();} finally {//release resource attempt {if (baos! = NULL) {baos.close ();}} catch (IOException exception e) {//TODO auto-generated catch block E.printstacktrace ();} try {if (yes! = NULL) {is.close ();}} catch (IOException exception e) {//TODO auto-generated catch block E.printstacktrace ();}} Returns the result;} method to build the request path publicCommon static string Setrarams (String music msg) {strings url_value = NULL; try {url_value = URL + + + api_key "with info =" + urlencoder.encode (MSG, "UTF-8") "key =?" ”;} catch (Unsupportedencodingexception E) {//TODO auto-generated catch block E.printstacktrace ();} return url_value;}}


Charmessageadapter.java content provider, inside about the dialog layout file you can follow your own like to design

A simple explanation. Where the dialog box is a ListView with two different sets of ListView (Red and Blue), please combine the following

Code to simulate the definition of their own dialog layout, I think my layout is ugly, so I do not post code. DIY It yourself ~ ~



com.www.xiaoaiai.com; import java.text.SimpleDateFormat; import java.util.List; import com.www.xiaoaiai.com.bean.ChatMessage; Import com.www.xiaoaiai.com.bean.ChatMessage.Type; import android.content.Context; import Android.view.LayoutInflater; Import Android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import Android.widget.TextView; public class Charmessageadapter Extended Baseadapter {/* * * For an interface that has not been loaded or wants to be loaded dynamically, it needs to be loaded using inflation. * The android??  OID inside want to create a picture, beginner is generally a new class, inherit the activity base class, * and then in the OnCreate inside the Setcontentview method used to load a defined interface in XML. * In fact, Layoutinflater is used in the activity to load the interface, * through the Getsystemservice (Context.layout_inflater_service) method can obtain a layoutinflater, * can also be blown by Layoutinflater = Getlayoutinflater (); * To obtain. Then use the inflatable method to load the layout of the XML, * in the actual development of layoutinflater this class is still very useful, its role is similar to Findviewbyid () * Different points is layoutinflater is used to find the layout of the XML layout file, * and instantiate! The Findviewbyid () is a specific widget control that is found under specific XML. *///For overloading the layout of objects, is the robot has helped us do a good job of class private Layoutinflater minflater;//chat Information data collection private list <ChatMessage> Mdatas; Public Charmessageadapter (Contextual context, List <ChatMessage> mdatas) {minflater = Layoutinflater.from (context); This.mdatas =Mdatas;} Inheriting baseadapter need to override the method to get the length of the data @ Overwrite public annotation GetCount will () {//TODO auto-Generate method Stub return Mdatas.size ();} Inheritance Baseadapter needs to override the method that gets the data in the project @ Overwrite the public object's getitem (int position) {//TODO auto-Generate method stub returns Mdatas.get (position);} Inheritance Baseadapter need to override the method, get itemid@ overlay getitemid (integer digits) {//Todo automatically generate method stub back to position;} /* * * Because this need to layout two times different positions so need to write two methods *///Getitemviewtype method tells the ListView which item is displayed in each row of the list @ Overwrite public annotation getitemviewtype (integer digit) {chatmessage Chatmessage = Mdatas.get (position), if (chatmessage.gettype () = = type.incoming) {returns 0;} return 1;} Getviewtypecount This method tells the ListView control how many kinds of items I have in the public annotation Getviewtypecount () {//TODO auto-Generate method stub returns 2;} /* * is a holder of the class, he generally has no method, * Only attributes, function is a temporary storage, * Put your GetView method in each return of the view saved, you can use the next time. * The advantage of this is that you do not have to go to the layout file every time to get your view, improve the efficiency. */Private Final class Viewholder {TextView mdate; The mmsg of TextView; }//below is how to dynamically layout the code @ Overwrite public view GetView (int position, view Convertview, Parent's ViewGroup) {chatmessage chatmessage = mdatas.get (location);// Above the usefulness, improve the page efficiency viewholder Viewholder = null, if (Convertview = = null) {//through the itemtype set a different layout if (getitemviewtype (position) = = 0) { Convertview = Minflater.inflate (R.layout.item_from_msg, parents, false); Viewholder= new Viewholder (); viewholder.mdate = (TextView) Convertview.findviewbyid (r.id.from_msg_date); viewholder.mmsg = (TextView) Convertview.findviewbyid (r.id.from_msg);} Other {Convertview = Minflater.inflate (R.layout.item_to_msg, parents, false); Viewholder = new Viewholder (); viewholder.mdate = (TextView) Convertview.findviewbyid (r.id.to_msg_date); viewholder.mmsg = (TextView) Convertview.findviewbyid (r.id.to_msg);} Use the Layoutinflater object to view the expanded label used//used to mark Convertview, if the Viewholder object has not to regenerate the object, in order to be efficient! Convertview.settag (Viewholder);} other {Viewholder = (Viewholder) Convertview.gettag ();} The following code slowly looks, very simple simpledateformat df = new SimpleDateFormat ("Yyyy-mm-dd HH:MM:SS"); Viewholder.mDate.setText (Df.format (Chatmessage.getdate ())); Viewholder.mMsg.setText (Chatmessage.getmsg ()); return Convertview;}}

Here is the main main mainactivity ~ ~

Package Com.www.xiaoaiai.com;import Java.util.arraylist;import Java.util.date;import java.util.list;import Com.www.xiaoaiai.com.bean.chatmessage;import Com.www.xiaoaiai.com.bean.chatmessage.type;import Com.www.xiaoaiai.com.until.aiaiuntil;import Android.support.v7.app.actionbaractivity;import Android.text.textutils;import Android.os.bundle;import Android.os.handler;import Android.os.Message;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.view.Window;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.listview;import Android.widget.toast;public class Mainactivity extends Actionbaractivity {// The outermost dialog layout private ListView mmsg;//Content provides object private Charmessageadapter madapter;//data collection Private list<chatmessage> Mdatas;//viewprivate EditText minputmsg;private Button msendmsg;//because you want to update the interface so use Handler mhandlerprivate Handler Mhandler =new Handler () {public void Handlemessage (android.os.MeSsage msg) {//wait for Ijieshou child thread Chatmessage cm= (chatmessage) msg.obj;mdatas.add (cm); madapter.notifydatasetchanged (); Mmsg.setselection (Mdatas.size ()-1);};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (r.layout.activity_main);//Initialize View Initview ();// Initialize the data initdatas ();//Initialize the monitor Initlistener ();} private void Initlistener () {Msendmsg.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) { Final String tomsg = Minputmsg.gettext (). toString (); if (Textutils.isempty (tomsg)) {Toast.maketext (Mainactivity.this, "Send message cannot be empty", Toast.length_short). Show (); return;} In order to do the effect of chatting chatmessage tomessage = new Chatmessage (); Tomessage.setdate (new Date ()); tomessage.setmsg (tomsg); Tomessage.settype (type.outcoming); Mdatas.add (tomessage); madapter.notifydatasetchanged (); MMsg.setSelection ( Mdatas.size ()-1); Minputmsg.settext (""); new Thread (New Runnable () {public void run () {// Network access cannot be used in the main thread should be chatmessage in the child thread Frommessage =aiaiuntil.sendmessage (tomsg); Message m =message.obtain (); m.obj=frommessage;//will receive Mhandler.sendmessage (m) in Handlemessage in handler after it is sent;}). Start ();}}); private void Initdatas () {Mdatas =new arraylist<chatmessage> (); Mdatas.add (New Chatmessage ("Hello, I'm little Ned", Type.incoming,new Date ())); madapter = new Charmessageadapter (This,mdatas); Mmsg.setadapter (Madapter);} private void Initview () {mmsg= (ListView) Findviewbyid (r.id.id_list_view_01); minputmsg= (EditText) Findviewbyid ( R.ID.INPUT_MSG); Msendmsg= (Button) Findviewbyid (r.id.id_send_msg);}}

Hope that everyone's study is helpful ~ ~ ~

Tips! ~~~

1 if you compile the R file does not appear, that is, R. Do not come out to indicate that your XML file is absolutely wrong

2 in this app, don't forget to add network access ~

In

In the androidmanifest.xml file

Add the following code

<uses-permission android:name= "Android.permission.INTERNET"/> loading application tags outside




Teach you to do Android chat robot

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.