android中一个与智能机器人问答的简单程序

现在网上的可以进行简单问答的人工智能挺多的,大家可以自行搜索接口,一般的网站上都会给你详细的提示与接口的使用方法,还有json数据的格式,这里不另作说明。

首先建立的是一个联网与人工智能接口交互的工具类。


这个方法返回的就是一发送信息后,接口回馈给你的json信息

public class HttpUtils {
public static String getJsonContent(String url){
String result = "";
URL url2;
InputStream is;
InputStreamReader isr;
BufferedReader br;
try {
url2 = new URL(url);
HttpURLConnection connection = 
(HttpURLConnection)url2.openConnection();
is = connection.getInputStream();
isr = new InputStreamReader(is,"utf-8");
String line = "";
br = new BufferedReader(isr);
while ((line=br.readLine())!=null) {
  result+=line;
}
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{


}
return result;
}

接下来是这个程序中比较难一点的list布局,写一个类,继承listView的父类BaseAdapter ,在这个类中定义你的适配器,为了方便,这个适配器没有进行listView优化 ,有需要的可以看我的另一篇文章,其中有对listview 优化的一些理解和方法,废话不多说,下面就是这个适配器类中的代码。

public class RobotAdapter extends BaseAdapter{
private Context context ;
private List<Map<String, Object>> list;
public RobotAdapter(Context context,List<Map<String, Object>> list) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override

//布局中最关键的一个方法,构造函数传的值是Context和你的对话记录的list集合,然后根据其中map键值的对应选择相对应的布局方式。
public View getView(int arg0, View arg1, ViewGroup arg2) {
int who = (Integer) list.get(arg0).get("person");
View view;
TextView text;
final TextView time;
if(who==1){
view = LayoutInflater.from(context).inflate(R.layout.per_send, null);
text = (TextView) view.findViewById(R.id.per_say);
text.setText((String)list.get(arg0).get("text"));
time = (TextView) view.findViewById(R.id.per_time);
time.setText((String)list.get(arg0).get("time"));
}else {
view = LayoutInflater.from(context).inflate(R.layout.robot_send, null);
text = (TextView) view.findViewById(R.id.rob_say);
text.setText((String)list.get(arg0).get("text"));
Log.i("main", (String)list.get(arg0).get("text"));
time = (TextView) view.findViewById(R.id.rob_time);
time.setText((String)list.get(arg0).get("time"));
}
return view;
}
}

下面这段代码是聊天界面的几个布局文件,比较粗糙,可以自行优化

<?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" >
    <LinearLayout
        android:id="@+id/layout01"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:background="@drawable/title_bar"
        >
        <TextView
            android:text="消息"
            android:textSize="20sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="130dp"
            android:layout_marginTop="15dp"
            android:textColor="#fffff0"/>    
    </LinearLayout>
    <LinearLayout
        android:id="@+id/layout02"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="@drawable/bottom_bar"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:weightSum="4">


        <EditText
            android:id="@+id/my_input"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:background="@drawable/login_edit_normal"
            android:maxLines="140"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="5dp">


            <requestFocus />
        </EditText>


        <Button
            android:id="@+id/btn_input"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="发送"
            android:textColor="#fffff0"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp" 
            android:background="@drawable/select_color"/>


    </LinearLayout>
    <ListView
        android:id="@+id/ls"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/layout02"
        android:layout_below="@+id/layout01"
        android:transcriptMode="alwaysScroll"
        android:listSelector="@android:color/transparent"
        >
        
    </ListView>


</RelativeLayout>


<?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:padding="10dp">
    <TextView
        android:id="@+id/rob_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#708090"
        android:text="时间"
        android:layout_centerHorizontal="true"
        android:textColor="#fffff0"
        android:textSize="12sp"/>
    <ImageView
        android:id="@+id/rob_pic"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_below="@+id/rob_time"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="10dp"
        android:src="@drawable/egg"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="大叔冰华"
        android:layout_below="@+id/rob_pic"
        android:layout_marginTop="5dp"/>
    <TextView
        android:id="@+id/rob_say"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/rob_pic"
        android:layout_toRightOf="@+id/rob_pic"
        android:background="@drawable/chatfrom_bg_normal"
        android:maxEms="10"
        android:text="我说"
        android:textColor="#fffff0"
        android:textSize="15sp" />


</RelativeLayout>


<?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:padding="10dp">
    <TextView
        android:id="@+id/per_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#708090"
        android:text="时间"
        android:layout_centerHorizontal="true"
        android:textSize="12sp"
        android:textColor="#fffff0"/>
    <ImageView
        android:id="@+id/per_pic"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_below="@+id/per_time"
        android:layout_alignParentRight="true"
        android:layout_marginTop="10dp"
        android:src="@drawable/me"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我"
        android:layout_below="@+id/per_pic"
        android:layout_alignLeft="@+id/per_pic"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="5dp"/>


    <TextView
        android:id="@+id/per_say"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/per_pic"
        android:layout_toLeftOf="@+id/per_pic"
        android:background="@drawable/chatto_bg_normal"
        android:maxEms="10"
        android:text="我说"
        android:textColor="#606060"
        android:textSize="15sp" />
</RelativeLayout>

由于时间关系,主activity类不做说明,代码自己看把

package org.example.robotdemo;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.security.auth.PrivateCredentialPermission;


import org.example.robotdemo.bean.GsonDemo;
import org.example.robotdemo.bean.NewsDemo;
import org.example.robotdemo.http.HttpUtils;


import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;


public class MainActivity extends Activity {

private ListView ls;
private EditText persend ;
private Button button;
private String APIKEY = "a6016421b08c4089841d1519ec00497b"; 
    private  String INFO;
    private  String getURL = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=";
    private RobotAdapter adapter ;
private List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.talk_layout);
ls = (ListView) findViewById(R.id.ls);
button = (Button) findViewById(R.id.btn_input);
persend = (EditText) findViewById(R.id.my_input);
adapter = new RobotAdapter(MainActivity.this, list);

ls.setAdapter(adapter);
ls.setSelection(adapter.getCount());
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String info = persend.getText().toString();
if(info!=null){
persend.setText("");
}
try {
INFO = URLEncoder.encode(info,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Map<String, Object> map = new HashMap<String, Object>();
Log.i("--------------", getURL);
map.put("person", 1);
map.put("text", info);
map.put("time", printDate());
list.add(map);
    adapter.notifyDataSetChanged();
    new RobotTask().execute(getURL+INFO);    
    ls.smoothScrollToPosition(ls.getCount()-1);    
}
});

}
public static String printDate() {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(new Date());
}

class RobotTask extends AsyncTask<String, Void, String>{


@Override
protected String doInBackground(String... arg0) {
String json = HttpUtils.getJsonContent(arg0[0]);
String string = GsonDemo.show(json);
Log.i("main", arg0[0]);
Log.i("mian",json);
return string;
}


@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Map<String , Object> map = new HashMap<String, Object>();
map.put("person", 0);
map.put("text", result);
Log.i("mian", result);
map.put("time", printDate());
list.add(map);
adapter.notifyDataSetChanged();
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值