歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android數據存儲匯總

Android數據存儲匯總

日期:2017/3/1 9:54:59   编辑:Linux編程

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相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved