标签:
写图灵机器人这个小例子可以学到以下几点知识:
1:网络访问
2:调用第三方api(虽然这个没怎么调用)
3:listview的多item处理
4,:listview的界面刷新
下面开始讲解代码编写过程:(下图是目录结构)

第一步:创建一个工具类和工具包:HttpUtil.java
package ***
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import com.google.gson.Gson;
import **.ChatMessageBean;
import **.ChatMessageBean.Type;
import **.ResultBean;
/**
* @author pop 此工具类为了向图灵中发送数据(msg),也是从图灵获取数据(result)
*/
public class HttpUtil {
private final static String URL = "http://www.tuling123.com/openapi/api";
private final static String KEY = "917c19478dd0d542ca6e67c8495cfe26";
public static ChatMessageBean doChat(String msg) {
ChatMessageBean chatBean = new ChatMessageBean();
String jsonResult = doGet(msg);
try {
Gson gson = new Gson();
ResultBean result = gson.fromJson(jsonResult, ResultBean.class);
chatBean.setText(result.getText());
} catch (Exception e) {
chatBean.setText("服务器繁忙,请稍后");
}
chatBean.setDate(new Date());
chatBean.setType(Type.COMING);
return chatBean;
}
/**
* 从图灵中获取返回值
*
* @param msg
* @return
*/
public static String doGet(String msg) {
String result = null;
String url = pjURL(msg);
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
URL urlGet = new URL(url);
HttpURLConnection coon = (HttpURLConnection) urlGet
.openConnection();
coon.setRequestMethod("GET");
coon.setReadTimeout(5000);
coon.setConnectTimeout(5000);
is = coon.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int len = -1;
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
baos.flush();
result = new String(baos.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* 拼接url
*
* @param msg
* @return
*/
private static String pjURL(String msg) {
try {
msg = URLEncoder.encode(msg, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String url = URL + "?key=" + KEY + "&info=" + msg;
return url;
}
}
第二步:创建测试类 HttpUtilTest,创建测试类之前要搭建测试环境(修改清单文件,注意还有网络的哟)
public class HttpUtilTest extends AndroidTestCase {
public void test() {
String result = HttpUtil.doGet("你好!");
Log.i("main", result);
result = HttpUtil.doGet("讲个笑话");
Log.i("main", result);
result = HttpUtil.doGet("我不开心");
Log.i("main", result);
result = HttpUtil.doGet("你好美");
Log.i("main", result);
result = HttpUtil.doGet("吃饭了么");
Log.i("main", result);
result = HttpUtil.doGet("睡觉了");
Log.i("main", result);
}
}
第三步:本系统根据业务分析就需要两种bean,一个是从图灵返回的bean,另一个是处理返回bean的结果bean
第一个bean
public class ResultBean {
private String code;
private String text;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
第二个bean
public class ChatMessageBean {
private String name;
private String text;
private Date date;
private Type type;
public ChatMessageBean() {
}
public ChatMessageBean(String text, Date date, Type type) {
this.text = text;
this.date = date;
this.type = type;
}
public enum Type {
OUTING, COMING
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}
第四步:编写布局文件。首先是发送与返回item,其次是主页面
返回item <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:orientation="vertical" > <TextView android:id="@+id/timeBack" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="#bebebe" android:text="@string/time" android:textColor="#f5f5f5" android:textSize="12sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <ImageView android:layout_width="49dp" android:layout_height="49dp" android:contentDescription="@null" android:src="@drawable/tuling" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="@string/tuling" android:textSize="18sp" /> </LinearLayout> <TextView android:id="@+id/txtBack" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:gravity="left" android:text="@string/hello_world" android:textColor="#bebebe" android:textSize="18sp" /> </LinearLayout> </LinearLayout>
发送item <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="5dp" android:gravity="right" android:orientation="vertical" > <TextView android:id="@+id/sTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="#bebebe" android:text="@string/time" android:textColor="#f5f5f5" android:textSize="12sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="right" android:orientation="horizontal" > <TextView android:id="@+id/sendTxt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="5dp" android:gravity="right" android:textColor="#bcbcbc" android:textSize="18sp" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <ImageView android:layout_width="49dp" android:layout_height="49dp" android:contentDescription="@null" android:src="@drawable/me" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="@string/zyy" android:textColor="#bebebe" android:textSize="18sp" /> </LinearLayout> </LinearLayout> </LinearLayout>
主界面 <RelativeLayout 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:background="@drawable/main" > <RelativeLayout android:id="@+id/top" android:layout_width="fill_parent" android:layout_height="45dp" android:layout_alignParentTop="true" android:background="#000" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/tuling" android:textColor="#fff" android:textSize="22sp" /> </RelativeLayout> <RelativeLayout android:id="@+id/bottom" android:layout_width="fill_parent" android:layout_height="45dp" android:layout_alignParentBottom="true" android:background="#000" > <Button android:id="@+id/bootom_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:onClick="send" android:text="@string/send" /> <EditText android:id="@+id/bottom_edit" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_margin="4dp" android:layout_toLeftOf="@id/bootom_send" android:background="#fff" android:gravity="center" android:hint="@null" /> </RelativeLayout> <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@id/bottom" android:layout_below="@id/top" android:divider="@null" android:dividerHeight="3dp" > </ListView> </RelativeLayout>
第五步:编写适配器,和主界面的activity
适配器
public class MessageAdapter extends BaseAdapter {
private List<ChatMessageBean> mDatas;
private LayoutInflater inflater;
private Context context;
public MessageAdapter(List<ChatMessageBean> mDatas, Context context) {
this.context = context;
this.mDatas = mDatas;
}
@Override
public int getCount() {
return mDatas.size();
}
@Override
public Object getItem(int postion) {
return mDatas.get(postion);
}
@Override
public long getItemId(int postion) {
return postion;
}
@SuppressLint("SimpleDateFormat")
@Override
public View getView(int postion, View view, ViewGroup parent) {
ChatMessageBean chatBean = mDatas.get(postion);
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ViewHolder holder = null;
if (view == null) {
inflater = LayoutInflater.from(context);
if (getItemViewType(postion) == 0) {
// 这是没用viewholder模式的情况
view = inflater.inflate(R.layout.back, parent, false);
TextView mTime = (TextView) view.findViewById(R.id.timeBack);
TextView mTxt = (TextView) view.findViewById(R.id.txtBack);
mTxt.setText(chatBean.getText());
mTime.setText(sf.format(chatBean.getDate()));
} else {
// 这是使用了viewholder模式的情况
view = inflater.inflate(R.layout.send, parent, false);
holder = new ViewHolder();
holder.mDate = (TextView) view.findViewById(R.id.sTime);
holder.mMsg = (TextView) view.findViewById(R.id.sendTxt);
// 设置数据
holder.mDate.setText(sf.format(chatBean.getDate()));
holder.mMsg.setText(chatBean.getText());
view.setTag(holder);
}
} else {
// 方法一:不适用viewholder,那么就要把上面的代码抄写一遍咯
if (getItemViewType(postion) == 0) {
TextView mTime = (TextView) view.findViewById(R.id.timeBack);
TextView mTxt = (TextView) view.findViewById(R.id.txtBack);
mTxt.setText(chatBean.getText());
mTime.setText(sf.format(chatBean.getDate()));
} else {
TextView mTime = (TextView) view.findViewById(R.id.sTime);
TextView mTxt = (TextView) view.findViewById(R.id.sendTxt);
mTxt.setText(chatBean.getText());
mTime.setText(sf.format(chatBean.getDate()));
}
// 方法二:使用viewholder
// holder = (ViewHolder) view.getTag();
}
return view;
}
@Override
public int getItemViewType(int postion) {
ChatMessageBean chatBean = mDatas.get(postion);
if (chatBean.getType() == Type.COMING) {
return 0;
}
return 1;
}
@Override
public int getViewTypeCount() {
return 2;
}
// 这是一种viewholder模式
private final class ViewHolder {
TextView mDate;
TextView mMsg;
}
}
主页面的activity
public class MainActivity extends Activity {
private ListView msgListView;
private MessageAdapter mAdapter;
private EditText sendTxt;
private List<ChatMessageBean> mDatas;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
ChatMessageBean bean = (ChatMessageBean) msg.obj;
mDatas.add(bean);
mAdapter.notifyDataSetChanged();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initView();
initData();
}
public void send(View v) {
final String send = sendTxt.getText() == null ? null : sendTxt
.getText().toString();
if (TextUtils.isEmpty(send)) {
Toast.makeText(this, "输入不可以为空", Toast.LENGTH_SHORT).show();
return;
}
ChatMessageBean sBean = new ChatMessageBean(send, new Date(),
Type.OUTING);
mDatas.add(sBean);
mAdapter.notifyDataSetChanged();
sendTxt.setText("");
new Thread() {
@Override
public void run() {
ChatMessageBean bBean = HttpUtil.doChat(send);
Message msg = Message.obtain();
msg.obj = bBean;
handler.sendMessage(msg);
}
}.start();
}
private void initData() {
mDatas = new ArrayList<ChatMessageBean>();
mDatas.add(new ChatMessageBean("你好,我是图灵,很高兴为你服务", new Date(),
Type.COMING));
mAdapter = new MessageAdapter(mDatas, this);
msgListView.setAdapter(mAdapter);
}
private void initView() {
sendTxt = (EditText) findViewById(R.id.bottom_edit);
msgListView = (ListView) findViewById(R.id.list);
}
}
总结,没写出来之前觉得不会写,不敢写,写出来之后,发现挺好玩的,而且确实学到了不少东西,百看不练等于完蛋。
标签:
原文地址:http://my.oschina.net/u/1539812/blog/476594