Showing posts with label Ghi dữ liệu. Show all posts
Showing posts with label Ghi dữ liệu. Show all posts

Monday, November 13, 2017

Lưu dữ liệu với SharedPreferences

Để lưu dữ liệu trong Android ngoài cách ghi thành file txt ta cũng có thể dùng SharedPreferences.
int mode = Activity.MODE_PRIVATE;
final String MYPREFS = "mySave";
SharedPreferences save = getSharedPreferences(MYPREFS, mode);
SharedPreferences.Editor editor = save.edit();
editor.putBoolean("isTrue", true);
editor.putFloat("lastFloat", 1f);
editor.putInt("number", 2);
editor.putString("text", "Chu ghi vao");
editor.commit();

Khi lấy dữ liệu đã ghi thì dùng
final String MYPREFS = "mySave";
int mode = Activity.MODE_PRIVATE;
SharedPreferences myShare = getSharedPreferences(MYPREFS,mode);
           
boolean isTrue = myShare.getBoolean("isTrue", false);
float lastFloat = myShare.getFloat("lastFloat", 0f);
int number = myShare.getInt("number", 1);

String luu = myShare.getString("text","");
Hoặc ta có thể làm ngắn gọn hơn như sau.

final SharedPreferences.Editor edit = prefs.edit();
 edit.putInt("vi", vimoix);
 
edit.commit();  
Khi lấy thì dùng.

SharedPreferences prefs;
prefs=PreferenceManager.getDefaultSharedPreferences(this);
int so = prefs.getInt("vi", 0);
 

Wednesday, October 4, 2017

Swift ghi dữ liệu

Ta cần lưu dữ liệu vào trong điện thoại người dùng, một chuỗi ký tự chẳng hạn, ta dùng các dòng lệnh sau. Copy vào dưới viewDidLoad
let file = "ghi.txt"
let text = "Đây là dòng chữ ghi vào"
if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
                    let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)       
                    do {
                        try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
                    }
                    catch {/* error handling here */}
                }
Để kiểm tra xem dữ liệu đã được ghi chưa, ta sẽ đọc file đó ra và set vào textview.
let documentsPath2 = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
        let path2 = documentsPath2.stringByAppendingPathComponent("ghi.txt")
        var read : String = ""
     do {
            try read = NSString(contentsOfFile: path2, encoding: NSUTF8StringEncoding) as String
            gi.text = read
            gi.font = UIFont.italicSystemFontOfSize(17)
            gi.textColor = UIColor.blueColor()
            gi.textAlignment = NSTextAlignment.Center
             }
        catch let error as NSError {
            // print("ERROR : reading from file \(fileName) : \(error.localizedDescription)")
        }

Ta thấy dữ liệu đã ghi và đọc thành công.
Thực tế ta hay dùng ghi vào theo dòng, tức dữ liệu ghi sau sẽ ở dòng dưới dữ liệu ghi trước. Việc này sẽ dễ cho khi đọc ra thành mảng lấy từng dòng để sử dụng.
Hàm sau ghi dữ liệu vào theo dòng.
func write(content: String, _ fileName: String) {
     let contentToAppend = content+"\n"
     let filePath = NSHomeDirectory() + "/Documents/" + fileName
   if let fileHandle = NSFileHandle(forWritingAtPath: filePath) {
 fileHandle.seekToEndOfFile()
fileHandle.writeData(contentToAppend.dataUsingEncoding(NSUTF8StringEncoding)!)
   }
        else {    
            do {
                try contentToAppend.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
            } catch {
                print("Error creating \(filePath)")
            }
        }

    }

Ghi dữ liệu trong Java

Để ghi dữ liệu, ta dùng lớp FileOutputStream.
Vẫn ở class đang thực hành, bạn chọn một textView bất kỳ để dùng.
Copy đoạn code sau vào dưới dòng tham chiếu địa chỉ findViewByid.
String vao="Đây là dòng ghi vào";
try {
FileOutputStream fos = openFileOutput("ghivao.txt", Context.MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fos);
     osw.append(vao);
     osw.flush();
     osw.close();
      } catch (FileNotFoundException e) {         
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }  
Ở đây ta ghi một chuỗi vào thành file có tên ghivao.txt, để biết đã ghi được chưa, ta sẽ đọc file đó rồi set ra textView đã chọn.
String docra="";
try {
              String FILE_NAME = "ghivao.txt";          
              FileInputStream fIS = openFileInput(FILE_NAME);          
              byte[] arrayData = new byte[fIS.available()];
              if((fIS.read(arrayData))!= -1){
              String fileContent = new String(arrayData);
              docra=fileContent;
              tv.setText(docra);
              }   
              fIS.close();           
          } catch (Exception e) {
             
              //Log.e("Error", e.toString());
          }
Ta mở file cần đọc là cái vừa ghi vào, đọc file đó rồi set dữ liệu ra textView.
Chạy thử để thấy dòng chữ đã được đọc ta, tức là trước đó nó được ghi vào thành công.
Nếu bạn thoát rồi mở lại class này nhiều lần, bạn sẽ thấy cứ mỗi lần lại có thêm dòng chữ “Đây là dòng ghi vào” được ghi nối vào đuôi.

Đó là vì file đã ghi trước vẫn ở đó, nên dữ liệu cứ thế thêm vào. Vì đây chỉ là ví dụ nên điều đó không ảnh hưởng đến lệnh ghi và đọc. Vấn đề là ta đã biết cách ghi và đọc file đó ra.