第1种:SharePreference 数据存储
1.存贮SharePreference数据
try{
//我们选择存贮在SD卡上,所以当在SD不存在的时候,我们会捕获一下
//可以设置Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限
sp = SharePerferenceActivity.this.getSharedPreferences("nagi", Context.MODE_PRIVATE);
//得到可编辑对象
Editor edit = sp.edit();
edit.putString("name", "毅神");
edit.putString("school", "北京工商大学");
edit.putInt("age", 22);
//最后在我们编辑完之后,一定提交
edit.commit();
filepath.setText("文件成功创建:data/data/"+getApplication().getPackageName()+"/shared_prefs/nagi.xml");
}catch(Exception e){
e.printStackTrace();
}
2.读取SharePreference数据
try{
sp = SharePerferenceActivity.this.getSharedPreferences("nagi", Context.MODE_PRIVATE);
if(sp == null){
showToast("你先创建sharePreference参数文件");
}else{
//getObject 是一个缺省值,如果sharepreference的key 不存在的话,返回第二个值
String name = sp.getString("name", "名字不存在");
String school = sp.getString("school", "");
int age = sp.getInt("age", 1);
filepath.setText("name="+name+",school="+school+",age="+age);
}
}catch(Exception e){
e.printStackTrace();
Log.i(TAG, "读取SD卡失败");
}
第2种:使用缓存保存数据
//保存用户名和密码到缓存中
private void saveToCashe(Context context, String name, String pd) {
try {
//得到data/data/包名/cachesfile/路径
File cashePath = context.getCacheDir();
File saveCashe = new File(cashePath,"user.txt");
FileOutputStream out = new FileOutputStream(saveCashe);
out.write((name+"##"+pd).getBytes());
out.close();
Log.i(tag, "已经成功的保存到缓存");
} catch (Exception e) {
e.printStackTrace();
Log.i(tag, "保存异常");
}
}
/**
*读取用户名和密码
* @param context
* @return
*/
private Map<String,String> loadDataFromCashe(Context context){
try {
File cashePath = context.getCacheDir();
File saveFile = new File(cashePath,"user.txt");
//将读取到数据保存到了Map集合中
Map<String,String> map = new HashMap<String, String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(saveFile)));
String result = reader.readLine();
String[] file = result.split("##");
map.put("name", file[0]);
map.put("password", file[1]);
reader.close();
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
第3种:文件数据的访问和存贮
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
import android.os.Environment;
public class FileService {
private Context context;
public FileService(Context context) {
this.context = context;
}
/**
* 以私有文件保存内容
* @param filename 文件名称
* @param content 文件内容
* @throws Exception
*/
public void saveToSDCard(String filename, String content) throws Exception{
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(content.getBytes());
outStream.close();
}
/**
* 以私有文件保存内容
* @param filename 文件名称
* @param content 文件内容
* @throws Exception
*/
public void save(String filename, String content) throws Exception{
FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
outStream.write(content.getBytes());
outStream.close();
}
/**
* 以追加方式保存内容
* @param filename 文件名称
* @param content 文件内容
* @throws Exception
*/
public void saveAppend(String filename, String content) throws Exception{// ctrl+shift+y / x
FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_APPEND);
outStream.write(content.getBytes());
outStream.close();
}
/**
* 保存内容,注:允许其他应用从该文件中读取内容
* @param filename 文件名称
* @param content 文件内容
* @throws Exception
*/
public void saveReadable(String filename, String content) throws Exception{
FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
outStream.write(content.getBytes());
outStream.close();
}
/**
* 保存内容,注:允许其他应用往该文件写入内容
* @param filename 文件名称
* @param content 文件内容
* @throws Exception
*/
public void saveWriteable(String filename, String content) throws Exception{
FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_WORLD_WRITEABLE);
outStream.write(content.getBytes());
outStream.close();
}
/**
* 保存内容,注:允许其他应用对该文件读和写
* @param filename 文件名称
* @param content 文件内容
* @throws Exception
*/
public void saveRW(String filename, String content) throws Exception{
FileOutputStream outStream = context.openFileOutput(filename,
Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE);
outStream.write(content.getBytes());
outStream.close();
}
/**
* 读取文件内容
* @param filename 文件名称
* @return
* @throws Exception
*/
public String readFile(String filename) throws Exception{
FileInputStream inStream = context.openFileInput(filename);
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
while( (len = inStream.read(buffer))!= -1){
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();//得到文件的二进制数据
outStream.close();
inStream.close();
return new String(data);
}
}
第4种: Internet读取数据存储数据
1.internet 读取数据
//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
URL url = new URL("http://www.sohu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);//设置连接超时
conn.setRequestMethod(“GET”);//以get方式发起请求
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();//得到网络返回的输入流
String result = readData(is, "GBK");
conn.disconnect();
//第一个参数为输入流,第二个参数为字符集编码
public static String readData(InputStream inSream, String charsetName) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String(data, charsetName);
}
2.向internet 发送请求参数1
//利用HttpURLConnection对象,我们可以向网络发送请求参数.
String requestUrl = "http://localhost:8080/nagi/contanctmanage.do";
Map<String, String> requestParams = new HashMap<String, String>();
requestParams.put("age", "12");
requestParams.put("name", "中国");
StringBuilder params = new StringBuilder();
for(Map.Entry<String, String> entry : requestParams.entrySet()){
params.append(entry.getKey());
params.append("=");
params.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
params.append("&");
}
if (params.length() > 0) params.deleteCharAt(params.length() - 1);
byte[] data = params.toString().getBytes();
URL realUrl = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setDoOutput(true);//发送POST请求必须设置允许输出
conn.setUseCaches(false);//不使用Cache
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");//维持长连接
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(data);
outStream.flush();
if( conn.getResponseCode() == 200 ){
String result = readAsString(conn.getInputStream(), "UTF-8");
outStream.close();
System.out.println(result);
}
3.向internet 发送请求参数2
public static void PostData() throws Exception{
String requestUrl = "http://192.168.18.114:80/Web2/servlet/ServerServlet";
StringBuilder build = new StringBuilder();
Map<String,String> map = new HashMap<String,String>();
map.put("name", "de");
map.put("pass", "123");
Set<Entry<String, String>> set = map.entrySet();
for(Entry<String, String> e :set){
build.append(e.getKey());
build.append("=");
build.append(e.getValue());
build.append("&");
}
build = build.deleteCharAt(build.length()-1);
String data = build.toString();
URL url = new URL(requestUrl);
//建立连接
HttpURLConnection http = (HttpURLConnection)url.openConnection();
//设置连接时间
http.setConnectTimeout(4000);
//设置请求方法
http.setRequestMethod("POST");
//支持 doInput 和 doOutput
http.setDoInput(true);
http.setDoOutput(true);
//不支持缓存
http.setUseCaches(false);
http.setRequestProperty("Accept",
"*/*");
http.setRequestProperty("Accept-Language",
"zh-cn");
http.setRequestProperty("Referer",
"let you guess...");
http.setRequestProperty("User-Agent",
"let you guess");
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setRequestProperty("Accept-Encoding",
"gzip, deflate");
http.setRequestProperty("Host",requestUrl);
http.setRequestProperty("Content-Length",
String.valueOf("hello gay".getBytes().length));
http.setRequestProperty("Connection",
"Keep-Alive");
http.setRequestProperty("Cache-Control",
"no-cache");
OutputStream outputStream = http.getOutputStream();
outputStream.write(data.getBytes());
int responseCode = http.getResponseCode();
if(responseCode==200) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream is = http.getInputStream();
int len = 0;
byte[] buff = new byte[64];
while((len=is.read(buff)) != -1){
out.write(buff, 0, len);
out.flush();
}
//打印出结果
String result = new String(out.toByteArray(),"UTF-8");
out.close();
System.out.println(result);
}
outputStream.close();
}
4.向Internet 发送XML数据
//利用HttpURLConnection对象,我们可以向网络发送xml数据.
StringBuilder xml = new StringBuilder();
xml.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
xml.append("<M1 V=10000>");
xml.append("<U I=1 D=\"N73\">中国</U>");
xml.append("</M1>");
byte[] xmlbyte = xml.toString().getBytes("UTF-8");
URL url = new URL("http://localhost:8080/itcast/contanctmanage.do?method=readxml");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);
conn.setDoOutput(true);//允许输出
conn.setUseCaches(false);//不使用Cache
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");//维持长连接
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length));
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(xmlbyte);//发送xml数据
outStream.flush();
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();//获取返回数据
String result = readAsString(is, "UTF-8");
outStream.close();
5.使用Anroid 封装好的HttpUtils
//get形式
public static String getResultForHttpGet(String url) throws ClientProtocolException, IOException
{
String result="";
HttpGet httpGet=new HttpGet(url);//编者按:与HttpPost区别所在,这里是将参数在地址中传递
HttpResponse response=new DefaultHttpClient().execute(httpGet);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
result=EntityUtils.toString(entity, HTTP.UTF_8);
}
return result;
}
/**
* HttpApache工具类
* @author dell
*/
public class HttpApacheFac {
private static String CharSet = HTTP.UTF_8;
private static HttpClient client = null;
//拿到默认HttpClient服务器客户端
public static synchronized HttpClient getHttpClient(){
if(client==null){
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,CharSet);
HttpProtocolParams.setUseExpectContinue(params,true);
//HttpProtocolParams.setUserAgent(params,"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
//+"AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
ConnManagerParams.setMaxConnectionsPerRoute(params,new ConnPerRouteBean(100));
ConnManagerParams.setTimeout(params,10000);
HttpConnectionParams.setConnectionTimeout(params,15000);
HttpConnectionParams.setSoTimeout(params,15000);
SchemeRegistry shm = new SchemeRegistry();
shm.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
shm.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,shm),params);
}
return client;
}
public static void closeHttpClient(){
if(client!=null){
client.getConnectionManager().shutdown();
}
}
public static HttpClient getHttps(String sslKeyPath,String host,String username,String password){
HttpClient client = null;
try{
client = new DefaultHttpClient();
SSLSocketFactory socket = null;
Scheme shm = null;
if(sslKeyPath!=null&&!sslKeyPath.equals("")){
File keyFile = new File(sslKeyPath);
if(keyFile.exists()&&keyFile.isFile()){
KeyStore key = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream fis = new FileInputStream(keyFile);
key.load(fis,"password".toCharArray());
fis.close();
socket = new SSLSocketFactory(key);
shm = new Scheme("https",socket,443);
}
}
if(socket==null){
shm = new Scheme("https",SSLSocketFactory.getSocketFactory(),443);
}
client.getConnectionManager().getSchemeRegistry().register(shm);
if(host!=null&&username!=null&&password!=null){
((AbstractHttpClient)client).getCredentialsProvider().setCredentials(new AuthScope(host,443),new UsernamePasswordCredentials(username,password));
}
}catch(Exception e){
e.printStackTrace();
}
return client;
}
/**
* 封装数据到Map对象
* 发送数据
* @param url
* @param argVals
* @return
*/
public static String doPost(String url,HashMap<String,Object>argVals){
try{
if(url==null){
return null;
}
HttpPost post = new HttpPost(url);
if(argVals!=null&&argVals.size()>0){
ArrayList<NameValuePair>args = new ArrayList<NameValuePair>();
for(Entry<String,Object>e:argVals.entrySet()){
NameValuePair arg = new BasicNameValuePair(e.getKey(),e.getValue().toString());
args.add(arg);
}
post.setEntity(new UrlEncodedFormEntity(args,CharSet));
}
HttpResponse resp = HttpApacheFac.getHttpClient().execute(post);
if(resp.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
HttpEntity res = resp.getEntity();
if(res!=null){
return EntityUtils.toString(res,CharSet);
}
}else{
post.abort();
}
}catch(Exception e){
e.printStackTrace();
return "请求异常";
}
return null;
}
/**
* 得到Coookies
* @param url
* @return
*/
public static String getCookies(String url){
StringBuffer res = new StringBuffer();
try{
//直接获得了CookieStore对象
CookieStore store = new BasicCookieStore();
//http上下文 绑定了request response application 的上下文数据
//可以理解为保存对象域
HttpContext con = new BasicHttpContext();
con.setAttribute(ClientContext.COOKIE_STORE,store);
HttpGet get = new HttpGet(url);
HttpResponse resp = HttpApacheFac.getHttpClient().execute(get,con);
res.append("请求返回状态信息:"+resp.getStatusLine()+"\n");
//将返回数据封装成为一个Entiy 对象
HttpEntity entity = resp.getEntity();
if(entity!=null){
res.append("请求返回信息长度:"+entity.getContentLength()+"\n");
}
//得到所有的头信息
Header[]headers = resp.getAllHeaders();
int i = 0;
for(i=0;i<headers.length;i++){
res.append("Header-"+i+"内容:"+headers[i]+"\n");
}
res.append("头消息共计"+i+"条\n");
List<Cookie>cookies = store.getCookies();
for(i=0;i<cookies.size();i++){
res.append("Cookie-"+i+"内容:"+cookies.get(i).toString()+"\n");
}
res.append("Cookie共计"+i+"个");
}catch(Exception e){
e.printStackTrace();
return "请求异常";
}
return res.toString();
}
}
第5种:Intent存贮数据
第6种:内容提供者存贮数据
第7种:数据库存贮和访问
未完!!!!