Practiced hand Small project (1)--Intelligent chat robot

Source: Internet
Author: User

I've always believed. Even if it's a simple app, he's also difficult, assuming you can do it with a complex app. This is certainly not a solid foundation for you, I always ask people around me. Why learn Android Forget, always learn bad. There are some things to remember, in fact, it's not your fault. Assuming that someone else has developed something so long, you learn all of a sudden how you make Google Live.


Limited space. If the reader does not understand the words, can review the basis.  I tried to simplify the code. Look first.

Let's say you're a beginner Android. This app may take you half an hour

Let's say you're an experienced developer, OK, and you'll probably be able to take your development class to the next 10 minutes.


watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvsmfja19law5nmda3/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center "align=" Middle ">


Development steps:

1. First go to the Turing Man register key

http://www.tuling123.com/

2. Get ready for networking and put the networking tool class into

PS: Here is my own networking tool class. Suppose like to be able to collect

3. Prepare JSON parsing

JSON parsing is not complicated, so it only uses the self-made JSON to parse the

4.UI Preparation


5. Business logic Preparation




First of all, you go to the Turing device People's official website application key This is not complicated, because can QQ login assumptions do not want to apply that you use my Bai


Key = 349baa5d2bd5d2d7612e4f2c1fcd973d


Second Step networking get JSON


In fact this request data. There's no difference, look at his request demo sample

Private String url= "Http://www.tuling123.com/openapi/api?"

Key=349baa5d2bd5d2d7612e4f2c1fcd973d&info= ";


Add your input information to the back of the

Networking: 1. Httpclient 2. Httpconnection 3.Xutils 4. Various tool classes.


A developer. With the development of things coming more and more. There are more and more tools to accumulate. In this little demo you can use your own tool class

My networking tools class, is my own package you can add threads in their own, with the Httpconnection network, and then the IO operation into a string through the interface put back string type.


Package Com.example.aicomputer;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.URL; Import Java.net.urlconnection;import Java.nio.byteorder;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import android.os.handler;/** * Encapsulated Network + thread */public class Httputils {//Use line pool to download pictures. Same moment. A maximum of 3 threads are executing private static executorservice Execuotrs = Executors.newfixedthreadpool (3); interface onbitmapnetworkresponse {public void ok (Bitmap Bitmap);p ublic void error (String error);} public static void Requestbitmapnetwork (final String path,final onbitmapnetworkresponse response) {final Handler Handler = new Handler (); Execuotrs.execute (new Runnable () {@Overridepublic void Run () {Boolean isnetworkok = false;try {URL url = n EW URL (PATH); HttpURLConnection OpenConnection = (httpurlconnectiON) url.openconnection (); Openconnection.setconnecttimeout (Openconnection.connect); Openconnection.getresponsecode () = = () {InputStream InputStream = Openconnection.getinputstream (); final Bitmap Bitmap = Bitmapfactory.decodestream (InputStream); Handler.post (new Runnable () {@Overridepublic void run () {Response.ok (bitmap);}}); Inputstream.close (); isnetworkok = True;}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally {if (! Isnetworkok) {handler.post (new Runnable () {@Overridepublic void run () {response.error ("Server is not in the service area!

");}});}}}});} Public interface Onnetworkresponse {public void ok (string response);p ublic void Error (string error); public static void Requestnetwork (final String path,final onnetworkresponse response) {//instantiation Handler final Handler Hanlder = new Handler (); new Thread () {public void run () {//Flag bit Boolean Isworkok = False;inputstream InputStream = null; Bytearrayoutputstream OutStream = null;try {URL url = new URL (path); System.out.println ("=======path=========" +path); HttpURLConnection connection = (httpurlconnection) url.openconnection (); connection.setconnecttimeout (5000); Connection.setdoinput (True); Connection.connect (); if (connection.getresponsecode () = =) {InputStream = Connection.getinputstream (); outstream = new Bytearrayoutputstream (); byte[] B = new Byte[1024];int len = 0;while (len = in Putstream.read (b))! =-1) {outstream.write (b, 0, Len);} Outstream.flush (); final string result = new String (Outstream.tobytearray ()); Hanlder.post (new Runnable () {@ overridepublic void Run () {Response.ok (result);}); Isworkok = True;}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally {// Network operation problem if (!isworkok) {response.error ("Server Wander!

");} if (InputStream! = null) {try {inputstream.close ();} catch (IOException e) {e.printstacktrace ()}} if (OutStream! = null) {try {outstream.close ();} catch (IOException e) {e.printstacktrace ();}}};}. Start ();}}


Suppose for this section. I don't know, I can see my writing Network programming series

Learning from Java Network Programming (2)


The third step is JSON parsing

We added the weather in Shenzhen after the URL returned is

{"Code": 100000, "text": "Today cloudy 24~19°c tomorrow Yin 26~21°c after Yin 22~17°c"}

The outermost is a curly brace, so directly with Jsonobject, parsing can be

Jsonobject JB = new Jsonobject (response);

4.UI Preparation

In fact, the UI is not complicated. The outermost layer is a linear layout. There are two linear layouts, the first one with a listview-----> Display Chat Message The second one has a button to send a message, a edittext input message.

Layout file: Activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "vertical" > <listview android:id= "@+id/lv" android:layout_width= "Fill_parent" Androi d:layout_height= "0DP" android:layout_weight= "1" android:divider= "@null" android:listselector= "@androi D:color/transparent "android:transcriptmode=" Alwaysscroll "> </ListView> <linearlayout and        Roid:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:orientation= "Horizontal" > <edittext android:id= "@+id/sendtext" android:layout_width= "0DP" Android:layout_h eight= "Wrap_content" android:layout_weight= "1"/> <button android:id= "@+id/sen D_btn "Android:layout_width=" Wrap_coNtent "android:layout_height=" wrap_content "android:text=" Send "/> </linearlayout& Gt;</linearlayout>


Now that we've said the ListView, we'll know what we're talking about. To be shown above. We are going to infer from the adapter that the message is the one that was sent, which is the portion of the layout that was sent over. On the left is the robot's message layout to the right is the layout where we send the message

is not complicated, a relative layout has a textview display send time, a imageview display the robot's avatar a textview display message content


Layout of robot messages

<?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 "> <textview android:id=" @+id/time "Android:layout_w Idth= "Fill_parent" android:layout_height= "wrap_content" android:gravity= "Center_horizontal"/> <Ima Geview android:id= "@+id/iv" android:layout_width= "70DP" android:layout_height= "70DP" android:l ayout_below= "@id/time" android:padding= "10DP" android:src= "@drawable/robot"/> <textview and Roid:id= "@+id/tv" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:la yout_below= "@id/time" android:layout_marginright= "50DP" android:layout_torightof= "@id/iv" Android:bac kground= "@drawable/aio_friend_bg_nor_11" android:gravity= "center"/></relativelayout>


We send the content of the message

<?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 "> <textview android:id=" @+id/time "Android:layout_ Width= "Fill_parent" android:layout_height= "wrap_content" android:gravity= "Center_horizontal"/> <Im Ageview android:id= "@+id/iv" android:layout_width= "70DP" android:layout_height= "70DP" Android: Layout_alignparentright= "true" android:layout_below= "@id/time" android:padding= "10DP" android:src= "@d Rawable/xiaoxin "/> <textview android:id=" @+id/tv "android:layout_width=" Wrap_content "Andro id:layout_height= "Wrap_content" android:layout_below= "@id/time" android:layout_marginleft= "50DP" Android oid:layout_toleftof= "@id/iv" android:background= "@drawable/aio_user_bg_nor_11" android:gravity= "center"/> ; </relativelayout>



Unconsciously, went to the last step, I believe you will think, good simple ah. Yes very easy, because the hardest in the back

Business logic:

1.Edittext and instantiation of ListView and button

Handling of 2.button Click events

Gets the contents of the EditText input, Processes ———— > Removes the space and carriage return information.  Replace into empty. The data is then encapsulated in the entity class.

When it is greater than 30, empty it once and then refresh the adapter

Send the processed information to the server to get the reply information and then encapsulate the entity class as well. Refresh the adapter


3. Set the Welcome language every time you come in. In order to improve the user experience, we have a welcome language, first set up an array to install the Welcome language


Come to res/values/strings add array

   <string-array name= "Welcome_tips" >        <item> Master, the slave has been waiting here </item>        <item> Master. How        's everything going </item> <item> darling, I want to die you </item>        <item> Welcome back, my dear master </item>        < item> I am a small new robot, very happy to serve you </item>    </string-array>

And then in the Java code as a method

private String Getrandomwelcometips () {string welcome_tip = Null;welcome_array = This.getresources (). Getstringarray ( r.array.welcome_tips); int index = (int) (Math.random () * (welcome_array.length-1)); welcome_tip = Welcome_array[index]; return welcome_tip;}

should not be ugly. Get array contents by random

Chatting in the middle. should also increase the time

Private String GetTime () {currenttime = System.currenttimemillis (); SimpleDateFormat format = new SimpleDateFormat ("yyyy mm month DD Day HH:MM:SS");D ate curdate = new Date (); String str = Format.format (curdate), if (Currenttime-oldtime >=) {oldtime = Currenttime;return str;} else {return "";}}
That is to get the next system time, and then format the next

Java Code mainactivity

Package Com.example.aicomputer;import Java.text.simpledateformat;import Java.util.arraylist;import java.util.Date; Import Java.util.list;import Org.json.jsonexception;import Org.json.jsonobject;import Com.example.aicomputer.httputils.onnetworkresponse;import Android.app.activity;import Android.os.Bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.listview;public class Mainactivity extends Activity implements    onclicklistener{//input Box Private EditText sendtext;private Button send_btn;    Private ListView ListView; private string Content_str;private string[] welcome_array;private string url= "Http://www.tuling123.com/openapi/api?

key=349baa5d2bd5d2d7612e4f2c1fcd973d&info= ";p rivate double currenttime=0, oldtime = 0;private List<ListData > lists;private ListData listdata;private myadapter adapter; @Override protected void onCreate (Bundle savedinstancest ATE) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initview (); }private void Initview () {listview = (ListView) Findviewbyid (r.id.lv); sendtext = (EditText) Findviewbyid (R.id.sendtext) SEND_BTN = (Button) Findviewbyid (R.ID.SEND_BTN); lists = new arraylist<listdata> ();//click event Sent Send_ Btn.setonclicklistener (This): adapter = new Myadapter (lists, this); Listview.setadapter (adapter); listData = new ListData (Getrandomwelcometips (), Listdata.receiver,gettime ()); Lists.add (ListData);} private String Getrandomwelcometips () {string welcome_tip = Null;welcome_array = This.getresources (). Getstringarray ( r.array.welcome_tips); int index = (int) (Math.random () * (welcome_array.length-1)); Welcome_tip = Welcome_array[iNdex];return Welcome_tip;} /*1. Gets the contents of the EditText input, processes the ———— > removes the space and carriage return information, instead of empty.

* 2. Then encapsulate the data in the entity class. When the value is greater than 30, clear it once and then refresh the adapter */@Overridepublic void OnClick (View v) {getTime (); content_str = Sendtext.gettext (). ToString () ; Sendtext.settext (""); String DROPK = Content_str.replace ("", ""); String droph = dropk.replace ("\ n", ""), ListData = new ListData (Content_str, Listdata.send, GetTime ()); Lists.add ( ListData), if (Lists.size () >) {for (int i = 0; i < lists.size (); i++) {lists.remove (i);}} Adapter.notifydatasetchanged (); Httputils.requestnetwork (Url+droph, New Onnetworkresponse () {@Overridepublic void ok (String response) {try {Jsonobject JB = new Jsonobject (response),//System.out.println (jb.getstring ("Code"));//System.out.println (jb.getstring ("text" )); ListData listdata;listdata = new ListData (jb.getstring ("text"), Listdata.receiver,gettime ()); Lists.add (ListData); Adapter.notifydatasetchanged ();} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} @Overridepublic void error (String error) {//TODO auto-generated Method stub}}); Private STring GetTime () {currenttime = System.currenttimemillis (); SimpleDateFormat format = new SimpleDateFormat ("yyyy mm month DD Day HH:MM:SS");D ate curdate = new Date (); String str = Format.format (curdate), if (Currenttime-oldtime >=) {oldtime = Currenttime;return str;} else {return "";}}}

In fact, when there is no click. The welcome language has been shown through the adapter to the ListView, so we can put the following in the adapter instantiation, the entity class. The main role is to encapsulate the time and content of the transmission. Infer from the adapter to show

In fact, the most important thing is the contents of the adapter. What should I do with the message sent here:

We passed two value collections to the adapter. The collection of entity class data is filled with a context

Let's set up a relative layout first. To populate the contents of an entry we want a list loaded with entity classes, entity classes, and very much data, and we need to infer that part of the content through identifiers.

Package Com.example.aicomputer;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.relativelayout;import Android.widget.textview;public Class Myadapter extends Baseadapter{private list<listdata> lists;private Context mcontext;private RelativeLayout Layout;public myadapter (list<listdata> lists,context mcontext) {this.lists = Lists;this.mcontext = MContext;} @Overridepublic int GetCount () {return lists.size ();} @Overridepublic Object getItem (int position) {return lists.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Layoutinflater Inflater = Layoutinflater. From (Mcontext), if (Lists.get (position). Getflag () = = listdata.receiver) {layout = (relativelayout) inflater.inflate ( R.layout.leftitem, null);} if (Lists.get (position). Getflag () = = listdata.send) {layout = (relativelayout) inflater.inflate (R.layout.rightitem, null);} TextView TV = (TextView) Layout.findviewbyid (r.id.tv); TextView time = (TextView) Layout.findviewbyid (r.id.time); Tv.settext (Lists.get (position). GetContent ()); Time.settext (Lists.get (position). GetTime ()); return layout;}}




If you have any questions, you can leave a message on my blog.


Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Practiced hand Small project (1)--Intelligent 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.