1.sharedpreference,存储简单的信息,比如用户名,密码

package com.google.datastore.sharep;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.google.datastore.R;

public class SharePreferences extends Activity{

private EditText editUsername = null;
private EditText editPassword = null;

private Button bt = null;
SharedPreferences userInfo = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
       setContentView(R.layout.sharepreferences);
       
       editUsername = (EditText)findViewById(R.id.username);
editPassword = (EditText)findViewById(R.id.password);
bt = (Button)findViewById(R.id.bt);
//String s = Environment.getExternalStorageDirectory().toString();
       initData();
       
        bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = userInfo.edit();
editor.putString("name", editUsername.getText().toString());
editor.putString("password", editPassword.getText().toString());
editor.commit();
}
});
}

//
private void initData() {
userInfo = getSharedPreferences("user_info", Context.MODE_PRIVATE);
String username = userInfo.getString("name", "");
String password = userInfo.getString("password", "");

editUsername.setText(username);
editPassword.setText(password);
}

}

2.网络存储

package com.google.datastore.net;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.datastore.R;

//有问题,思路就是这样,2.3以后不能在主线程中访问网络
public class Net extends Activity{
private TextView tvNet;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.netget);

tvNet = (TextView)findViewById(R.id.textNet);
new Thread(download).start();
}
//
Runnable download = new Runnable() {
@Override
public void run() {
String msg = "";
try {
URL url = new URL("http://linux.chinaitlab.com/command/723482.html");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(6 * 1000);
conn.setConnectTimeout(5 * 1000);

InputStream is = conn.getInputStream();
Log.d("lixp", "is ========" + is);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(100);

int current = 0;
while((current = bis.read()) != -1) {
baf.append((byte)current);
}

msg = new String(baf.toByteArray(), "UTF-8");
Log.d("lixp", "msg ========" + msg);
}
catch(Exception e) {
msg = e.getMessage();
Log.e("lixp", "e ===" + e);
}
//tvNet.setText(msg);
}
};
}

3.文件存储

package com.google.datastore.filestore;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.datastore.R;

public class FileActivity extends Activity{
private EditText name;
private EditText age;
private FileService fileService;
private Button saveButton;
private Button readButton;
private Button saveToSd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.file);

name = (EditText)findViewById(R.id.filename);
                age = (EditText)findViewById(R.id.content);
                saveButton = (Button)findViewById(R.id.save);
                readButton = (Button)findViewById(R.id.read);
               saveToSd = (Button)findViewById(R.id.saveToSdCard);
        
               fileService = new FileService(FileActivity.this);
        
               saveButton.setOnClickListener(listener);
               saveToSd.setOnClickListener(listener);
              readButton.setOnClickListener(listener);
}

private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Button btn = (Button)v;
String filename = name.getText().toString();
String content = age.getText().toString();
switch (btn.getId()) {
case R.id.save:

try {
fileService.save(filename, content);
Toast.makeText(FileActivity.this, R.string.fileSaveSuccess,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(FileActivity.this, R.string.fileSaveException,
Toast.LENGTH_LONG).show();
}
break;

case R.id.saveToSdCard:           
            if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
try {
fileService.saveToSd(filename, content);
Toast.makeText(FileActivity.this,
R.string.fileSaveSuccess, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(FileActivity.this, R.string.fileSaveException,
Toast.LENGTH_LONG).show();
}
} else {
Log.e("lixp", "Environment.getExternalStorageState() is not equals ..");
}

break;

case R.id.read:
            //有错误5-16
            FileService fileService = new FileService(getApplicationContext());
        Intent intent = getIntent();
        String fileName = intent.getStringExtra("fileName");
       
        Log.d("lixp", "fileService.read(fileName) = " + fileService.read(fileName));
        /*try {
        content.setText(fileService.read(fileName));
        }
        catch(Exception e) {
        e.printStackTrace();
        }*/
            break;            
default:
break;
}
}
};
}

package com.google.datastore.filestore;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class FileService {
private Context context;
public FileService(Context context) {
super();
this.context = context; 
}

/**
* 保存文件
*/
public void save(String fileName, String content) {

try {
//以私有方式读写数据,创建出来的文件只能被该应用访问
FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();

}
catch(Exception e) {
Log.e("lixp", "save() e ============" + e);
}
}

/**
* 保存文件到sdcard
*/
public void saveToSd(String fileName, String content){

try {
//File file = new File(new File("/mnt/sdcard"), fileName);
//考虑不同版本的sdCard目录不同,采用系统提供的API获取SD卡的目录
//命名要避免冲突,和本包的冲突了
File file = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();

}
catch(Exception e) {
Log.e("lixp", "saveToSd() e =============" + e);
}
}

/**
* 读取文件内容
*/
public String read(String fileName) {
byte[] data = null;
try {
FileInputStream fileInputStream = context.openFileInput(fileName);
////把每次读取的内容写入到内存中,然后从内存中获取
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;

//只要没读完,不断的读取
while((len = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
//得到内存中的数据 以二进制存放的
data = outputStream.toByteArray();

}
catch(Exception e) {
Log.e("lixp", "read() e ===========" + e);
}
//根据二进制数据转换成所对应的字符串
return new String(data);
}

}

4.SQLITE数据库存储
package com.google.datastore.sqllite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/*SQLiteOpenHelper:是一个辅助类,这个类主要用于生产一个数据库,并对数据库的版本进行管理。此类为一抽象类,使用是需要继承此类并实现该类的方法 
onCreate(SQLiteDatabase):在数据库第一次生产的时候会调用这个方法,一般我们在这个方法里边生产数据库表。 
onUpgrade(SQLiteDatabase,int,int):当数据库需要升级的时候,Android系统会主动的调用这个方法。一般我们在这个方法里边删除数据库表,并建立新的数据库表,当然是否还需要做其他的操作,完全取决于应用程序的需求。 
onOpen(SQLiteDatabase):这是当打开数据库时的回调函数,一般也不会用到。 
   调用程序方法返回SQLiteDatabase对象。 
当在程序当中调用这个类的方法getWritableDatabase()或者getReadableDatabase()方法的时候,如果当时没有数据,那么Android系统就会自动生产一个数据库。数据库使用完后记得调用close()方法关闭数据库。 
*/
public class DbOpenHelper extends SQLiteOpenHelper{
    public static final String TABLE_NAME = "fb";
public static final String ID = "_id";
public static final String COUNTRY = "country";
       public static final String CODE = "code";
    
//构造方法
public DbOpenHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS"
+ TABLE_NAME + "("
+ ID + "INTEGER PRIMARY KEY,"
+ COUNTRY + "VARCHAR,"
+ CODE + "INTEGER)"
);
}

//升级数据库
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}

package com.google.datastore.sqllite;

import android.app.Activity;
import android.os.Bundle;
import com.google.datastore.R;

public class DbActivity extends Activity{
DbOpenHelper helper = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);    
   /**
    * 得到SQLiteDatabase的实例
    */
  /* helper = new DbOpenHelper(this, FB, null, version);
   //如果没有数据库,自动创建
   SQLiteDatabase db = helper.getWritableDatabase();*/
}

/**
* 插入数据
*/
/*ContentValues values = new ContentValues();
values.put(DBHelper.COUNTRY, "中国");  
    values.put(DBHelper.CODE, 86);  
    db.insert(DBHelper.TB_NAME,DBHelper.ID, values);

*//**
* 改动数据
*//*
db.insert(DBHelper.TB_NAME,DBHelper.ID,null);
    values.clear();
    values.put(DBHelper.COUNTRY, "意大利");
    values.put(DBHelper.CODE, 39);
    db.update(DBHelper.TB_NAME, values,DBHelper.ID + " = 2",null);
    
    *//**
     * execSQL 执行SQL语言
     *//*
    db.execSQL("INSERT INTO "
            + DBHelper.TB_NAME + "("
            + DBHelper.COUNTRY + ","
            + DBHelper.CODE + ") VALUES "
            + "('洪都拉斯',504)");

*//**
     * 查询数据
     *//*
    Cursor c = db.query(DBHelper.TB_NAME,null,null,null,null,null,
    DBHelper.CODE+" DESC");
    //删除数据
    db.delete(DBHelper.TB_NAME,null,null);
    */
}

Android数据存储汇总的更多相关文章

  1. 【Android开发日记】之入门篇(八)——Android数据存储(下)

    废话不多说了,紧接着来讲数据库的操作吧.Come On! 提到数据存储问题,数据库是不得不提的.数据库是用来存储关系型数据的不二利器.Android为开发者提供了强大的数据库支持,可以用来轻松地构造基 ...

  2. Android数据存储之SQLCipher数据库加密

    前言: 最近研究了Android Sqlite数据库(文章地址:Android数据存储之Sqlite的介绍及使用)以及ContentProvider程序间数据共享(Android探索之ContentP ...

  3. Android数据存储之GreenDao 3.0 详解

    前言: 今天一大早收到GreenDao 3.0 正式发布的消息,自从2014年接触GreenDao至今,项目中一直使用GreenDao框架处理数据库操作,本人使用数据库路线 Sqlite----> ...

  4. Android数据存储方式--SharedPreferences

    Android数据存储方式有如下四种:SharedPreferences.存储到文件.SQLite数据库.内容提供者(Content provider).存储到网络服务器. 本文主要介绍一下Share ...

  5. Android数据存储-通过SharedPreferences实现记住密码的操作

    在Android中登陆中,为了实现用户的方便,往往需要根据用户的需要进行记住密码的操作,所以,在Android数据存储中SharedPreferences恰恰可以实现这一点 下面,小编将带领大家通过S ...

  6. 10、Android数据存储

    课程目标: 掌握Android中数据存储的几种方式 熟练使用PreferenceActivity&PreferenceScreen做专业的Setting功能 熟练使用SQLite3来存储数据 ...

  7. Android - 数据存储 -存储文件

    Android使用的文件系统和其他平台的基本磁盘的文件系统很相似.这里将要介绍如何使用File API在Android文件系统中读写文件. File对象适合按顺序读写大量的数据.例如,适合图片文件或者 ...

  8. Android - 数据存储 -存储键值对

    如果你有少量的键值数据需要存储,可以使用SharedPreferencesAPI.SharedPreferences对象指向一个包含键值对的文件并且提供了一些简单的方法来读取它们.每个SharedPr ...

  9. Android数据存储五种方式

    1 使用SharedPreferences存储数据:常用于做本地缓存 2 文件存储数据:(1)data/data/<package name>/files目录内   (2)SDCard内 ...

随机推荐

  1. C#中如何获取系统环境变量

    原文:C#中如何获取系统环境变量 C#中获取系统环境变量需要用到Environment Class.其中提供了有关当前环境和平台的信息以及操作它们的方法.该类不能被继承. 以下代码得到%systemd ...

  2. 网页动态切换母版页(MasterPage)

    原文:网页动态切换母版页(MasterPage) 是否可以变更网页的母版页(MasterPage)呢?某.aspx在创建时,已经附加入某一母版页(MasterPage)了,现需要.aspx动态变更母版 ...

  3. 使用collectd与visage收集kvm虚拟机性能实时图形

    软件功能: 通过collectd软件来监控收集kvm虚拟机的性能数据,包含cpu,memory.磁盘IO.网络流量等 通过visage软件将收集到的数据绘制图形. 安装: 系统环境:ubuntu12. ...

  4. WCF常见问题(1) -- WebService/WCF Session Cookie

    原文:WCF常见问题(1) -- WebService/WCF Session Cookie 在.net 3.0推出WCF之前使用的WebService,有的应用有使用Session保持一些信息,在不 ...

  5. js 计算过去和未来的时间距离现在多少天?

    计算传入的任意一时间.计算出这个时间距离现在还有多少天!或者计算过去的时间距离现在已经过去了多少天! 返回值有两种! 1.负值 代表过去了多少天 2.正值 代表距离设定的时间还有多少天 说明:距离设定 ...

  6. JavaScript语言基础知识8

    这篇文章是对前面学习的知识进行总结: 1.JavaScript支持多种数据类型,如数值类型.字符串类型.布尔类型等. 2.在JavaScript中,字符串是用引號括起来的字符系列,转义字符能够用来表示 ...

  7. WebService使用DataSetSurrogate压缩Dataset的序列化和解压反序列化传输 (转)

    转自:http://blog.163.com/hehong0925@126/blog/static/1339333372012102242920521/ 在WebService中将dataset序列化 ...

  8. openGL的使用步骤

    使用openGL步骤:1.创建GLSurfaceView对象2.创建GLSurfaceView.renderer实现类.3.设置activity的contentView,以及设置view的render ...

  9. bootstrap + angularjs + seajs构建Web Form前端2

    bootstrap + angularjs + seajs构建Web Form前端(二) 回顾 上一篇讲解了引入bootstrap构建一个简单的登录页面,如何让angularjs自动启动并绑定视图,操 ...

  10. C++虚函数表调用学习

    知识点是看 陈皓大哥的博客,代码也参考了他的,不过做了很小的改动. 原文链接:http://blog.csdn.net/haoel/article/details/1948051 #include & ...