Android App中各种数据保存方式的使用实例总结

少量数据保存之SharedPreferences接口实例
SharedPreferences数据保存主要是通过键值的方式存储在xml文件中
xml文件在data/此程序的包名/XX.xml。
格式:




写入日期:2013年10月07日,时间:11:28:09

SharedPreferences读写的基本步骤:
读:
 1.通过Context的getSharedPreferences获取SharedPreferences接口的对象share:SharedPreferences share = this.getSharedPreferences("share",Context.MODE_PRIVATE);
"shre"保存的xml文件名 ,Context.MODE_PRIVATE 保存的类型为只被本程序访问 (还有MODE_WORLD_READABLE表示其余的程序能够读不能写,MODE
_WORLD_WRITEBLE能读写 这两个都在api17的时候被废了)
2.通过share的getXXX的方法获取指定key的值 :  share.getInt("count", 0);
写:
1.通过SharedPreferences对象的edit()方法获取Edit对象:Edit   editor = share.edit();
2.通过editor对象的putXXX方法来写入值 :editor.putInt("count", 1);
3.调用Editor的commit()方法提交修改值 :editor.commit();

访问其他程序的SharedPreferences
访问其他程序的SharedPreferences 的读写唯一不同的是先的获取该程序的Context接口对象:this.createPackageContext(packageName, flags)
packageName为要该目标程序的包名,flags访问类型
其余的就和上面的步骤差不多 就不再概叙

实例

 
 
 
package com.android.xiong.sharepreferencestest; 
 
import java.text.SimpleDateFormat; 
import java.util.Date; 
 
import android.app.Activity; 
import android.content.Context; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 
 
public class MainActivity extends Activity { 
 
 private Button write; 
 private Button read; 
 
 private TextView txt1; 
 private TextView countTxt; 
  
 SharedPreferences share ; 
  
 Editor editor; 
 
 int countO=0; 
 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main); 
  //获取SharedPreferences对象 
  share = this.getSharedPreferences("share", 
    Context.MODE_PRIVATE); 
  //获取Editor对象 
  editor = share.edit(); 
  write = (Button) findViewById(R.id.write); 
  read = (Button) findViewById(R.id.read); 
  txt1 = (TextView) findViewById(R.id.txt1); 
  countTxt=(TextView)findViewById(R.id.txtCount); 
  //获取share中key为count的值 
  countO=share.getInt("count", 0); 
  countO++; 
  //修改share中key为count的值 
  editor.putInt("count", countO); 
  //提交修改 
  editor.commit(); 
  System.out.println("该应用程序使用了:"+countO+"次"); 
  countTxt.setText("该应用程序使用了:"+countO+"次"); 
   
  OnClickListener writeListener = new OnClickListener() { 
 
   @Override 
   public void onClick(View v) { 
    // TODO Auto-generated method stub 
 
    SimpleDateFormat data = new SimpleDateFormat( 
      "写入日期:yyyy年MM月dd日,时间:hh:mm:ss"); 
    editor.putString("time", 
      data.format(new Date())); 
    editor.commit(); 
 
   } 
  }; 
  OnClickListener readListener=new OnClickListener() { 
    
   @Override 
   public void onClick(View v) { 
    // TODO Auto-generated method stub 
    if(!share.contains("share")){ 
     txt1.setText(share.getString("time", null)); 
    } 
     
   } 
  }; 
  write.setOnClickListener(writeListener); 
  read.setOnClickListener(readListener); 
 
 } 
 
 @Override 
 public boolean onCreateOptionsMenu(Menu menu) { 
  // Inflate the menu; this adds items to the action bar if it is present. 
  getMenuInflater().inflate(R.menu.main, menu); 
  return true; 
 } 
 
} 


机身内存数据读写(Internal Storage)
1.机身内存读取主要用个两个类文件输入流(FileInputStream)和文件输出流(FileOutputStream): FileInputStream fileInput = this.openFileInput("test.txt") 第一个参数为 data/此程序包名/data/test.txt 文件下 的文件名 ;
FileOutputStream fileOut = this.openFileOutput("test.txt",this.MODE_APPEND)第一个参数表示文件名 第二个参数表示打开的方式 
2.获取了文件输入输出流之后 其后的文件的读写和基本的IO操作一样
机身内存数据读写实例

 
  
 
package com.android.xiong.fileiotest; 
 
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.InputStreamReader; 
import java.lang.reflect.Array; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 
 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
 
public class MainActivity extends Activity { 
 
 private Button read; 
 private Button write; 
 private EditText ed1; 
 private EditText ed2; 
 private EditText ed3; 
 private Button delete; 
 
 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main); 
  read = (Button) findViewById(R.id.read); 
  write = (Button) findViewById(R.id.write); 
  delete = (Button) findViewById(R.id.delete); 
  ed3 = (EditText) findViewById(R.id.ed3); 
  ed2 = (EditText) findViewById(R.id.ed2); 
  ed1 = (EditText) findViewById(R.id.ed1); 
  write.setOnClickListener(new OnClickListener() { 
   @Override 
   public void onClick(View v) { 
    String str = ed1.getText().toString(); 
    if (!str.equals("")) { 
     write(str); 
    } 
 
   } 
  }); 
  read.setOnClickListener(new OnClickListener() { 
 
   @Override 
   public void onClick(View v) { 
    read(); 
 
   } 
  }); 
  delete.setOnClickListener(new OnClickListener() { 
   @Override 
   public void onClick(View v) { 
    String str = ed3.getText().toString(); 
    if (!str.equals("")) { 
     deleteFiles(str); 
    } else { 
     ed3.setText(str + ":该文件输入错误或不存在!"); 
    } 
 
   } 
  }); 
 
 } 
 
 private void write(String content) { 
  try { 
   // 以追加的方式打开文件输出流 
   FileOutputStream fileOut = this.openFileOutput("test.txt", 
     this.MODE_APPEND); 
   // 写入数据 
   fileOut.write(content.getBytes()); 
   // 关闭文件输出流 
   fileOut.close(); 
 
  } catch (Exception e) { 
   e.printStackTrace(); 
  } 
 } 
 
 private void read() { 
  try { 
   ed2.setText(""); 
   // 打开文件输入流 
   FileInputStream fileInput = this.openFileInput("test.txt"); 
   BufferedReader br = new BufferedReader(new InputStreamReader( 
     fileInput)); 
   String str = null; 
   StringBuilder stb = new StringBuilder(); 
   while ((str = br.readLine()) !=null ) { 
    stb.append(str); 
   } 
   ed2.setText(stb); 
  } catch (Exception e) { 
   e.printStackTrace(); 
  } 
 
 } 
  
 //删除指定的文件 
 private void deleteFiles(String fileName) { 
  try { 
   // 获取data文件中的所有文件列表 
   List name = Arrays.asList(this.fileList()); 
   if (name.contains(fileName)) { 
    this.deleteFile(fileName); 
    ed3.setText(fileName + ":该文件成功删除!"); 
   } else 
    ed3.setText(fileName + ":该文件输入错误或不存在!"); 
 
  } catch (Exception e) { 
   e.printStackTrace(); 
  } 
 } 
 
 @Override 
 public boolean onCreateOptionsMenu(Menu menu) { 
  getMenuInflater().inflate(R.menu.main, menu); 
  return true; 
 } 
 
} 


SDcard(External Storage)读写数据实例
1.SDcard数据读写需要注定的先要在Androidmainfest.xml文件中注册新建删除和读写的权限 : 





2.读写的基本流程就是:
2.1 通过Environment类的getExternalStorageState()方法来判断手机是否有SDcard: 

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

2.2 最通过getExternalStorageDirectory()方法来获取文件目录:

复制代码 代码如下:

File file = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/test.txt");

读写的文件都在sdcrad文件夹中 通过File Explorer可以导出来
2.3 其后就和基本IO操作相同了
2.4还有要注意一点的是 在运行的模拟器的时候要附带虚拟的SDcard时  要在Run as->Run Configurations 中要关联一下 如下图
Android App中各种数据保存方式的使用实例总结_第1张图片
SDcard数据读写实例
 
  
 


 
 
 
  
  
  
  
  
 
  
   
    
     
 
     
    
   
  
 
 
package com.android.xiong.sdcardtest; 
 
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.InputStreamReader; 
 
import android.app.Activity; 
import android.os.Bundle; 
import android.os.Environment; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
 
public class MainActivity extends Activity { 
 
 private Button write; 
 private Button read; 
 
 private EditText ed1; 
 private TextView txt1; 
 
 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main); 
  write = (Button) findViewById(R.id.write); 
  read = (Button) findViewById(R.id.read); 
  ed1 = (EditText) findViewById(R.id.ed1); 
  txt1 = (TextView) findViewById(R.id.txt1); 
  write.setOnClickListener(new OnClickListener() { 
 
   @Override 
   public void onClick(View v) { 
    // TODO Auto-generated method stub 
    writeSDcard(ed1.getText().toString()); 
 
   } 
  }); 
  read.setOnClickListener(new OnClickListener() { 
 
   @Override 
   public void onClick(View v) { 
    // TODO Auto-generated method stub 
 
    txt1.setText(readSDcard()); 
   } 
  }); 
 } 
 
 // 把数据写入SD卡 
 
 private void writeSDcard(String str) { 
 
  try { 
   // 判断是否存在SD卡 
   if (Environment.getExternalStorageState().equals( 
     Environment.MEDIA_MOUNTED)) { 
    // 获取SD卡的目录 
    File file = Environment.getExternalStorageDirectory(); 
    FileOutputStream fileW = new FileOutputStream(file.getCanonicalPath() + "/test.txt"); 
    fileW.write(str.getBytes()); 
    fileW.close(); 
   } 
  } catch (Exception e) { 
   e.printStackTrace(); 
  } 
 
 } 
 
 // 从SD卡中读取数据 
 private String readSDcard() { 
  StringBuffer str = new StringBuffer(); 
  try { 
   // 判断是否存在SD 
   if (Environment.getExternalStorageState().equals( 
     Environment.MEDIA_MOUNTED)) { 
    File file = new File(Environment.getExternalStorageDirectory() 
      .getCanonicalPath() + "/test.txt");                 
    // 判断是否存在该文件 
    if (file.exists()) { 
     // 打开文件输入流 
     FileInputStream fileR = new FileInputStream(file); 
     BufferedReader reads = new BufferedReader( 
       new InputStreamReader(fileR)); 
     String st = null; 
     while ((st =reads.readLine())!=null ) { 
      str.append(st); 
     } 
     fileR.close(); 
    } else { 
     txt1.setText("该目录下文件不存在"); 
    } 
   } 
 
  } catch (Exception e) { 
   e.printStackTrace(); 
  } 
  return str.toString(); 
 } 
 
 @Override 
 public boolean onCreateOptionsMenu(Menu menu) { 
  // Inflate the menu; this adds items to the action bar if it is present. 
  getMenuInflater().inflate(R.menu.main, menu); 
  return true; 
 } 
 
} 

SQLite简介和简单的登录与注册源代码
1.获取SQLiteDatabase对象db创建数据库或连接数据库:SQLiteDatabasedb = SQLiteDatabase.openOrCreateDatabase(MainActivity.this.getFilesDir().toString()+ "/test.dbs", null);如果目录下有test.dbs数据库则是连接没有就是创建
2.用对象db的方法来执行sql语句:db.execSQL(String sql) 此方法木有返回值 所以查询不好弄。查询一般用db.rawQuery返回一个Cursor对象(相当与jdbc中的ResultSet),Cursor有如下几个方法来查询数据:
  2.1 move ToFirst 将记录指针跳到第一行
  2.2 moveToLast将记录指针跳到最后一行
  2.3 moveNext将记录指针移到下一行
  2.4moveToPosition( int ss)将记录指针跳到指定的ss行
  2.5moveToPrevious将记录指针跳到上一行
将记录指针跳到指定的行之后就可以通过对象的getXXX方法来获取数据 :如 Cursor cursor = db.rawQuery("select  na,pw from user where na=? and pw=?", new String []{name,pwd});
3.回收资源close
当然以SQLiteDatabase对象还可以调用许多方法来操作数据库,不过俺是觉得这几个方法基本够了

简单的登录与注册源代码:
(仅此来练习SQLite的操作  一般注册的信息都样上传到服务器而不会是存储在手机数据库)

Android App中各种数据保存方式的使用实例总结_第2张图片

 
 
 
   
 
   
     
       
         
 
         
       
     
     
     
   
 
 

 
 
   
   
   
     
   
   
  


 
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
    


package com.android.xiong.sqlitelogin; 
 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.Intent; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteException; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
 
public class MainActivity extends Activity { 
 
  // 帐号和密码 
  private EditText edname; 
  private EditText edpassword; 
 
  private Button btregister; 
  private Button btlogin; 
  // 创建SQLite数据库 
  public static SQLiteDatabase db; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    edname = (EditText) findViewById(R.id.edname); 
    edpassword = (EditText) findViewById(R.id.edpassword); 
    btregister = (Button) findViewById(R.id.btregister); 
    btlogin = (Button) findViewById(R.id.btlogin); 
    db = SQLiteDatabase.openOrCreateDatabase(MainActivity.this.getFilesDir().toString() 
        + "/test.dbs", null); 
    // 跳转到注册界面 
    btregister.setOnClickListener(new OnClickListener() { 
 
      @Override 
      public void onClick(View v) { 
        // TODO Auto-generated method stub 
        Intent intent = new Intent(); 
        intent.setClass(MainActivity.this, RegistersActivity.class); 
        startActivity(intent); 
      } 
    }); 
    btlogin.setOnClickListener(new LoginListener()); 
  } 
 
  @Override 
  protected void onDestroy() { 
    // TODO Auto-generated method stub 
    super.onDestroy(); 
    db.close(); 
  } 
 
 
  class LoginListener implements OnClickListener { 
 
    @Override 
    public void onClick(View v) { 
      // TODO Auto-generated method stub 
      String name = edname.getText().toString(); 
      String password = edpassword.getText().toString(); 
      if (name.equals("") || password.equals("")) { 
        // 弹出消息框 
        new AlertDialog.Builder(MainActivity.this).setTitle("错误") 
            .setMessage("帐号或密码不能空").setPositiveButton("确定", null) 
            .show(); 
      } else { 
        isUserinfo(name, password); 
      } 
    } 
 
    // 判断输入的用户是否正确 
    public Boolean isUserinfo(String name, String pwd) { 
      try{ 
        String str="select * from tb_user where name=? and password=?"; 
        Cursor cursor = db.rawQuery(str, new String []{name,pwd}); 
        if(cursor.getCount()<=0){ 
          new AlertDialog.Builder(MainActivity.this).setTitle("错误") 
          .setMessage("帐号或密码错误!").setPositiveButton("确定", null) 
          .show(); 
          return false; 
        }else{ 
          new AlertDialog.Builder(MainActivity.this).setTitle("正确") 
          .setMessage("成功登录").setPositiveButton("确定", null) 
          .show(); 
          return true; 
        } 
         
      }catch(SQLiteException e){ 
        createDb(); 
      } 
      return false; 
    } 
   
  } 
  // 创建数据库和用户表 
  public void createDb() { 
    db.execSQL("create table tb_user( name varchar(30) primary key,password varchar(30))"); 
  } 
  @Override 
  public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
  } 
 
} 

package com.android.xiong.sqlitelogin; 
 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.database.sqlite.SQLiteDatabase; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
 
public class RegistersActivity extends Activity { 
 
  private EditText edname1; 
  private EditText edpassword1; 
  private Button btregister1; 
  SQLiteDatabase db; 
 
  @Override 
  protected void onDestroy() { 
    // TODO Auto-generated method stub 
    super.onDestroy(); 
    db.close(); 
  } 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.register); 
    edname1 = (EditText) findViewById(R.id.edname1); 
    edpassword1 = (EditText) findViewById(R.id.edpassword1); 
    btregister1 = (Button) findViewById(R.id.btregister1); 
    btregister1.setOnClickListener(new OnClickListener() { 
 
      @Override 
      public void onClick(View v) { 
        // TODO Auto-generated method stub 
        String name = edname1.getText().toString(); 
        String password = edpassword1.getText().toString(); 
        if (!(name.equals("") && password.equals(""))) { 
          if (addUser(name, password)) { 
            DialogInterface.OnClickListener ss = new DialogInterface.OnClickListener() { 
              @Override 
              public void onClick(DialogInterface dialog, 
                  int which) { 
                // TODO Auto-generated method stub 
                // 跳转到登录界面 
                Intent in = new Intent(); 
                in.setClass(RegistersActivity.this, 
                    MainActivity.class); 
                startActivity(in); 
                // 销毁当前activity 
                RegistersActivity.this.onDestroy(); 
              } 
            }; 
            new AlertDialog.Builder(RegistersActivity.this) 
                .setTitle("注册成功").setMessage("注册成功") 
                .setPositiveButton("确定", ss).show(); 
 
          } else { 
            new AlertDialog.Builder(RegistersActivity.this) 
                .setTitle("注册失败").setMessage("注册失败") 
                .setPositiveButton("确定", null); 
          } 
        } else { 
          new AlertDialog.Builder(RegistersActivity.this) 
              .setTitle("帐号密码不能为空").setMessage("帐号密码不能为空") 
              .setPositiveButton("确定", null); 
        } 
 
      } 
    }); 
 
  } 
 
  // 添加用户 
  public Boolean addUser(String name, String password) { 
    String str = "insert into tb_user values(?,?) "; 
    MainActivity main = new MainActivity(); 
    db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString() 
        + "/test.dbs", null); 
    main.db = db; 
    try { 
      db.execSQL(str, new String[] { name, password }); 
      return true; 
    } catch (Exception e) { 
      main.createDb(); 
    } 
    return false; 
  } 
 
} 


你可能感兴趣的:(Android App中各种数据保存方式的使用实例总结)