Andrioid项目之九图灵机器人

Andrioid项目之九图灵机器人

Andrioid项目之九图灵机器人_第1张图片Andrioid项目之九图灵机器人_第2张图片
要实现一个图灵机器人,首先需要在 http://www.tuling123.com/ 中注册,然后创建一个应用,
便可通过应用的API key使用图灵机器人。图灵机器人非常方便的一点是不需要添加额外的库类。
只需要get请求访问 http://www.tuling123.com/openapi/api 就可以获得json数据,
然后对json数据进行解析即可。
下面就用Json解析一下数据

Json解析格式:
一、 JSON (JavaScript Object Notation)一种简单的数据格式,比xml更轻巧,属于轻量级解析。
Json建构于两种结构:
1、“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。 如: 
{
“name”:”jackson”,
“age”:100
}


2、值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)如:
{
“students”:
[
{“name”:”jackson”,“age”:100},
{“name”:”michael”,”age”:51}
]
}
下面具体来看一下图灵机器人的具体实现:
Andrioid项目之九图灵机器人_第3张图片
一:创建接口HttpGetData
<span style="font-size:14px;">package com.example.rootpeople1;

public interface HttpGetData {
	void getDataUrl(String data);
}
</span>

二:创建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 HttpResponse httpResponse;
	private HttpEntity httpEntity;
	private InputStream in;
	private HttpGetData listener;
	//请求的urL
	 public HttpData(String url,HttpGetData listener) {
			this.url=url;
			this.listener=listener;
		}
	@Override
	protected String doInBackground(String... params) {
		try {
			httpClient=new DefaultHttpClient();
			httpGet=new HttpGet(url);
			httpResponse=httpClient.execute(httpGet);
			httpEntity=httpResponse.getEntity();
			in=httpEntity.getContent();//获取实体内容
			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;
	}
	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub6
	listener.getDataUrl(result);
		super.onPostExecute(result);
	}

}
三:创建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);
		
	}
	
	
}
四: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 stub
		return lists.size();
	}

	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return lists.get(position);
	}

	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 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;
	}

}
五:测试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 [] welcomeArray;
	private double currenttime,oldTime=0;
	
	@Override
	protected 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("时间"+listData);
		list.add(listData);
		
	}

	public void getDataUrl(String data) {
		// TODO Auto-generated method stub
		parseText(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("时间"+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年MM月dd日  HH:mm:ss");
		//SimpleDateFormat format=new SimpleDateFormat("HH:mm");
		Date curdata=new Date();
		String str=format.format(curdata);
		if(currenttime - oldTime >=5*60*1000){
			oldTime=currenttime;
			return  str;
		}else{
			return "";
		}
			
		
	}
}
UI布局文件
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"
    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: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/senText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" 
              android:background="@android:drawable/edit_text"
              />

        <Button
            android:id="@+id/send_btn" 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/send"
 
            />
    </LinearLayout>

</LinearLayout>
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
        android:id="@+id/time"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="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"
        android:gravity="center_vertical"
        android:id="@+id/time"
        
        />
    
    <TextView 
         android:layout_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="@drawable/aio_user_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:layout_alignParentRight="true"
        android:layout_below="@+id/time"
        android:src="@drawable/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>
最终运行界面:
Andrioid项目之九图灵机器人_第4张图片 Andrioid项目之九图灵机器人_第5张图片


Andrioid项目之九图灵机器人_第6张图片
如需源码请点击连接下载:
http://pan.baidu.com/s/1gfbKRcv
密码 eyb2

你可能感兴趣的:(json,json解析,机器人,图灵机器人,智能对话)