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. iOS7 UIKit动力学-碰撞特性UICollisionBehavior 上

    我们谈到了重力上述财产UIGravityBehavior这个类. 非常明确的看法,当我们添加的属性的严重性后,,苹果UIview像掉进无底洞,地下坠,不断的加速.而如今呢,我们要在这个手机屏幕上,加入 ...

  2. uva 1560 - Extended Lights Out(枚举 | 高斯消元)

    题目链接:uva 1560 - Extended Lights Out 题目大意:给定一个5∗6的矩阵,每一个位置上有一个灯和开关,初始矩阵表示灯的亮暗情况,假设按了这个位置的开关,将会导致周围包含自 ...

  3. C++ Primer 学习笔记_63_重载运算符和转换 --转换和类类型【上】

    重载运算符和转换 --转换与类类型[上] 引言: 在前面我们提到过:能够用一个实參调用的位 unsignedchar 相同范围的值,即:0到255. 这个类能够捕获下溢和上溢错误,因此使用起来比内置u ...

  4. 防止tab页重复的去请求服务端

    直接看图吧. 左边是企业树,右边是依据企业变化的一个tab页 实现功能:1.我们希望假设选中的企业不变,我们在切换旁边五个tab页的时候,仅仅是第一次进去的时候请求server端.以下来回切换tab页 ...

  5. Spring IOC之基于注解的容器配置

    Spring配置中注解比XML更好吗?基于注解的配置的介绍提出的问题是否这种途径比XML更好.简单来说就是视情况而定. 长一点的答案是每一种方法都有自己的长处也不足,而且这个通常取决于开发者决定哪一种 ...

  6. 关于knob.js进度插件的使用

    关于这个插件,妹的,第一次使用坑死爹了,各种不会,幸亏我有持之以恒的精神,最终还是让其臣服于我的胯下.... 1.  引入 head  部分添加knob.js,同时引入excanvas.js这个文件主 ...

  7. DataUml Design 课程6-DataUML Design 1.1版本号正式宣布(支持PD数据模型)

    从DataUML Design正式宣布到现在两个月,因为最近忙,出版到现在为止1.1版本号.稍后我们将始终坚持以良好DataUML Design软件,我希望程序员有很多支持. 一.1.1新的和改进的版 ...

  8. Strongly connected(hdu4635(强连通分量))

    /* http://acm.hdu.edu.cn/showproblem.php?pid=4635 Strongly connected Time Limit: 2000/1000 MS (Java/ ...

  9. 10 Super Useful Tools for Web Designers

    36个扁平化设计的iphone和ipad应用界面设计案例 http://designwoop.com/2014/04/36-examples-of-flat-iphone-and-ipad-appli ...

  10. 对Extjs中store的多种操作

    Store.getCount()返回的是store中的所有数据记录,然后使用for循环遍历整个store,从而得到每条记录. 除了使用getCount()的方法外,还可以使用each()函数,如下面的 ...