首先我是使用了易源接口,所以要去申请接口。在官方网站注册号帐号后使用接口流程都有官方文档介绍
然后记下自己的appid和secret
找到接口
主要有两个Activity
MainActivity 主要是输入账号查询界面 还包括下面的历史纪录的一个listview
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private EditText editText_id;
private AutoCompleteTextView edittext_name;
private TextView textView;
private TextInputLayout textInputLayout_id;
private ListView listView;
private HistoryDataBase myDataBase;
private LayoutInflater layoutInflater;
private ArrayList<Express> arrayList;
ImageView imageView;
Map map;
List list;
Intent news_intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
init();
}
public void init(){
textView = (TextView)findViewById(R.id.text);
editText_id = (EditText)findViewById(R.id.edittext_id);
edittext_name = (AutoCompleteTextView)findViewById(R.id.edittext_name);
textInputLayout_id=(TextInputLayout)findViewById(R.id.textinputlayout_id);
Button button_query=(Button)findViewById(R.id.button_query);
button_query.setOnClickListener(this);
imageView = (ImageView)findViewById(R.id.image_main);
layoutInflater= getLayoutInflater();
myDataBase=new HistoryDataBase(this);
arrayList=myDataBase.getArray();
listView=(ListView)findViewById(R.id.listView1);
final HistoryAdapter historyAdapter=new HistoryAdapter(layoutInflater,arrayList);
listView.setAdapter(historyAdapter);
/**
* 点击条目查询
*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
editText_id.setText(arrayList.get(i).getExpressNumber());
edittext_name.setText(arrayList.get(i).getExpressName());
}
});
/**
* 长按可删除
*/
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(final AdapterView<?> adapterView, View view, final int position, long l) {
new AlertDialog.Builder(MainActivity.this ).setTitle("删除").setMessage("确定删除这条记录吗?")
.setNegativeButton("取消",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
myDataBase.deleteNote(arrayList.get(position).getId());
arrayList=myDataBase.getArray();
HistoryAdapter historyAdapter1=new HistoryAdapter(layoutInflater,arrayList);
listView.setAdapter(historyAdapter1);
}
}).create().show();
return true;
}
});
news_intent = new Intent(MainActivity.this,NewsActivity.class);
editText_id.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
//检测错误输入,当输入错误时,hint会变成红色并提醒
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//检查实际是否匹配,由自己实现
if (checkType(charSequence.toString())) {
textInputLayout_id.setErrorEnabled(true);
// textInputLayout_id.setError("请检查格式");
return;
} else {
textInputLayout_id.setErrorEnabled(false);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
getcompany();
ArrayAdapter arrayAdapter;//输入提示
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, list);
edittext_name.setAdapter(arrayAdapter);
}
public boolean checkType(String check){
for(int i=0;i<check.length();i++){
if(check.charAt(i)>'9'||check.charAt(i)<'0')return true;
}
return false;
}
@Override
public void onClick(View v) {
String string_editext_name = edittext_name.getText().toString();
String string_edittext_id= editText_id.getText().toString();
Express express = (Express) map.get(string_editext_name);
/**
* 插入到数据库
*/
Express express1=new Express(string_edittext_id,string_editext_name);
myDataBase.toInsert(express1);
arrayList=myDataBase.getArray();
HistoryAdapter historyAdapter1=new HistoryAdapter(layoutInflater,arrayList);
listView.setAdapter(historyAdapter1);
if(express!=null){
news_intent.putExtra("logo",express.getLogo());
news_intent.putExtra("name",express.getExpressName());
news_intent.putExtra("num", string_edittext_id);
startActivity(news_intent);
}
else Toast.makeText(MainActivity.this,"查询不到此快递公司",Toast.LENGTH_SHORT).show();
}
public void getcompany(){
GetCompany getCompany=new GetCompany(MainActivity.this,R.raw.company);
list =getCompany.getList();
map=getCompany.getMap();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
NewsActivity 主要是查询结果的展示界面 在此activity中有发送网络请求得到数据 并通过listview展示出来。其中 为了简单明了 把发送网络请求和得到快递公司的信息通过另外两个类GetContext和Getcompany 实现
public class NewsActivity extends AppCompatActivity {
private final int SHOW_MESSAGE=1;
private final int ShOW_IMAGE=2;
private List<Listitem> list = new ArrayList<Listitem>();
ImageView imageView;
ListView listView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newsshow);
init();
}
public void init(){
imageView=(ImageView)findViewById(R.id.image_newsshow);
TextView textView = (TextView)findViewById(R.id.text_newsshow);
listView= (ListView) findViewById(R.id.list_newsshow);
Intent intent=getIntent();
String name=intent.getStringExtra("name");
final String logo=intent.getStringExtra("logo");
String num=intent.getStringExtra("num");
textView.setText("快递单号:" + num );
sendRestWidthHttpClient(name,num);
new Thread(new Runnable() {
@Override
public void run() {
GetImage getImage=new GetImage(logo);
Message message = new Message();
message.obj=getImage.getBitmap();
message.what=ShOW_IMAGE;
handler.sendMessage(message);
}
}).start();
}
/**
* @param name 快递名称
* @param id 快递单号
*/
private void sendRestWidthHttpClient(final String name, final String id){
new Thread(new Runnable() {
@Override
public void run() {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
//String appid="25388";//要替换成自己的
// String secret="1d1dc90eebee41e8ae8566ea56b7ff47";//要替换成自己的
String s=df.format(new Date()).toString();
System.out.print(s);
GetContext getContext=new GetContext("http://route.showapi.com/64-19?com="+name+"&nu="+id+"&showapi_appid=25388&showapi_timestamp="+df.format(new Date())+"&showapi_sign=1d1dc90eebee41e8ae8566ea56b7ff47");
String response = getContext.getResponse();
Message message = new Message();
message.obj=response;
message.what=SHOW_MESSAGE;
handler.sendMessage(message);
}
}).start();
}
private Handler handler =new Handler() {
public void handleMessage(Message msg){
Log.d("abc","yes");
switch (msg.what){
case SHOW_MESSAGE:
String text = (String) msg.obj;
Log.d("abctext",text);
try {
JSONObject jsonObject= new JSONObject(text);
JSONObject showapi_res_body = jsonObject.getJSONObject("showapi_res_body") ;
String flag=showapi_res_body.getString("flag");
Log.d("abcflag", flag);
if(flag.equals("true")){
JSONArray data = showapi_res_body.getJSONArray("data");
for(int i=0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
String context=jsonObject1.getString("context"); //得到内容
String time= jsonObject1.getString("time"); //得到时间
int imageId,textcolor;
if(i==0) {
imageId = R.drawable.dian2;
textcolor = getResources().getColor(R.color.main_text);
}
else {
imageId=R.drawable.dian1;
textcolor=getResources().getColor(R.color.black);
}
list.add(new Listitem(imageId, context, time,textcolor));
Log.d("abc111",context+" "+time);
}
News_Adapter adapter = new News_Adapter(NewsActivity.this,R.layout.listitem,list);
listView.setAdapter(adapter);
}
else {
Toast.makeText(NewsActivity.this,"查询不到",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
case ShOW_IMAGE:Bitmap bitmap=(Bitmap)msg.obj;
imageView.setImageBitmap(bitmap);
}
}
};
}
GetContext类 主要通过在NewsActivity中传来的一个url进行网络访问并得到数据 response 转换为string传回给NewsActivity
注意:使用connection连接网络的getInputStream()方法,要把minSdkVersion设置到14以下,不然会得到空值。我就这个地方卡了好久 上网查了才知道的
public class GetContext {
private StringBuilder response;
public GetContext(String url){//给定访问的网址,返回网址内容
try{
URL myurl = new URL(url);
HttpURLConnection connection =(HttpURLConnection) myurl.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in=connection.getInputStream();
BufferedReader reader= new BufferedReader(new InputStreamReader(in));
response=new StringBuilder();
String line;
while((line=reader.readLine())!=null){
response.append(line);
}
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getResponse() {
return response.toString();
}
}
Getcompany
public class GetCompany {
private List list;
private Map map;
public List getList() {
return list;
}
public Map getMap() {
return map;
}
public GetCompany(Context context,int id){
list=new ArrayList();
map = new HashMap();
//得到资源中的Raw数据流
InputStream in = context.getResources().openRawResource(id);
/* 获取文件的大小(字节数) */
int length = 0;
JSONArray expressList = null;
try {
length = in.available();
byte[] buffer = new byte[length];
in.read(buffer);
//String result = EncodingUtils.getString(buffer, "UTF-8");
String text = new String(buffer,"utf-8");
Log.d("abc", text);
Log.d("abc","Yes");
JSONObject jsonObject= new JSONObject(text);
JSONObject showapi_res_body = jsonObject.getJSONObject("showapi_res_body") ;
expressList= showapi_res_body.getJSONArray("expressList");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
for(int i=0;i<expressList.length();i++){
JSONObject jsonObject1= null;
try {
jsonObject1 = expressList.getJSONObject(i);
String name=jsonObject1.getString("expName");
String simpleName=jsonObject1.getString("simpleName");
String logo=jsonObject1.getString("imgUrl");
list.add(name);
Express express=new Express();
express.setLogo(logo);
express.setExpressName(simpleName);
map.put(name, express);
Log.d("abc",name+" "+simpleName+" "+logo);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
GetImage
`public class GetImage {
private Bitmap bitmap;
public Bitmap getBitmap() {
return bitmap;
}
public GetImage(String url){
URL imgUrl = null;
try {
imgUrl = new URL(url);
//获得连接
HttpURLConnection conn=(HttpURLConnection)imgUrl.openConnection();
//设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
conn.setConnectTimeout(6000);
//连接设置获得数据流
conn.setDoInput(true);
//不使用缓存
conn.setUseCaches(false);
//这句可有可无,没有影响
//conn.connect();
//得到数据流
InputStream is = conn.getInputStream();
//解析得到图片
bitmap = BitmapFactory.decodeStream(is);
//关闭数据流
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
还有数据库的使用跟我上一篇记事本应用的差不多这里就不再列举出来详细的内容 其中 这里还需要一个raw文件用于保存 一下基本的快递公司的信息以及得到图片的网址
源码github地址