本文主要是介绍Android 开发(13)数据存储技术,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、shared preferences存储
1、SP存取数据
写数据
读数据
2、QQ自动登录实现
public class MainActivity extends AppCompatActivity {private EditText editText1, editText2;private Button button;private String username = "stan", password = "stan123";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);editText1 = (EditText) findViewById(R.id.et1);editText2 = (EditText) findViewById(R.id.et2);button = (Button) findViewById(R.id.btn);final SharedPreferences sp = getSharedPreferences("stan", MODE_PRIVATE);String user = sp.getString("user", null);String pass = sp.getString("pass", null);if (user != null && pass != null) {if (user.equals(username) && pass.equals(password)) {Intent intent = new Intent(MainActivity.this, DetailActivity.class);startActivity(intent);}} else {button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String username_in = editText1.getText().toString();String password_in = editText2.getText().toString();if (!(username_in == null) && !(password_in == null)) {if (username_in.equals(username) && password_in.equals(password)) {SharedPreferences.Editor editor = sp.edit();editor.putString("user", username_in);editor.putString("pass", password_in);editor.commit();Intent intent = new Intent(MainActivity.this, DetailActivity.class);startActivity(intent);} else {Toast.makeText(MainActivity.this, "用户名或者密码错误", Toast.LENGTH_SHORT).show();}} else {Toast.makeText(MainActivity.this, "用户名或者密码为空", Toast.LENGTH_SHORT).show();}}});}}
}
sharedPreferences 最终将数据保存在一个 xml 文件中,这个文件所在的位置是
data>data>包名>shared_prefs
二、文件存储
- 这里的外部存储和内部存储不是指内置存储和SD的卡的差异
1、内部存储
简易备忘录的实现
public class MainActivity extends AppCompatActivity {private ImageButton btn_cancel, btn_save;private EditText editText;private FileInputStream fis;private FileOutputStream fos;private byte[] buffer;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn_cancel = (ImageButton) findViewById(R.id.cancel);btn_save = (ImageButton) findViewById(R.id.save);editText = (EditText) findViewById(R.id.et);btn_save.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {try {fos = openFileOutput("inner", MODE_PRIVATE);String text = editText.getText().toString();fos.write(text.getBytes());fos.flush();Toast.makeText(MainActivity.this, "文件已经保存", Toast.LENGTH_SHORT).show();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}}});//open app to open filetry {fis = openFileInput("inner");buffer = new byte[fis.available()];fis.read(buffer);editText.setText(new String(buffer));} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}btn_cancel.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {finish();}});}
}
2、外部存储
- 简单来说我们的手机连接电脑,在电脑上能够查看的部分就是外部存储
- 上面的备忘录实例将获取输入和输出流的部分改为直接新建一个相应的FOS或者FIS对象并指定相应的File文件就可以了
关键代码
- 记得要在 manifest 里面开启权限
final File file = new File(Environment.getExternalStorageDirectory(),"stan.txt");
fos = new FileOutputStream(file);
fis = new FileInputStream(file);
三、数据库存储
1、关于SQLite数据库
基本特点
使用
- 总的来说和其他的数据库的使用基本上是大同小异
- 使用前需要在 adb shell 的命令行创建数据库的目录和文件,使用SDK中提供的adb工具
- 创建好目录和文件之后可以使用
sqlite3 databasename
进入sqlite 数据库进行操作 - 利用SDK提供的sqlite3.exe 工具也可以直接连接数据库操作
- 关于命令:
.exit
退出数据库.tables
查看当前数据库的数据表 - 数据表的创建和查询基本就是sql了,没啥可说
- 注意:创建数据库文件的时候先要进入数据库的目录
2、使用代码操作SQLite数据库
简易的字典的实现
- Mainactivity代码
public class MainActivity extends AppCompatActivity {private ImageButton btn_search, btn_add;private EditText text_search;private ListView word_list;private DBhelper dBhelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn_add = (ImageButton) findViewById(R.id.btn_add);btn_search = (ImageButton) findViewById(R.id.btn_search);text_search = (EditText) findViewById(R.id.word_search);word_list = (ListView) findViewById(R.id.display_word);dBhelper = new DBhelper(this, "dict.db", null, 1);btn_search.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String searchWord = text_search.getText().toString().trim();Cursor cursor = dBhelper.getReadableDatabase().query("word_dict", null, "word=?", new String[]{searchWord}, null, null, null);ArrayList<HashMap<String, String>> resList = new ArrayList<>();while (cursor.moveToNext()) {String word = cursor.getString(1);String detail = cursor.getString(2);HashMap<String, String> map = new HashMap<>();map.put("word", word);map.put("detail", detail);resList.add(map);}if (resList != null && resList.size() != 0) {SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, resList, R.layout.result_main,new String[]{"word", "detail"}, new int[]{R.id.list_word, R.id.list_detail});word_list.setAdapter(adapter);} else {Toast.makeText(MainActivity.this, "查询的单词不存在", Toast.LENGTH_SHORT).show();}}});btn_add.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(MainActivity.this, AddActivity.class);startActivity(intent);}});}}
- 添加单词activity
public class AddActivity extends AppCompatActivity {private ImageButton btn_save, btn_cancel;private EditText word, detail;private DBhelper dBhelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_add);btn_cancel = (ImageButton) findViewById(R.id.add_cancel);btn_save = (ImageButton) findViewById(R.id.add_save);word = (EditText) findViewById(R.id.add_word);detail = (EditText) findViewById(R.id.add_detail);dBhelper = new DBhelper(this, "dict.db", null, 1);btn_cancel.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {finish();}});btn_save.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String word_text = word.getText().toString();String detail_text = detail.getText().toString();if (!word_text.equals("") && !detail_text.equals("")) {ContentValues values = new ContentValues();values.put("word", word_text);values.put("detail", detail_text);dBhelper.getReadableDatabase().insert("word_dict", null, values);Toast.makeText(AddActivity.this, "单词添加成功", Toast.LENGTH_SHORT).show();} else {Toast.makeText(AddActivity.this, "输入的单词或释义为空", Toast.LENGTH_SHORT).show();}}});}
}
- 帮助类
public class DBhelper extends SQLiteOpenHelper {private final static String CREATE = "create table word_dict(_id integer primary key autoincrement,word text,detail text)";public DBhelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {super(context, name, factory, version);}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL(CREATE);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {Log.i("upgrade", "版本升级" + oldVersion + "--->" + newVersion);}
}
四、数据共享
1、基本原理
- 本质就是 ContentResolver 来作为应用之间媒介,进行数据信息的分享
- 这里面通过URI定位我们需要共享的数据,数据的结构就是表格的形式,增删改查的操作和操作数据库很相似
2、读取系统的电话本数据
public class MainActivity extends AppCompatActivity {private final static String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);TextView editText = (TextView) findViewById(R.id.et);editText.setText(getQueryData());}private String getQueryData() {ContentResolver resolver = getContentResolver();Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);StringBuilder builder = new StringBuilder();for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {int index = cursor.getColumnIndex(DISPLAY_NAME);builder.append(cursor.getString(index) + "\n");}return builder.toString();}
}
这篇关于Android 开发(13)数据存储技术的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!