android学习-有道词典开发实例

最近学习android程序开发,在网看上到一个关于android手机开发有道词典的例子。但是,并不能正常运行,现在个人改进版本源代码和思路献上之供学习之用。

第一步,申请API key,申请地址:http://fanyi.youdao.com/openapi?path=data-mode

数据接口:

http://fanyi.youdao.com/openapi.do?keyfrom=<keyfrom>&key=<key>&type=data&doctype=<doctype>&version=1.1&q=要翻译的文本

 

 

 

 

版本:1.1,请求方式:get,编码方式:utf-8

 

主要功能:中英互译,同时获得有道翻译结果和有道词典结果(可能没有)

 

参数说明:

 

 type - 返回结果的类型,固定为data

 

 doctype - 返回结果的数据格式,xml或json或jsonp

 

 version - 版本,当前最新版本为1.1

 

 q - 要翻译的文本,不能超过200个字符,需要使用utf-8编码

 

errorCode:

 

 0 - 正常

 

 20 - 要翻译的文本过长

 

 30 - 无法进行有效的翻译

 

 40 - 不支持的语言类型

 

 50 - 无效的key

json数据格式举例

请求链接:=see

 

返回的json数据: 

 

 

{

"translation":["看到"],

"basic":{"phonetic":"si?","explains":["vi. 看;看见;领会","vt. 看见;理解;领会","n. (See)人名;(英)西伊;(柬)塞;(德)泽"]},

"query":"see",

"errorCode":0,

"web":[

{"value":["看见","看出","看看"],"key":"see"},

{"value":["看透","看穿","干完"],"key":"see through"},

{"value":["圣座","教廷","罗马教廷"],"key":"Holy See"}

   ]

当你输入一个无效的Key时将返回如下json数据:

{"query":"see","errorCode":50}

现在程序代码供上:

布局文件activity_main.xml 

<?xml version="1.0" encoding="utf-8"?> <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:orientation="vertical"       android:background="@drawable/bg"     >     <EditText         android:id="@+id/searchcontent"         android:layout_width="wrap_content"         android:layout_height="wrap_content"                 android:hint="输入要查询的单词/文字....."         />     <Button         android:id="@+id/btn_search"         android:layout_width="wrap_content"         android:layout_height="wrap_content"                android:text="Search"                 />     <ScrollView         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:scrollbars="none"          >          <TextView              android:id="@+id/searchresult"              android:layout_width="fill_parent"              android:layout_height="wrap_content"                                      />             </ScrollView>     </LinearLayout>

 
 

 

MainActivity:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147

package com.example.youdaotranslationdemo;

import java.io.BufferedReader; import java.io.InputStreamReader;

import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; 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.TextView; import android.widget.Toast;

public class MainActivity extends Activity {  private EditText searchText;  private Button btn_search;  private TextView   searchresult;  //  private String YouDaoBaseUrl="http://fanyi.youdao.com/openapi.do";  private String YouDaoKeyFrom="你申请的keyfrom";  private String YouDaokey="你申请的key";  private String YouDaoType="data";  private String YouDaoDoctype="json";  private String YouDaoVersion="1.1";  

 @Override  protected void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.activity_main);   ini();  }  private void ini(){   searchText=(EditText)findViewById(R.id.searchcontent);   btn_search=(Button)findViewById(R.id.btn_search);   searchresult=(TextView)findViewById(R.id.searchresult);   btn_search.setOnClickListener(new searchListener());     }  class searchListener implements OnClickListener{

 @Override  public void onClick(View v) {   // TODO Auto-generated method stub   String YouDaoSearchContent=searchText.getText().toString().trim();   if(YouDaoSearchContent.equals("")){    Toast.makeText(MainActivity.this, "请输入要查询的内容!", Toast.LENGTH_LONG).show();   }else{         String YouDaoUrl=YouDaoBaseUrl+"?keyfrom="+YouDaoKeyFrom+"&key="+YouDaokey+"&type="+YouDaoType+     "&doctype="+YouDaoDoctype+"&version="+YouDaoVersion+"&q="+YouDaoSearchContent;   try{    AnalyzingOfJson(YouDaoUrl);       }catch(Exception e){    e.printStackTrace();   }   }  }

 private void AnalyzingOfJson(String youDaoUrl) throws Exception {   // TODO Auto-generated method stub    HttpGet httpGet= new HttpGet(youDaoUrl);    HttpResponse httpResponse= new DefaultHttpClient().execute(httpGet);    if(httpResponse.getStatusLine().getStatusCode()==200){    // String result= EntityUtils.toString(httpResponse.getEntity());     BufferedReader input1= new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())) ;     StringBuilder sb= new StringBuilder();        for(String s=input1.readLine();s!=null;s=input1.readLine()){      sb.append(s);     }     String result=sb.toString();     System.out.println("result="+result);     JSONArray jsonArray= new JSONArray("["+result+"]");    // String message=null;     StringBuilder message=new StringBuilder();     for(int i=0;i<jsonArray.length();i++){      JSONObject jsonObject= jsonArray.getJSONObject(i);      if(jsonObject!=null){       String errorCode=jsonObject.getString("errorCode");            if(errorCode.equals("0")){           String query= jsonObject.getString("query");       //message=query;      message.append(query);        String translation=jsonObject.getString("translation");       // message+="\t"+translation;        message.append("\t"+translation);        //有道词典-基本词典        if(jsonObject.has("basic")){         JSONObject basic=jsonObject.getJSONObject("basic");         if(basic.has("phonetic")){          String phonetic=basic.getString("phonetic");         // message+="\n\t"+phonetic;          message.append("\n\t音标:["+phonetic+"]");         }         if(basic.has("explains")){          String explains=basic.getString("explains");          //message+="\n\t"+explains;          message.append("\n\t"+explains);         }        }        if(jsonObject.has("web")){         String web=jsonObject.getString("web");         JSONArray webstring= new JSONArray("["+web+"]");        // message+="\n网络释义:";         message.append("\n网络释义:");         JSONArray webArray= webstring.getJSONArray(0);         int count=0;         while(!webArray.isNull(count)){          if(webArray.getJSONObject(count).has("key")){           String key=webArray.getJSONObject(count).getString("key");           //message+="\n\t<"+(count+1)+">"+key;           message.append("\n\t<"+(count+1)+">"+key);                    }          if(webArray.getJSONObject(count).has("value")){           String value=webArray.getJSONObject(count).getString("value");           //message+="\n\t "+value;           message.append("\n\t "+value);                    }          count++;         }                }                    }       if(errorCode.equals("20")){        Toast.makeText(getApplicationContext(), "要翻译的文本过长", Toast.LENGTH_LONG).show();       }       if(errorCode.equals("30")){       Toast.makeText(getApplicationContext(), "无法进行有效的翻译 ", Toast.LENGTH_LONG).show();       }       if(errorCode.equals("40")){        Toast.makeText(getApplicationContext(), "不支持语言类型", Toast.LENGTH_LONG).show();       }       if(errorCode.equals("50")){        Toast.makeText(getApplicationContext(), "无效的Key", Toast.LENGTH_LONG).show();       }      }else{     Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();       }     }     searchresult.setText(message.toString());        }    else{     Toast.makeText(getApplicationContext(), "提取异常", Toast.LENGTH_LONG).show();    }  }    }  

  }

        
           
 
         
        
 
         
 
       
    

Manifest.xml

“联网权限”一定要设置不然会报网络连接异常。

 

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.youdaotranslationdemo"     android:versionCode="1"     android:versionName="1.0" >

    <uses-sdk         android:minSdkVersion="8"         android:targetSdkVersion="8" /> <uses-permission  android:name="android.permission.INTERNET"/> <uses-permission  android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission  android:name="android.permission.ACCESS_WIFI_STATE"/>     <application         android:allowBackup="true"         android:icon="@drawable/ic_launcher"         android:label="@string/app_name"         android:theme="@style/AppTheme" >         <activity             android:name="com.example.youdaotranslationdemo.MainActivity"             android:label="@string/app_name" >             <intent-filter>                 <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application>

</manifest>

 最后,需要说明的是该版本不可以在android3.0以后运行,因为android3.0以上需要把联网操作放进线程中去操作,因此在mainfast的中将targetSdkVersion设为8,可以正常运行。

如果有什么问题可以留言,共同学习。。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值