The implementation of Android intelligent question and answer robot

Source: Internet
Author: User
Tags dateformat sendmsg

Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/38498353, this article from: "Zhang Hongyang's Blog"

Today saw an iOS written by the Turing of the person, directly to the official website (http://www.tuling123.com/openapi/) See the next API access, too simple, just a GET request ~ So. Wrote a Android version number of the robot, there is no technical content, but quite fun ~ just last night to see their favorite Qin Moon. Hey, little Pixiu, that's my robot pet.

1.

First Look at:


Of course it's not just small talk, it's more powerful. See:


OK, let's do it first, and be interested in studying it yourself. Also support self-initiative to learn OH ~

Here's the start code ~

2. layout file

The display of the main interface message is a ListView, only the item in this ListView has two styles. One is the green message on the left, one is the white message on the right.

Message layout file on the left:

<?xml version= "1.0" encoding= "Utf-8"?

><linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_ Parent "android:layout_height=" wrap_content "android:orientation=" vertical "> <textview android:id=" @+id/chat_from_createdate "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "a ndroid:text= "2012-09-01 18:30:20" style= "@style/chat_date_style"/> <linearlayout android:lay Out_width= "Fill_parent" android:layout_height= "wrap_content" android:orientation= "Horizontal" > &L T LinearLayout android:layout_width= "wrap_content" android:layout_height= "Wrap_content" and roid:layout_marginleft= "10DP" android:orientation= "vertical" > <imageview Andro Id:id= "@+id/chat_from_icon" android:layout_width= "49DP" android:layout_height= "49DP" android:src= "@drawable/icOn "/> <textview android:id=" @+id/chat_from_name "android:layout_width=" Wra P_content "android:layout_height=" wrap_content "android:layout_gravity=" center " android:text= "Small Xiu ghpd Xiu ghpd" android:textsize= "18sp"/> </LinearLayout> <textvie W android:id= "@+id/chat_from_content" android:layout_width= "Wrap_content" android:layout _height= "Wrap_content" android:minheight= "50DP" android:background= "@drawable/chat_from_msg" Android:text= "Is it big?

"Android:textsize=" 18sp "android:textcolor=" #000 "android:gravity=" center_vertical " Android:focusable= "true" android:clickable= "true" android:linespacingextra= "2DP"/ > </LinearLayout></LinearLayout>


The right side and the left are basically the same, not affixed. Finally, the code is given.

Main layout file:

<?

XML version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:background=" @drawable/C Hat_bg_default "android:orientation=" vertical "> <relativelayout android:id=" @+id/ly_chat_title " Android:layout_width= "Fill_parent" android:layout_height= "45DP" android:background= "@drawable/title_bar" &G T <textview android:layout_width= "fill_parent" android:layout_height= "Fill_parent" Andro id:gravity= "center" android:text= "small Pixiu" android:textcolor= "#fff" android:textsize= "20SP" android:textstyle= "Bold"/> </RelativeLayout> <relativelayout android:id= "@+id/ly_chat_ Bottom "android:layout_width=" fill_parent "android:layout_height=" 55DP "Android:layout_alignparentbot Tom= "true" Android:background= "@drawable/bottom_bar" > <button android:id= "@+id/id_chat_send" android:layout _width= "60DP" android:layout_height= "40DP" android:layout_alignparentright= "true" Android : Layout_centervertical= "true" android:layout_marginright= "10DP" android:background= "@drawable/chat_s End_btn "android:onclick=" SendMessage "android:text=" send "/> <edittext androi D:id= "@+id/id_chat_msg" android:layout_width= "fill_parent" android:layout_height= "40DP" a Ndroid:layout_centervertical= "true" android:layout_marginleft= "10DP" android:layout_marginright= "10d P "android:layout_toleftof=" @id/id_chat_send "android:background=" @drawable/login_edit_normal " Android:singleline= "true" android:textsize= "18sp"/> </RelativeLayout> <listview Android:id= "@+id/id_chaT_listview "android:layout_width=" fill_parent "android:layout_height=" Fill_parent "Android:layout_abo Ve= "@id/ly_chat_bottom" android:layout_below= "@id/ly_chat_title" android:cachecolorhint= "#0000" Andro Id:divider= "@null" android:dividerheight= "5DP" android:scrollbarstyle= "Outsideoverlay" > </listview ></RelativeLayout>

is the ListView and the following message box and message button.

3, Httputils

Encapsulates a tool class for the Access API, in fact a GET request:

Package Com.zhy.utils;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import java.io.InputStream; Import Java.io.unsupportedencodingexception;import Java.net.httpurlconnection;import Java.net.URL;import Java.net.urlencoder;import Java.util.date;import Com.example.android_robot_01.bean. Chatmessage;import Com.example.android_robot_01.bean. Chatmessage.type;import Com.example.android_robot_01.bean.commonexception;import Com.example.android_robot_01.bean. Result;import Com.google.gson.gson;public class Httputils{private static String Api_key = " 534dc342ad15885dffc10d7b5f813451 ";p rivate static String URL =" Http://www.tuling123.com/openapi/api ";/** * sends a message. And get the message returned * @param msg * @return */public static chatmessage sendmsg (String msg) {chatmessage message = new Chatmessage (); String url = setparams (msg); String res = doget (URL); Gson Gson = new Gson (); result = Gson.fromjson (res, result.class); if (Result.getcode () > 400000 | | result.gettext () = = null| | result.get Text (). trIm (). Equals ("")) {message.setmsg ("The feature waits for development ...");} Else{message.setmsg (Result.gettext ());} Message.settype (Type.input); Message.setdate (new Date ()); return message;} /** * Stitching URL * @param msg * @return */private static string SetParams (String msg) {try{msg = Urlencoder.encode (msg, "UTF-8") ;} catch (Unsupportedencodingexception e) {e.printstacktrace ();} return URL + "? key=" + Api_key + "&info=" + msg;} /** * GET request. Get Return Data * @param urlstr * @return */private static string doget (String urlstr) {URL url = null; HttpURLConnection conn = Null;inputstream is = null; Bytearrayoutputstream BAOs = null;try{url = new URL (urlstr); conn = (httpurlconnection) url.openconnection (); Conn.setreadtimeout (5 *), Conn.setconnecttimeout (5 *), Conn.setrequestmethod ("GET");  Conn.getresponsecode () = = () {is = Conn.getinputstream (); BAOs = new Bytearrayoutputstream (); int len = -1;byte[] buf = new Byte[128];while (len = Is.read (BUF))! =-1) {baos.write (buf, 0, Len);} Baos.flush (); return baos.tostring ();} Else{throw NEW commonexception ("Server connection Error! 

");}} catch (Exception e) {e.printstacktrace (); throw new Commonexception ("Server connection Error! ");} Finally{try{if (is! = null) Is.close ();} catch (IOException e) {e.printstacktrace ();} Try{if (BAOs! = null) Baos.close ();} catch (IOException e) {e.printstacktrace ();} Conn.disconnect ();}}}


Exposed, is sendmsg this static method. Of course, the returned data is also encapsulated directly into the Chatmessage

4, Chatmessage

package com.example.android_robot_01.bean;import Java.text.dateformat;import Java.text.simpledateformat;import Java.util.date;public class chatmessage{/** * Message type */private type type;/** * message Content */pri Vate string msg;/** * Date */private Date date;/** * Date strings format */private string datestr;/** * Sender */private string name;publi c enum Type{input, Output}public chatmessage () {}public chatmessage (type type, String msg) {super (); this.type = Type; This.msg = msg;setdate (New Date ());} Public String Getdatestr () {return datestr;} Public Date getDate () {return date;} public void SetDate (date date) {this.date = Date;dateformat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); this.datestr = Df.format (date);} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public type GetType () {return type;} public void SetType (type type) {This.type = type;} Public String getmsg () {return msg;} public void Setmsg (String msg) {this.msg = msg;}} 
It's not even a spill. Very easy~

5. Main activity

Package Com.example.android_robot_01;import Java.util.arraylist;import Java.util.date;import java.util.List;import Android.app.activity;import Android.content.context;import Android.os.bundle;import Android.os.Handler;import Android.os.message;import Android.text.textutils;import Android.view.view;import Android.view.Window;import Android.view.inputmethod.inputmethodmanager;import Android.widget.edittext;import Android.widget.ListView;import Android.widget.toast;import Com.example.android_robot_01.bean. Chatmessage;import Com.example.android_robot_01.bean. Chatmessage.type;import Com.zhy.utils.httputils;public class Mainactivity extends activity{/** * Display a ListView of messages */ Private ListView mchatview;/** * Text field */private EditText mmsg;/** * Store Chat message */private list<chatmessage> mdatas = new A Rraylist<chatmessage> ();/** * Adapter */private chatmessageadapter madapter;private Handler mhandler = new Handler () { public void Handlemessage (Android.os.Message msg) {Chatmessage from = (chatmessage) msG.obj;mdatas.add (from); madapter.notifydatasetchanged (); Mchatview.setselection (Mdatas.size ()-1);};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (r.layout.main_chatting); InitView (); mAdapter = new Chatmessageadapter (this, mdatas); Mchatview.setadapter (Madapter);} private void Initview () {Mchatview = (ListView) Findviewbyid (r.id.id_chat_listview); mmsg = (EditText) Findviewbyid ( R.ID.ID_CHAT_MSG) Mdatas.add (new Chatmessage (type.input), "I am a small xiu ghpd Xiu ghpd." Very pleased to serve you "));} public void SendMessage (view view) {final String msg = Mmsg.gettext (). toString (); if (Textutils.isempty (msg)) { Toast.maketext (This, "you haven't filled in information yet ...", Toast.length_short). Show (); return;} Chatmessage to = new Chatmessage (Type.output, msg); To.setdate (new Date ()); Mdatas.add (to); Madapter.notifydatasetchanged (); Mchatview.setselection (Mdatas.size ()-1); Mmsg.settext ("");// Off soft keyboard Inputmethodmanager IMM = (inputmethodmanager) getsystemservice (ContexT.input_method_service)///Get Inputmethodmanager instance if (Imm.isactive ()) {//Suppose to turn on imm.togglesoftinput ( Inputmethodmanager.show_implicit,inputmethodmanager.hide_not_always);//Turn off the soft keyboard. Open method again, this method is to toggle the on and off state of the}new Thread () {public void run () {Chatmessage from = Null;try{from = Httputils.sendmsg (msg);} catch (Exception e) {from = new Chatmessage (type.input, "server hangs ..."); Message message = Message.obtain (); message.obj = from;mhandler.sendmessage (message);};}. Start ();}}

Sets the data for the ListView. Set the first sentence at the beginning "I am the little Xiu ghpd Xiu ghpd." Very happy to serve you. " There is also the Sendbutton event handling.

6. Adapter

Package Com.example.android_robot_01;import Java.util.list;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.textview;import Com.example.android_robot_01.bean. Chatmessage;import Com.example.android_robot_01.bean. Chatmessage.type;public class Chatmessageadapter extends Baseadapter{private layoutinflater minflater;private List <ChatMessage> Mdatas;public Chatmessageadapter (context context, list<chatmessage> datas) {minflater = Layoutinflater.from (context); mdatas = Datas;} @Overridepublic int GetCount () {return mdatas.size ();} @Overridepublic Object getItem (int position) {return mdatas.get (position);} @Overridepublic long Getitemid (int position) {return position;} /** * Accept message 1, send message 0 */@Overridepublic int getitemviewtype (int position) {Chatmessage msg = mdatas.get (position); return Msg.gettype () = = Type.input?

1:0;} @Overridepublic int Getviewtypecount () {return 2;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Chatmessage chatmessage = Mdatas.get ( position); Viewholder Viewholder = null;if (Convertview = = null) {Viewholder = new Viewholder (); if (chatmessage.gettype () = = Type.INPU T) {Convertview = Minflater.inflate (r.layout.main_chat_from_msg,parent, false); viewholder.createdate = (TextView) Convertview.findviewbyid (r.id.chat_from_createdate); viewholder.content = (TextView) Convertview.findviewbyid ( r.id.chat_from_content); Convertview.settag (Viewholder);} Else{convertview = Minflater.inflate (r.layout.main_chat_send_msg,null); viewholder.createdate = (TextView) Convertview.findviewbyid (r.id.chat_send_createdate); viewholder.content = (TextView) Convertview.findviewbyid ( r.id.chat_send_content); Convertview.settag (Viewholder);}} Else{viewholder = (Viewholder) Convertview.gettag ();} ViewHolder.content.setText (Chatmessage.getmsg ()); ViewHolder.createDate.setText (chatmessage. GETDATESTR ()); return Convertview;} Private class Viewholder{public TextView createdate;public TextView name;public TextView content;}}


The only thing to note is that since our ListView item has two display styles, we need to rewrite two more methods than usual:

/** * received message for 1. Send Message 0 */@Overridepublic int getitemviewtype (int position) {Chatmessage msg = mdatas.get (position); return Msg.gettype () = = Type.input? 1:0;} @Overridepublic int Getviewtypecount () {return 2;}

The Getviewtypecount returns the number of species, and getitemviewtype the position of the item of course returns different integer variables. Then in GetView, you can load different item layouts depending on the type of message.


is basically finished, no technical content, purely entertainment. Everybody programmer brother, nothing can take a moment to write down play a play ~ work under Rest ~


Source code click to download






The implementation of Android intelligent question and answer 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.