Android应用之词典(一)

来源:互联网 发布:货单打印软件 编辑:程序博客网 时间:2024/05/18 02:56

下面简单的实现词典的查询功能

1.布局方面

一个EditText,一个Button,一个TextView就可以了

如下

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/rl"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@color/mistyrose"   >        <EditText            android:id="@+id/edt_content"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:layout_marginLeft="5dp"            android:layout_marginTop="15dp"            android:background="@color/honeydew"            android:padding="5dp"/>        <Button            android:id="@+id/bt_transf"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:layout_marginRight="5dp"            android:layout_below="@+id/edt_content"            android:text="翻译"             />        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_below="@+id/bt_transf"            android:orientation="vertical">           <TextView               android:id="@+id/tv_result"               android:layout_width="match_parent"               android:layout_height="wrap_content"               android:padding="5dp"               android:text="翻译结果"               android:textSize="18sp"               android:textColor="@color/black" />        </LinearLayout></RelativeLayout>

2.Java代码

具体过程是连接到网络,这样才能查询,获取EditText上的内容,连网查询翻译的API接口,获取json字符串,解析json,将其在TextView上显示

这其中涉及到以下几点

(1)网络请求

(2)IO操作

(3)JSON转换

(4)UI更新


网络请求

使用HttpURLConnection

new一个URL对象

URL url=new URL("http://fanyi.youdao.com/openapi.");

建立连接

connection=(HttpURLConnection)url.openConnection();
使用GET请求方式

connection.setRequestMethod("GET");


接下来是IO操作

InputStream in=connection.getInputStream();//获取输入字节流BufferedReader buf=new BufferedReader(new InputStreamReader(in));//包装为字符流StringBuilder response=new StringBuilder(); String line;//读取while((line=buf.readLine())!=null){  response.append(line);}


JSON字符串处理

主要点:[]为JSONArray,{}为JSONObject ,其它的字符串,整形等直接用getString(),等形式来获取


UI更新

需要使用handler机制


具体代码如下

public class MainActivity extends Activity implements View.OnClickListener {    private static final int SHOW_RESPONSE=0;    private TextView textView_result;    private Button button_transf;    private EditText editText_content;    private Handler handler=new Handler(){        @Override        public void handleMessage(Message msg) {            switch (msg.what){                case SHOW_RESPONSE:                    CharSequence response=Html.fromHtml(msg.obj.toString());                    textView_result.setText(response);            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView_result=(TextView)findViewById(R.id.tv_result);        button_transf=(Button)findViewById(R.id.bt_transf);        editText_content=(EditText)findViewById(R.id.edt_content);        button_transf.setOnClickListener(this);    }    public void connectDict(){        new Thread(new Runnable() {            @Override            public void run() {                HttpURLConnection connection=null;                try {                    String content=editText_content.getText().toString();                    URL url=new URL("http://fanyi.youdao.com/openapi.do?keyfrom=dictionaryTestqq&key=416582248&type=data&doctype=json&version=1.1&q="+content);                    connection=(HttpURLConnection)url.openConnection();                    connection.setRequestMethod("GET");                    connection.setConnectTimeout(8000);                    connection.setReadTimeout(8000);                    InputStream in=connection.getInputStream();//获取输入字节流                    BufferedReader buf=new BufferedReader(new InputStreamReader(in));//包装为字符流                    StringBuilder response=new StringBuilder();                    String line;                    //读取                    while((line=buf.readLine())!=null){                           response.append(line);                    }                    Message message=new Message();                    message.what=SHOW_RESPONSE;                    message.obj=getJsonResult(response);                    handler.sendMessage(message);                } catch (MalformedURLException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }                if(connection!=null){                    connection.disconnect();                }            }            private String getJsonResult(StringBuilder response) {                String trans=null;                try {                    JSONObject jsonObject=new JSONObject(String.valueOf(response));                    trans="translation:"+jsonObject.getString("translation")+"<br>";                    JSONObject basicObject=jsonObject.getJSONObject("basic");                    trans+="美式:"+basicObject.getString("us-phonetic")+"<br>";                    trans+="标准:"+basicObject.getString("phonetic")+"<br>";                    trans+="英式:"+basicObject.getString("uk-phonetic")+"<br>";                    trans+="<br>explains:<br>";                    JSONArray expObject=basicObject.getJSONArray("explains");                    for (int i=0;i<expObject.length();i++){                        trans+=expObject.get(i)+"<br>";                    }                    trans+= "<br><h1><font color='red'>web:</font></h1>";                    JSONArray webObject=jsonObject.getJSONArray("web");                    for (int i=0;i<webObject.length();i++){                        JSONObject oj=(JSONObject)webObject.get(i);                        trans+="key: "+oj.getString("key")+"<br>";                        trans+=oj.getString("value")+"<br>";                    }                } catch (JSONException e) {                    e.printStackTrace();                }                return trans;            }        }).start();    }    @Override    public void onClick(View v) {        if(v.getId()==R.id.bt_transf){            connectDict();        }    }}




0 0
原创粉丝点击