包裹俠-快遞單號查詢App

Dseai_發表於2016-11-27

首先我是使用了易源介面,所以要去申請介面。在官方網站註冊號帳號後使用介面流程都有官方文件介紹

然後記下自己的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地址

相關文章