Android資料存放區匯總

來源:互聯網
上載者:User

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);
    */
}


 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.