您的位置:首页 > 移动开发 > Android开发

Android 获取系统内存、保存解析xml demo

2014-05-05 11:10 288 查看
多了不说,直接看代码:(获取内存容量,貌似有点问题,在4.4版本测试没问题,其他版本好像要挂)



package com.gj.save;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import org.xmlpull.v1.XmlSerializer;

import com.gj.save.bean.User;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
}
public void save(View v){
Toast.makeText(this, MyUtils.getSDAvailableStorageSpace(this), 1).show();
}

public void save1(View v){
Toast.makeText(this, MyUtils.getSysAvailableStorageSpace(this), 1).show();
}
/**
* 使用SharedPreferences保存XML格式数据
* @param v
*/
public void save2(View v){
//在data/data/包/shared_prefs目录下创建info.xml
SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
Editor edit = sp.edit();
edit.putInt("id", 1);
edit.putBoolean("sex", false);
edit.putString("name", "zhangsan");
edit.commit();
}
/**
* 使用SharedPreferences方式读取数据
* @param v
*/
public void save3(View v){
//MODE_PRIVATE,私有文件
SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
//getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
String name = sp.getString("name", "");
Toast.makeText(this, "id:"+sp.getInt("id", 1)+"\tsex:"+sp.getBoolean("sex", true)+"\tname:"+sp.getString("name", ""), 1).show();
}
/**
* XML文件序列化
* @param v
*/
public void save4(View v){
try {
XmlSerializer serializer = Xml.newSerializer();
//getExternalStorageDirectory在SD卡下生成
File file = new File(Environment.getExternalStorageDirectory(),"backup.xml");
FileOutputStream fos = new FileOutputStream(file);
serializer.setOutput(fos, "utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "users");
/**------------------------*/
serializer.startTag(null, "user");
serializer.attribute(null, "id", 1+"");
/**------------------------*/
serializer.startTag(null, "name");
serializer.text("zhangsan");
serializer.endTag(null, "name");
/**------------------------*/
serializer.startTag(null, "age");
serializer.text("28");
serializer.endTag(null, "age");
/**------------------------*/
serializer.endTag(null, "user");
/**------------------------*/
serializer.endTag(null, "users");
serializer.endDocument();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void save5(View v){
//从ClassLoader中获取class包下的文件
InputStream is = MainActivity.this.getClassLoader().getResourceAsStream("users.xml");
try {
StringBuffer sb = new StringBuffer();
List<User> list = UserService.getUsers(is);
for (User user : list) {
sb.append(user.toString());
}
tv.setText(sb.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, "解析失败", 1).show();
}
}
}

package com.gj.save;

import java.io.File;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter;

@SuppressLint("NewApi")
public class MyUtils {

/**
* 得到SD卡总容量
* @param context
* @return
*/
public static String getSDTotalStorageSpace(Context context){
File path = Environment.getExternalStorageDirectory();
StatFs fs = new StatFs(path.getPath());
long blockSize = fs.getBlockSizeLong();
long totalBlocks = fs.getBlockCountLong();
long totalSize = blockSize*totalBlocks;
return Formatter.formatFileSize(context, totalSize);
}
/**
* 得到SD卡可用容量
* @param context
* @return
*/
public static String getSDAvailableStorageSpace(Context context){
File path = Environment.getExternalStorageDirectory();
StatFs fs = new StatFs(path.getPath());
long blockSize = fs.getBlockSizeLong();
long availableBlocks = fs.getAvailableBlocksLong();
long availSize = availableBlocks*blockSize;
return Formatter.formatFileSize(context, availSize);
}

/**
* 得到系统总容量
* @param context
* @return
*/
public static String getSysTotalStorageSpace(Context context){
File path = Environment.getDataDirectory();
StatFs fs = new StatFs(path.getPath());
long blockSize = fs.getBlockSizeLong();
long totalBlocks = fs.getBlockCountLong();
long totalSize = blockSize*totalBlocks;
return Formatter.formatFileSize(context, totalSize);
}
/**
* 得到系统可用容量
* @param context
* @return
*/
public static String getSysAvailableStorageSpace(Context context){
File path = Environment.getDataDirectory();
StatFs fs = new StatFs(path.getPath());
long blockSize = fs.getBlockSizeLong();
long availableBlocks = fs.getAvailableBlocksLong();
long availSize = availableBlocks*blockSize;
return Formatter.formatFileSize(context, availSize);
}
}

package com.gj.save;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

import com.gj.save.bean.User;

public class UserService {

public static List<User> getUsers(InputStream is) throws Exception{
//得到XmlPullParser解析器
XmlPullParser pull =  Xml.newPullParser();
List<User> list = null;
User user = null;
pull.setInput(is, "utf-8");
//得到当前标示
int type = pull.getEventType();
//如果标示不是结束标示就循环
while(XmlPullParser.END_DOCUMENT != type){
switch (type) {
case XmlPullParser.START_TAG:
if("users".equals(pull.getName())){
list = new ArrayList<User>();
}else if("user".equals(pull.getName())){
user = new User();
user.setId(pull.getAttributeValue(0));
}else if("name".equals(pull.getName())){
user.setName(pull.nextText());
}else if("age".equals(pull.getName())){
user.setAge(pull.nextText());
}else if("birth".equals(pull.getName())){
user.setBirth(pull.nextText());
}else if("sex".equals(pull.getName())){
user.setSex(pull.nextText());
}
break;
case XmlPullParser.END_TAG:
if("user".equals(pull.getName())){
list.add(user);
user = null;
}
break;
default:
break;
}
//将"游标"指到下一行
type = pull.next();
}
return list;
}
}

<?xml version='1.0' encoding='utf-8'?>
<users>
<user id="1">
<name>zhangsan</name>
<age>23</age>
<birth>1991-10-12</birth>
<sex>男</sex>
</user>
<user id="2">
<name>李四</name>
<age>25</age>
<birth>1983-12-11</birth>
<sex>女</sex>
</user>
<user id="3">
<name>赵五</name>
<age>61</age>
<birth>1951-09-11</birth>
<sex>男</sex>
</user>
<user id="4">
<name>妹纸</name>
<age>18</age>
<birth>1993-02-22</birth>
<sex>女</sex>
</user>
</users>

点击下载源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android xml