Android基础工具函数代码集

整理在学习研究Android开发,编写了一些基本用到的工具集,现在整理分享(后续会持续更新,有问题还请指出)。

1、HttpClient工具,使用Apache的HttpClient类实现get和post方法

 1 import java.io.IOException;
 2 import java.io.UnsupportedEncodingException;
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.apache.http.HttpEntity;
 7 import org.apache.http.HttpResponse;
 8 import org.apache.http.NameValuePair;
 9 import org.apache.http.ParseException;
10 import org.apache.http.client.ClientProtocolException;
11 import org.apache.http.client.HttpClient;
12 import org.apache.http.client.entity.UrlEncodedFormEntity;
13 import org.apache.http.client.methods.HttpGet;
14 import org.apache.http.client.methods.HttpPost;
15 import org.apache.http.impl.client.DefaultHttpClient;
16 import org.apache.http.message.BasicNameValuePair;
17 import org.apache.http.protocol.HTTP;
18 import org.apache.http.util.EntityUtils;
19 
20 public class HttpUtil {
21     
22     public static String httpGet(String url) {
23         String response = null;
24         try {
25             HttpClient httpClient = new DefaultHttpClient();
26             HttpGet httpGet = new HttpGet(url);
27             HttpResponse httpResponse = httpClient.execute(httpGet);
28             if (null != httpResponse) {
29                 int status = httpResponse.getStatusLine().getStatusCode();
30                 if (HTTP_OK == status) {
31                     HttpEntity httpEntity = httpResponse.getEntity();
32                     response = EntityUtils.toString(httpEntity, HTTP.UTF_8);
33                 } else {
34                     response = ("错误码:" + status);
35                 }
36             }
37         } catch (ClientProtocolException e) {
38             e.printStackTrace();
39         } catch (IOException e) {
40             e.printStackTrace();
41         }
42         
43         return response;
44     }
45     
46     public static String httpPost(String url, List<HttpPostParam> params) {
47         String response = null;
48         try {
49             HttpClient httpClient = new DefaultHttpClient();
50             HttpPost httpPost = new HttpPost(url);
51             
52             if (null != params) {
53                 if (params.size() > 0) {
54                     List<NameValuePair> pairsList = new ArrayList<NameValuePair>();
55                     for (int i = 0; i < params.size(); i++) {
56                         HttpPostParam param = params.get(i);
57                         NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
58                         pairsList.add(pair);
59                     }
60                     httpPost.setEntity(new UrlEncodedFormEntity(pairsList, HTTP.UTF_8));
61                 }
62             }
63             
64             HttpResponse httpResponse = httpClient.execute(httpPost);
65             if (null != httpResponse) {
66                 int status = httpResponse.getStatusLine().getStatusCode();
67                 if (HTTP_OK == status) {
68                     HttpEntity httpEntity = httpResponse.getEntity();
69                     response = EntityUtils.toString(httpEntity, HTTP.UTF_8);
70                 } else {
71                     response = ("错误码:" + status);
72                 }
73             }
74         } catch (UnsupportedEncodingException e) {
75             e.printStackTrace();
76         }catch (ClientProtocolException e) {
77             e.printStackTrace();
78         } catch (ParseException e) {
79             e.printStackTrace();
80         }catch (IOException e) {
81             e.printStackTrace();
82         }
83         
84         return response;
85     }
86     
87     private final static int HTTP_OK = 200;
88 }
View Code

post方法自定义了传入的参数结构

 1 public class HttpPostParam {
 2         
 3     public HttpPostParam() {
 4     }
 5     
 6     public HttpPostParam(String key, String value) {
 7         this.key = key;
 8         this.value = value;
 9     }
10     public String getKey() {
11         return key;
12     }
13     public void setKey(String key) {
14         this.key = key;
15     }
16     public String getValue() {
17         return value;
18     }
19     public void setValue(String value) {
20         this.value = value;
21     }
22     
23     @Override
24     public String toString() { //转为json格式
25         return "{key=" + this.key + ",value=" + this.value + "}";
26     }
27 
28     private String key = null;
29     private String value = null;
30 }
View Code

2、Json基本操作工具,使用GSON和JAVA中的JSONObject对范型进行操作实现

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class JsonUtil {
    /**
     * 对象T转为json字符串
     * @param t
     * @return json字符串
     */
    public static <T> String beanToJson(T t) {
        Gson gson = new Gson();
        return gson.toJson(t);
    }
    
    /**
     * json字符串转为对象T
     * @param json
     * @param cls
     * @return 对象T
     */
    public static <T> T jsonToBean(String json, Class<T> cls) {
        Gson gson = new Gson();
        return gson.fromJson(json, cls);
    }
    
    /**
     * 对象T列表转为json字符串数组
     * @param list
     * @returnjson字符串数组
     */
    public static <T> String beanlistToJson(List<T> list) {
        Gson gson = new Gson();
        return gson.toJson(list);
    }
    
        /**
     * json字符串数组转为对象T列表
     * @param json
     * @param type
     * @return 对象T列表
     */
    public static <T> List<T> jsonToBeanlist(String json, TypeToken<T> type) {
        Gson gson = new Gson();
        return gson.fromJson(json, type.getType());
    }
    
    /**
     * json字符串转为json对象
     * @param json
     * @return json对象
     */
    public static JSONObject jsonToObject(String json) {
        try {
            return new JSONObject(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * json对象转为json字符串
     * @param object
     * @return json字符串
     */
    public static String objectToJson(JSONObject object) {
        return object.toString();
    }
}
View Code

3、从网络获取图片资源对象,使用HttpURLConnection实现

 1 /**
 2      * 从网络URL获取图片
 3      * @param imgUrl
 4      * @return 图片对象
 5      */
 6     public static Bitmap getBitmap(String imgUrl) {
 7         Bitmap bitmap = null;
 8         try {
 9             URL url = new URL(imgUrl);
10             HttpURLConnection connection = (HttpURLConnection)url.openConnection();
11             connection.setDoInput(true);
12             connection.connect();
13             InputStream iStream = connection.getInputStream();
14             bitmap = BitmapFactory.decodeStream(iStream);
15             iStream.close();
16         } catch (Exception e) {
17             e.printStackTrace();
18         }
19         return bitmap;
20     }
View Code

4、将Toast信息放到后台Activity的UI线程中,可实现Toast信息的快速刷新

 1 /**
 2      * 在后台显示前台Toast信息
 3      * @param activity
 4      * @param message
 5      */
 6     public static void showToast(final Activity activity, final String message) {
 7         activity.runOnUiThread(new Runnable() {
 8             public void run() {
 9                 if (null != mToast) {
10                     mToast.cancel();
11                     mToast = null;
12                 }
13                 mToast = Toast.makeText(activity, message, Toast.LENGTH_LONG);
14                 mToast.show();
15             }
16         });
17     }
18     
19     private static Toast mToast = null;
View Code

5、XML信息解析,使用DOM和SAX实现

  DOM实现:

 1 import java.io.File;
 2 import java.io.InputStream;
 3 import java.util.List;
 4 
 5 public class DOMParseInstance {
 6     public static List<Object> parse(InputStream iStream) {
 7         return new DOMHandler().parse(iStream);
 8     }
 9     
10     public static List<Object> parse(File file) {
11         return new DOMHandler().parse(file);
12     }
13     
14     public static List<Object> parse(String xml) {
15         return new DOMHandler().parse(xml);
16     }
17 }
View Code
 1 import java.io.File;
 2 import java.io.InputStream;
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import javax.xml.parsers.DocumentBuilder;
 7 import javax.xml.parsers.DocumentBuilderFactory;
 8 
 9 import org.w3c.dom.Document;
10 import org.w3c.dom.Element;
11 import org.w3c.dom.Node;
12 import org.w3c.dom.NodeList;
13 
14 public class DOMHandler {
15     public List<Object> parse(InputStream iStream) {
16         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
17         try {
18             DocumentBuilder builder = factory.newDocumentBuilder();
19             Document document = builder.parse(iStream);
20             return parseDocument(document);
21         } catch (Exception e) {
22             e.printStackTrace();
23         }
24         return null;
25     }
26     
27     public List<Object> parse(File file) {
28         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
29         try {
30             DocumentBuilder builder = factory.newDocumentBuilder();
31             Document document = builder.parse(file);
32             return parseDocument(document);
33         } catch (Exception e) {
34             e.printStackTrace();
35         }
36         return null;
37     }
38     
39     public List<Object> parse(String xml) {
40         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
41         try {
42             DocumentBuilder builder = factory.newDocumentBuilder();
43             Document document = builder.parse(xml);
44             return parseDocument(document);
45         } catch (Exception e) {
46             e.printStackTrace();
47         }
48         return null;
49     }
50     
51     private List<Object> parseDocument(Document document) {
52         if (null == document) {
53             return null;
54         }
55         
56         //注意这里的数据类型,需要修改
57         List<Object> xmlList = new ArrayList<>();
58         Element rootElement = document.getDocumentElement(); //根节点
59         if (rootElement.hasChildNodes()) { //存在子节点
60             NodeList nodeList = rootElement.getChildNodes();
61             for (int i = 0; i < nodeList.getLength(); i++) {    //遍历子节点
62                 //由于XML是标准格式的XML,DOM在解析时会将/n /t当做一个节点
63                 //判断当前NodeList中的子项是否为Element对象实例,否则强制类型转换就异常
64                 if (nodeList.item(i) instanceof Element) { 
65                     Element node = (Element)nodeList.item(i);
66                     if (null != node) {    //获取到一个节点,判断节点的名称是否为需要的节点名称
67                         
68                         
69                         //如果有子节点,可以继续遍历子节点
70                         //遍历节点Person下的所有子节点
71                         NodeList childList = node.getChildNodes();
72                         for (int j = 0; j < childList.getLength(); j++) {
73                             Node childNode = childList.item(j);
74                             if (null != childNode) {
75                                 if (Node.ELEMENT_NODE == childNode.getNodeType()) { //判断是否为节点
76                                     //子节点信息
77                                 }
78                             }
79                         }
80                     }
81                 }
82             }
83         }
84         
85         return xmlList;
86     }
87 }
View Code

  SAX实现:

 1 import java.io.File;
 2 import java.io.IOException;
 3 import java.io.InputStream;
 4 
 5 import javax.xml.parsers.ParserConfigurationException;
 6 import javax.xml.parsers.SAXParser;
 7 import javax.xml.parsers.SAXParserFactory;
 8 
 9 import org.xml.sax.SAXException;
10 import org.xml.sax.helpers.DefaultHandler;
11 
12 public class SAXParseInstance {
13     
14     public static void prase(String xml, DefaultHandler handler) {
15         try {
16             getInstance().parse(xml, handler);
17         } catch (SAXException e) {
18             e.printStackTrace();
19         } catch (IOException e) {
20             e.printStackTrace();
21         }
22     }
23     
24     public static void prase(InputStream iStream, DefaultHandler handler) {
25         try {
26             getInstance().parse(iStream, handler);
27         } catch (SAXException e) {
28             e.printStackTrace();
29         } catch (IOException e) {
30             e.printStackTrace();
31         }
32     }
33     
34     public static void prase(File file, DefaultHandler handler) {
35         try {
36             getInstance().parse(file, handler);
37         } catch (SAXException e) {
38             e.printStackTrace();
39         } catch (IOException e) {
40             e.printStackTrace();
41         }
42     }
43     
44     private static SAXParser getInstance() {
45         try {
46             return SAXParserFactory.newInstance().newSAXParser();
47         } catch (ParserConfigurationException e) {
48             e.printStackTrace();
49         } catch (SAXException e) {
50             e.printStackTrace();
51         }
52         return null;
53     }
54 }
View Code
 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 import org.xml.sax.Attributes;
 5 import org.xml.sax.SAXException;
 6 import org.xml.sax.helpers.DefaultHandler;
 7 
 8 public class SAXHandler extends DefaultHandler{
 9 
10     public List<Object> getXmList() {
11         return xmlList;
12     }
13     
14     @Override
15     public void startDocument() throws SAXException {
16         //申请xml数据列表内存
17         xmlList = new ArrayList<>();
18         
19         super.startDocument();
20     }
21 
22     @Override
23     public void endDocument() throws SAXException {
24         //结束,可以做一些尾部处理
25         
26         super.endDocument();
27     }
28 
29     @Override
30     public void startElement(String uri, String localName, String qName,
31             Attributes attributes) throws SAXException {
32         //进入一个子节点,可以根据qName判断是那个节点,在这里可以申请子节点的内存信息
33         
34         
35         
36         tagName = qName;
37         super.startElement(uri, localName, qName, attributes);
38     }
39 
40     @Override
41     public void endElement(String uri, String localName, String qName)
42             throws SAXException {
43          //根据uri判断是那个前缀,qName判断是那个节点,将解析的数据放入列表
44         
45         
46         
47         tagName = null;
48         super.endElement(uri, localName, qName);
49     }
50 
51     @Override
52     public void characters(char[] ch, int start, int length)
53             throws SAXException {
54         if (null != tagName) { //有子节点
55             String data = new String(ch, start, length); //节点的数据
56             //根据tagName的节点判断是那个节点信息,然后获取对应类型的数据
57             
58         }
59         super.characters(ch, start, length);
60     }
61 
62     private String tagName = null;            //标记当前节点
63     //这里的数据类型需要修改
64     private List<Object> xmlList = null;    //xml信息列表
65 }
View Code

6、Android内部与SD卡一些操作

 1 import java.io.File;
 2 import java.text.DecimalFormat;
 3 
 4 import android.os.Environment;
 5 
 6 public class Utils {
 7     /**
 8      * 获取内部存储路径
 9      * @return 路径
10      */
11     public static String getInnerSDCardPath() {
12         return Environment.getExternalStorageDirectory().getPath();
13     }
14     
15     /**
16      * 获取SD卡存储路径
17      * @return 路径
18      */
19     public static String getExtSDCardPath() {
20          File dir = null;
21          if (getSDCardEnable()) {
22              dir = Environment.getExternalStorageDirectory();//获取跟目录
23          }
24          return dir.toString();
25     }
26     
27     /**
28      * SD卡是否可用
29      * @return
30      */
31     public static boolean getSDCardEnable() {
32         String status = Environment.getExternalStorageState();
33         if (status.equals(Environment.MEDIA_MOUNTED)) {
34             return true;
35         }
36         return false;
37     }
38     
39     /**
40      * 创建目录
41      * @param path
42      */
43     public static void makeDirs(String path) {
44         File file = new File(path);
45         if (!file.exists()) {
46             file.mkdirs();
47         }
48     }
49     
50     /**
51      * 字节大小转换
52      * @param value
53      * @return
54      */
55     public static String convertByte(String value) {
56         String strRet = null;
57         Float fValue = Float.valueOf(value);
58         float fByte = fValue.floatValue();
59         
60         DecimalFormat decimalFormat = new DecimalFormat(".0"); //精确度为小数点后1位
61         if (fByte >= G_NUM) {
62             strRet = decimalFormat.format(fByte/G_NUM) + "GB";
63         } else if (fByte >= M_NUM) {
64             strRet = decimalFormat.format(fByte/M_NUM) + "MB";
65         } else if (fByte >= K_NUM) {
66             strRet = decimalFormat.format(fByte/K_NUM) + "KB";
67         } else if (fByte >= B_NUM) {
68             strRet = decimalFormat.format(fByte/B_NUM) + "B";
69         }
70         
71         return strRet;
72     }
73     
74     private static final long B_NUM = 1024;
75     private static final long K_NUM = B_NUM * 1024;
76     private static final long M_NUM = K_NUM * 1024;
77     private static final long G_NUM = M_NUM * 1024;
78 }
View Code

 

posted on 2017-02-21 09:48  跑的比兔子还快的乌龟  阅读(482)  评论(0编辑  收藏  举报

导航