Andrioid project of the nine Turing robot

Source: Internet
Author: User

Andrioid Project nine Turing man
to implement a Turing person, you first need to register in http://www.tuling123.com/and then create an app that the Turing device can be used by the app's API key. One of the most convenient thing about Turing is that you don't need to add additional library classes. only GET request access to HTTP://WWW.TULING123.COM/OPENAPI/API can get JSON data, the JSON data can then be parsed.
let's use JSON to parse the data .
JSON parsing format: one, JSON (JavaScript Object Notation) A simple data format, lighter than XML, is lightweight parsing.
json is constructed in two structures:
1. The collection of name/value pairs (A collection of name/value pairs). In different languages, it is understood as objects (object), record (record), structure (struct), Dictionary (dictionary), hash table (hash table), keyed list (keyed list), or associative array (associative Array). such as:  
{
"name": "Jackson",
"age":
}


Span style= "COLOR: #ff0000" > 2, the value of the ordered list (an ordered list of values). In most languages, it is understood as an array (array) such as:

{
" Students ":
[
{" name ":" Jackson "," Age ":",
{"name": "Michael", "Age": Wuyi}
"
}
Here's a look at the specific implementation of a psychic robot:
One: Create interface Httpgetdata
<span style= "FONT-SIZE:14PX;" >package Com.example.rootpeople1;public interface Httpgetdata {void Getdataurl (String data); </span>

II: Create Httpdata.java
Package Com.example.rootpeople1;import Java.io.bufferedreader;import Java.io.inputstream;import Java.io.inputstreamreader;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Android.os.asynctask;public class HttpData extends AsyncTask <string, Void, string> {private HttpClient httpclient;private httpget httpget;private String url;private httprespo NSE httpresponse;private httpentity httpentity;private inputstream in;private httpgetdata listener;//requested URL public Httpdata (String Url,httpgetdata listener) {This.url=url;this.listener=listener;} @Overrideprotected string Doinbackground (String ... params) {try {httpclient=new defaulthttpclient (); httpget=new HttpGet (URL); Httpresponse=httpclient.execute (HttpGet); httpentity=httpresponse.getentity (); in= Httpentity.getcontent ();//Get entity Content BufferedReader br=new BufferedReader (New INPUTSTReamreader (in)); String Line=null;          StringBuffer sb=new StringBuffer (); while ((Line=br.readline ())!=null) {sb.append (line);} return sb.tostring ();} catch (Exception e) {//Todo:handle Exception}return null;} @Overrideprotected void OnPostExecute (String result) {//TODO auto-generated method Stub6listener.getdataurl (Result); Super.onpostexecute (result);}}
Three: Create Listdata.java
Package Com.example.rootpeople1;public class ListData {private String content;public static final  int Send=1;public static final  int  receiver=2;private int flag;private string Time;public string GetTime () {return time;} public void SetTime (String time) {this.time = time;} Public String getcontent () {return content;} public void SetContent (String content) {this.content = content;} public int Getflag () {return flag;} public void Setflag (int flag) {This.flag = flag;} Public ListData (String content, int flag,string time) {super (); setcontent (content); Setflag (flag); SetTime (time);}}
Four: Textadapter.java
Package Com.example.rootpeople1;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 Textadapter extends Baseadapter{private list<listdata> lists;private Context mcontext;private RelativeLayout Layout;public Textadapter (list<listdata> lists, Context mcontext) {this.lists = Lists;this.mcontext = MContext;} public int GetCount () {//TODO auto-generated method Stubreturn lists.size ();} Public Object getItem (int position) {//TODO auto-generated method Stubreturn lists.get (position);} public long getitemid (int position) {//TODO auto-generated method Stubreturn position;} Public 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.rightem, NULL );} TextView TV = (TextView) Layout.findviewbyid (r.id.tv); TextView time= (TextView) Layout.findviewbyid (r.id.time) Time.settext (lists.get (position). GetTime ()); Tv.settext ( Lists.get (position). GetContent ()); return layout;}}
V: Test Mainactivity.java
Package Com.example.rootpeople1;import Java.text.simpledateformat;import Java.util.arraylist;import java.util.Date ; Import Java.util.list;import Org.json.jsonobject;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 Httpgetdata,onclicklistener {private Httpdata httpdata;private list<listdata> list;private ListView lv;private Button send_btn;private EditText sendtext;private string content_str;private textadapter adapter;private string [] Welco Mearray;private double currenttime,oldtime=0; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initeview ();} private void Initeview () {list=new arraylist<listdata> (); lv= (ListView) Findviewbyid (r.id.lv); send_btn= (Button ) Findviewbyid (r.id.send_bTN); sendtext= (EditText) Findviewbyid (R.id.sentext); Send_btn.setonclicklistener (this); Adapter=new Textadapter ( List,this); Lv.setadapter (adapter); ListData ListData = Null;listdata=new ListData (getrandomwelcometips (), Listdata.receiver,gettime ()); System.out.println ("Time" +listdata); List.add (listData);} public void Getdataurl (String data) {//TODO auto-generated method Stubparsetext (data);} public void ParseText (String str) {try {jsonobject jb=new jsonobject (str);/*system.out.println (jb.getstring ("Code")); System.out.println (jb.getstring ("text")), */listdata ListData = Null;listdata=new ListData (jb.getstring ("text"), Listdata.receiver,gettime ()); System.out.println ("Time" +listdata); List.add (ListData); adapter.notifydatasetchanged ();} catch (Exception e) {//Todo:handle exception}}public void OnClick (View v) {content_str=sendtext.gettext (). toString (); Sendtext.settext (""); String dropk=content_str.replace ("", ""); String droph=dropk.replace ("\ n", ""); ListData ListData = null;listdata=new ListData (contenT_str,listdata.send,gettime ()); System.out.println ("SFDs" +listdata), List.add (Listdata), if (List.size () >30) {for (int i=0;i<list.size (); i++) { List.remove (i);}} Adapter.notifydatasetchanged (); Httpdata= (Httpdata) New Httpdata ("http://www.tuling123.com/openapi/api?key= 5a4b5c8bbf2c8a9dd02861999fa0d45c&info= "+droph,this). Execute (); private String Getrandomwelcometips () {string welcome_tipe=null;welcomearray=this.getresources (). Getstringarray ( r.array.welcome_tips); int index= (int) (Math.random () * (welcomearray.length-1)); Welcome_tipe=welcomearray[index]; return welcome_tipe;} Private String GetTime () {currenttime-=system.currenttimemillis (); SimpleDateFormat format=new SimpleDateFormat ("yyyy year mm DD Day HH:mm:ss");//simpledateformat format=new SimpleDateFormat ("hh:mm");D ate curdata=new Date (); String Str=format.format (Curdata); if (Currenttime-oldtime >=5*60*1000) {Oldtime=currenttime;return str;} Else{return "";}}}
UI 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" android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin "android:paddingright=" @dimen/activity_horizontal_margin "android:paddingtop=" @dimen/activity_ Vertical_margin "tools:context=". Mainactivity "> <listview android:id=" @+id/lv "android:layout_width=" Fill_parent "Android:la yout_height= "0DP" android:layout_weight= "1" android:divider= "@null" android:listselector= "@android: Co Lor/transparent "android:transcriptmode=" Alwaysscroll "> </ListView> <linearlayout Android        : layout_width= "fill_parent" android:layout_height= "wrap_content" android:orientation= "Horizontal" >      <edittext      Android:id= "@+id/sentext" android:layout_width= "0DP" android:layout_height= "Wrap_content"        android:layout_weight= "1" android:background= "@android:d rawable/edit_text"/> <button android:id= "@+id/send_btn" android:layout_width= "Wrap_content" android:layout _height= "Wrap_content" android:text= "@string/send"/> </linearlayout></linearlayout& Gt
Leftitem.xml
<?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 androi D:id= "@+id/time" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android:grav        ity= "Center_horizontal"/> <textview android:id= "@+id/tv" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparentleft= "true" android:layout_below= "@+id/time "Android:layout_marginleft=" 45DP "android:layout_margintop=" 55DP "android:background=" @drawable/aio_            Friend_bg_nor_11 "android:gravity=" center "/> <com.makeramen.roundedimageview.roundedimageview             xmlns:app= "Http://schemas.android.com/apk/res-auto" android:id= "@+id/iv" android:layout_width= "60DP" Android:layout_height= "60DP" android:gravity= "Center_horizontal" android:src= "@drawable/test_photo"            App:riv_border_color= "#333333" app:riv_border_width= "3dip" app:riv_corner_radius= "10dip" App:riv_mutate_background= "true" app:riv_oval= "true"/></relativelayout>
Rightem.xml
<?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:orientation=" vertical " > <textview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" an Droid:gravity= "center_vertical" android:id= "@+id/time"/> <textview android:la yout_below= "@id/iv" android:layout_marginleft= "55DP" android:layout_toleftof= "@id/iv" Android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content" android:id= "@+id/tv" android:background= "@d Rawable/aio_user_bg_nor_11 "android:gravity=" center "/> <com.makeramen.roundedimageview.roundedimag Eview xmlns:app= "Http://schemas.android.com/apk/res-auto" android:id= "@+id/iv" android:layout_width= " 60DP "Android:layout_height= "60DP" android:layout_alignparentright= "true" android:layout_below= "@+id/time" android:src= "@drawab        Le/picture "app:riv_border_color=" #333333 "app:riv_border_width=" 3dip "app:riv_corner_radius=" 10dip " App:riv_mutate_background= "true" app:riv_oval= "true"/></relativelayout>
Final Run Interface:



For source code please click on the connection download: HTTP://PAN.BAIDU.COM/S/1GFBKRCV
Password Eyb2

Andrioid project of the nine Turing 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.