Chatbots and chatbots

Source: Internet
Author: User

Chatbots and chatbots

I have always believed that even the simplest APP has its own difficulties. If you cannot make a complicated APP, you must have a solid foundation, people around me always ask me why I forgot about Android, but it is always hard to learn. I cannot remember some things. In fact, this cannot blame you. If someone else has developed things for so long, you just learned how to make Google live.


The length is limited. If you cannot understand it, you can review the basics and try to simplify the code. First look

If you are new to Android, it may take you half an hour to use this APP.

If you are an experienced developer, OK, you may be able to import your own development class after reading it again, and it will be done in less than 10 minutes.



Development steps:

1. register the KEY with the Turing bot first.

Http://www.tuling123.com/

2. Prepare the online operations and add the online tools

PS: Here is my own online tools. If you like it, you can add it to your favorites.

3. Prepare json Parsing

Json Parsing is not complex, so it only uses built-in json parsing.

4. UI preparation


5. business logic preparation




Step 1: Go to the Tuling robot official website to apply for the key. This is not complicated, because you can log on Via QQ. If you don't want to apply, use it.


Key = 349baa5d2bd5d2d7612e4f2c1fcd973d


Step 2 obtain json from the Internet


In fact, there is no difference in this request data. Let's look at his request example.

private String url="http://www.tuling123.com/openapi/api?key=349baa5d2bd5d2d7612e4f2c1fcd973d&info=";

Add your input information.

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


As developers develop more and more things and accumulate more and more tools, you can use your own tool classes in this small Demo.

My network tool class is self-encapsulated. You can add a thread in your own, use Httpconnection for networking, and convert it to String based on IO operations. Use the interface to return the 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. gra Phics. bitmapFactory; import android. OS. handler;/*** encapsulated Network + thread */public class HttpUtils {// use the thread pool to download images at the same time, A maximum of three threads are running private static ExecutorService execuotrs = Executors. newFixedThreadPool (3); interface OnBitmapNetWorkResponse {public void OK (Bitmap bitmap); public void error (String error);} public static void RequestBitmapNetWork (final String path, final OnBitmapNetWorkResponse response) {final Han Dler handler = new handler({{@ Overridepublic void run () {boolean isNetWorkOK = false; try {URL url = new URL (path ); httpURLConnection openConnection = (HttpURLConnection) url. openConnection (); openConnection. setConnectTimeout (5000); openConnection. connect (); if (openConnection. getResponseCode () == 200) {InputStream inputStream = openConnection. getInputStream (); final Bi Tmap 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 ("the server is not in the service zone! ") ;}}}}}});} Public interface OnNetWorkResponse {public void OK (String response); public void error (String error );} public static void RequestNetWork (final String path, final OnNetWorkResponse response) {// instantiate handler final Handler hanlder = new Handler (); new Thread () {public void run () {// flag boolean isWorkOK = false; InputStream inputStream = null; ByteArrayOutputStream outStream = null; try {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 () = 200) {inputStream = connection. getInputStream (); outStream = new ByteArrayOutputStream (); byte [] B = new byte [1024]; int len = 0; while (len = inputS Tream. 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 error if (! IsWorkOK) {response. error ("the server is distracted! ");} If (inputStream! = Null) {try {inputStream. close () ;}catch (IOException e) {e. printStackTrace () ;}} if (outStream! = Null) {try {outStream. close () ;}catch (IOException e) {e. printStackTrace () ;}};}. start ();}}

If you do not understand this section, you can refer to my network programming series.

From java Network Programming (2)


Step 3: json Parsing

The weather we add to Shenzhen after the url returns

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

The outermost layer is a braces. so can be parsed directly using JsonObject.

JSONObject jb = new JSONObject(response);

4. UI preparation

In fact, the ui is not complex. The outermost layer is a linear layout with two linear la s in it. The first one is listview -----> display chat information, the second one is a button that sends messages, and the other is Edittext input information.

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: orientation = "vertical"> <ListView android: id = "@ + id/lv" android: layout_width = "fill_parent" android: layout_height = "0dp" android: layout_weight = "1" android: divider = "@ null" android: listSelector = "@ android: color/transparent" android: transcriptMode = "alwaysScroll"> </ListView> <LinearLayout android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: orientation = "horizontal"> <EditText android: id = "@ + id/sendText" android: layout_width = "0dp" android: layout_height = "wrap_content" android: layout_weight = "1"/> <Button android: id = "@ + id/send_btn" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "send"/> </LinearLayout>


Now that we have discussed listview, we will know our chat information. To display it above, we need to identify the sent message in the adapter and determine the layout of the sent message, on the left is the message layout of the robot, and on the right is the layout of message sending.

It is not complicated either. One textview in a relative layout shows the sending time, one Imageview shows the robot's avatar, and one textview displays the message content.


Robot message layout

<?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" />    <ImageView        android:id="@+id/iv"        android:layout_width="70dp"        android:layout_height="70dp"        android:layout_below="@id/time"        android:padding="10dp"        android:src="@drawable/robot" />    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/time"        android:layout_marginRight="50dp"        android:layout_toRightOf="@id/iv"        android:background="@drawable/aio_friend_bg_nor_11"        android:gravity="center" /></RelativeLayout>

Message Content

<?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" />    <ImageView        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="@drawable/xiaoxin" />    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/time"        android:layout_marginLeft="50dp"        android:layout_toLeftOf="@id/iv"        android:background="@drawable/aio_user_bg_nor_11"        android:gravity="center" /></RelativeLayout>


Without knowing it, we will go to the last step. I believe you will feel that it is very simple. Yes, it is very simple, because the most difficult part is

Business logic:

1. instantiate Edittext, listview, And button

2. Handling button click events

Obtain the content entered by Edittext and process it ----> remove the space and press enter information, and replace it with null. Then encapsulate the data in the Entity class. When there are more than 30 records, clear them once and refresh the adapter.

Send the processed information to the server to obtain the reply information and encapsulate the entity class. Refresh the adapter.


3. Set the welcome language. Every time you come in, we will make a welcome speech to improve the user experience. First, we will create an array to hold the welcome speech.


Add the res/values/Strings Array

<String-array name = "welcome_tips"> <item> owner, slaves are waiting for a long time </item> <item> owner, recently, everything is fine. </item> <item> dear, I want to die. </item> <item> welcome back, my dear master </item> <item> I am a new robot and I am very happy to serve you </item> </string-array>

In the java code

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;}

It is not difficult to understand how to obtain the array content randomly.

When chatting, you should also add the time

Private String getTime () {currentTime = System. currentTimeMillis (); SimpleDateFormat format = new SimpleDateFormat ("MM dd, yyyy HH: mm: ss"); Date curDate = new Date (); String str = format. format (curDate); if (currentTime-oldTime >=500) {oldTime = currentTime; return str ;}else {return "";}}
That is, get the system time and format it.

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; im Port 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 = "; private double currentTime = 0, oldTime = 0; private List <ListData> lists; private ListData listData; private MyAdapter adapter; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initView ();} private void initView () {listView = (ListView) findViewById (R. id. lv); sendtext = (E DitText) findViewById (R. id. sendText); send_btn = (Button) findViewById (R. id. send_btn); lists = new ArrayList <ListData> (); // send the Click Event send_btn.setOnClickListener (this); adapter = new MyAdapter (lists, this); listView. setAdapter (adapter); listData = new ListData (getRandomWelcomeTips (), ListData. aggreger, getTime (); lists. add (listData);} private String getRandomWelcomeTips () {String welcome_tip = null; welcome_a Rray = 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. obtain the content entered by Edittext and process it ----> remove the space and press enter information, and replace it with null. * 2. encapsulate the data in the object class. When there are more than 30 logs, clear the logs once and 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 ()> 30) {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. aggreger, 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 ("MM dd, yyyy HH: mm: ss"); Date curDate = new Date (); String str = format. format (curDate); if (currentTime-oldTime >=500) {oldTime = currentTime; return str ;}else {return "";}}}
In fact, when there is no click, the welcome speech has been displayed on the listview through the adapter, so we can put it under the adapter instantiation, the entity class, the main function is to encapsulate the sending time and content, and identify and display the content in the adapter.

In fact, the most important thing is the content of the adapter. How should we handle the sent message:

We passed two value sets to the adapter, filled with a context of the collection of Object-class data

First, we should establish a relative layout to fill in the content of the entry. If we want a list containing entity classes, Entity classes, and a lot of data, we need to identify and display that part of 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;}}


Click to download source code


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


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.