Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android項目之九圖靈機器人

Android項目之九圖靈機器人

編輯:關於Android編程

\\

要實現一個圖靈機器人,首先需要在 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}
]
}
下面具體來看一下圖靈機器人的具體實現: \ 一:創建接口HttpGetData
package com.example.rootpeople1;

public interface HttpGetData {
	void getDataUrl(String data);
}

二:創建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 {
	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 lists;
	private Context  mContext;
	private RelativeLayout layout;
	
	
	public TextAdapter(List 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 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();
		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=&quot;+droph,this).execute();" private="" string="" getrandomwelcometips(){="" welcome_tipe="null;" welcomearray="this.getResources().getStringArray(R.array.welcome_tips);" int="" index="(int)" (math.random()*(welcomearray.length-1));="" return="" welcome_tipe;="" gettime(){="" currenttime-="System.currentTimeMillis();" simpledateformat="" format="new" simpledateformat("yyyy年mm月dd日="" hh:mm:ss");="" simpledateformat("hh:mm");="" date="" curdata="new" date();="" str="format.format(curdata);" if(currenttime="" -="" oldtime="">=5*60*1000){
			oldTime=currenttime;
			return  str;
		}else{
			return "";
		}
			
		
	}
}
UI布局文件
activity_main.xml


    
    

    

        
leftitem.xml



    

    

    

rightem.xml


     
    
    

    

最終運行界面:
\\     \
如需源碼請點擊連接下載: http://pan.baidu.com/s/1gfbKRcv
密碼eyb2  
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved