Thứ Ba, 20 tháng 11, 2018

Android - Quản lý phiên

Phiên giúp bạn khi muốn lưu trữ dữ liệu người dùng bên ngoài ứng dụng lập trình Android của bạn, để khi người dùng lần sau sử dụng ứng dụng của bạn, bạn có thể dễ dàng lấy lại chi tiết của mình và thực hiện tương ứng.

Điều này có thể được thực hiện bằng nhiều cách. Nhưng cách dễ nhất và đẹp nhất để thực hiện việc này là thông qua Tùy chọn được chia sẻ .

Học lập trình Android

Tùy chọn được chia sẻ

Tùy chọn chia sẻ cho phép bạn lưu và truy xuất dữ liệu dưới dạng cặp khóa, giá trị. 

Học lập trình Android để sử dụng các tùy chọn chia sẻ, bạn phải gọi phương thức getSharedPreferences () trả về một cá thể SharedPreference trỏ đến tệp chứa các giá trị của các sở thích.

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 

Bạn có thể lưu một số thứ trong sharedpreferences bằng cách sử dụng lớp SharedPreferences.Editor. Bạn sẽ gọi phương thức chỉnh sửa của cá thể SharedPreference và sẽ nhận nó trong đối tượng trình soạn thảo. Cú pháp của nó là

Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();

Ngoài phương thức putString, có các phương thức có sẵn trong lớp trình soạn thảo cho phép thao tác dữ liệu bên trong các tùy chọn được chia sẻ. Chúng được liệt kê như sau:

Sr.NoChế độ & mô tả
1ứng dụng()
Nó là một phương pháp trừu tượng. Nó sẽ cam kết các thay đổi của bạn trở lại từ trình soạn thảo đối tượng sharedPreference mà bạn đang gọi
2thông thoáng()

Nó sẽ xóa tất cả các giá trị khỏi trình chỉnh sửa
3xóa (khóa chuỗi)

Thao tác này sẽ xóa giá trị có khóa đã được chuyển dưới dạng tham số
4putLong (Khóa chuỗi, giá trị dài)

Nó sẽ tiết kiệm một giá trị dài trong một trình soạn thảo tùy chọn
5putInt (Khóa chuỗi, giá trị int)

Nó sẽ lưu một giá trị số nguyên trong một trình soạn thảo tùy chọn
6putFloat (Khóa chuỗi, giá trị float)

Nó sẽ lưu một giá trị float trong một trình soạn thảo tùy chọn
Quản lý phiên qua các tùy chọn được chia sẻ

Để thực hiện quản lý phiên từ các tùy chọn được chia sẻ, chúng tôi cần kiểm tra các giá trị hoặc dữ liệu được lưu trữ trong các tùy chọn được chia sẻ trong phương thức onResume . Nếu chúng ta không có dữ liệu, chúng ta sẽ khởi động ứng dụng ngay từ đầu vì nó mới được cài đặt. Nhưng nếu chúng tôi có dữ liệu, chúng tôi sẽ bắt đầu từ nơi người dùng rời khỏi nó. Nó được thể hiện trong ví dụ dưới đây

Thí dụ

Ví dụ dưới đây minh họa việc sử dụng Quản lý phiên. Nó đóng một ứng dụng cơ bản cho phép bạn đăng nhập lần đầu tiên. Và sau đó khi bạn thoát khỏi ứng dụng mà không đăng xuất, bạn sẽ được đưa trở lại cùng một vị trí nếu bạn khởi động lại ứng dụng. Nhưng nếu bạn đăng xuất khỏi ứng dụng, bạn sẽ được đưa trở lại màn hình đăng nhập chính.

Để thử nghiệm với ví dụ này, bạn cần chạy ứng dụng này trên thiết bị thực hoặc trong trình giả lập.

Các bướcSự miêu tả
1Bạn sẽ sử dụng android studio IDE để tạo ứng dụng Android theo gói com.example.sairamkrishna.myapplication.
2Sửa đổi tệp src / MainActivity.java để thêm mã tiến trình để thêm mã phiên.
3Tạo Hoạt động mới và đặt tên là second.java.Chỉnh sửa tệp này để thêm mã tiến trình để thêm mã phiên.
4Sửa đổi tệp res / layout / activity_main.xml để thêm mã XML tương ứng.
5Sửa đổi tệp res / layout / second_main.xml để thêm mã XML tương ứng.
7Chạy ứng dụng và chọn một thiết bị Android đang chạy và cài đặt ứng dụng trên đó và xác minh kết quả.
Đây là nội dung của MainActivity.java .
package com.example.sairamkrishna.myapplication;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
   EditText ed1,ed2,ed3;
   Button b1;
   Intent in;

   public static final String MyPREFERENCES = "MyPrefs" ;
   public static final String Name = "nameKey";
   public static final String Phone = "phoneKey";
   public static final String Email = "emailKey";
   SharedPreferences sharedpreferences;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      ed1=(EditText)findViewById(R.id.editText);
      ed2=(EditText)findViewById(R.id.editText2);
      ed3=(EditText)findViewById(R.id.editText3);

      b1=(Button)findViewById(R.id.button);
      sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String n  = ed1.getText().toString();
            String ph  = ed2.getText().toString();
            String e  = ed3.getText().toString();

            SharedPreferences.Editor editor = sharedpreferences.edit();

            editor.putString(Name, n);
            editor.putString(Phone, ph);
            editor.putString(Email, e);
            editor.commit();

            in = new Intent(MainActivity.this,second_main.class);
            startActivity(in);
         }
      });
   }
}
Đây là nội dung của second_main.java .
package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class second_main extends Activity {
   Button bu=null;
   Button bu2=null;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.second_main);

      bu=(Button)findViewById(R.id.button2);
      bu2=(Button)findViewById(R.id.button3);
   }

   public  void logout(View view){
      SharedPreferences sharedpreferences = getSharedPreferences(MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = sharedpreferences.edit();
      editor.clear();
      editor.commit();
   }

   public void close(View view){
      finish();
   }
}
Đây là nội dung của activity_main.xml .
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Shared Preference"
      android:id="@+id/textView"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="35dp" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials Point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textSize="35dp"
      android:textColor="#ff16ff01" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:layout_below="@+id/textView2"
      android:layout_marginTop="67dp"
      android:hint="Name"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText2"
      android:layout_below="@+id/editText"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:hint="Pass" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText3"
      android:layout_below="@+id/editText2"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:hint="Email" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="login"
      android:id="@+id/button"
      android:layout_below="@+id/editText3"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp" />

</RelativeLayout>
Đây là nội dung của second_main.xml .
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical" android:layout_width="match_parent"
   android:layout_height="match_parent">
   
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Logout"
      android:onClick="logout"
      android:id="@+id/button2"
      android:layout_gravity="center_horizontal"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="191dp" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Close"
      android:onClick="close"
      android:id="@+id/button3"
      android:layout_below="@+id/button2"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="69dp" />

</RelativeLayout>
Đây là nội dung của Strings.xml .
<resources>
   <string name="app_name">My Application</string>
</resources>
Đây là nội dung của AndroidManifest.xml .
<? xml version = "1.0" encoding = "utf-8"?>xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"<manifest xmlns: android = "http://schemas.android.com/apk/res/android" 
   package = "com.example.sairamkrishna.myapplication">package = "com.example.sairamkrishna.myapplication" > 
   
   <ứng dụng<ứng dụng
      android: allowBackup = "true"android: allowBackup = "true"
      android: icon = "@ mipmap / ic_launcher"android: icon = "@ mipmap / ic_launcher"
      android: label = "@ string / app_name"android: label = "@ string / app_name"
      android: theme = "@ style / AppTheme">android: theme = "@ style / AppTheme" > 
      
      <hoạt động<hoạt động
         android: name = ". MainActivity"android: name = ".MainActivity"
         android: label = "@ string / app_name">android: label = "@ string / app_name" > 
         
         <intent-filter><intent-filter>
            <action android: name = "android.intent.action.MAIN" /><action android: name = "android.intent.action.MAIN" />  
            <category android: name = "android.intent.category.LAUNCHER" /><category android: name = "android.intent.category.LAUNCHER" />  
         </ intent-filter></ intent-filter>
         
      </ hoạt động></ hoạt động>
      
      <hoạt động android: name = ". second"> </ activity><hoạt động android: name = ".second" > </ activity> 
      
   </ application></ application>
</ manifest></ manifest>
Hãy thử chạy ứng dụng của bạn. Tôi cho rằng bạn đã tạo AVD của mình trong khi thiết lập môi trường. Để chạy ứng dụng từ Android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào Chạy biểu tượng từ thanh công cụ. 

Android studio cài đặt ứng dụng trên AVD của bạn và khởi động ứng dụng và nếu mọi thứ đều ổn với thiết lập và ứng dụng của bạn, ứng dụng sẽ hiển thị cửa sổ Trình mô phỏng sau

Nhập tên người dùng và mật khẩu của bạn (nhập bất kỳ thứ gì bạn thích, nhưng hãy nhớ bạn nhập gì) và nhấp vào nút đăng nhập. Nó được thể hiện trong hình dưới đây -

Ngay sau khi bạn nhấp vào nút đăng nhập, bạn sẽ được đưa đến màn hình Chào mừng này. Bây giờ thông tin đăng nhập của bạn được lưu trữ trong các tùy chọn được chia sẻ.

Bây giờ bấm vào Exit mà không cần đăng xuất nút và bạn sẽ được đưa trở lại màn hình chủ và trong tập tin ưu đãi ra đặt sẽ được như hình dưới đây

Nếu bạn mở tệp myPref.xml dưới dạng tệp ghi chú, nó sẽ như sau

Nếu bạn bấm vào nút đăng xuất, nó sẽ xóa các giá trị ưu tiên. và nếu bạn đã nhập các giá trị khác nhau làm đầu vào, nó sẽ nhập các giá trị đó làm tùy chọn trong XML.

Không có nhận xét nào:

Đăng nhận xét

Lập trình Android - RenderScript

Trong chương này, chúng ta sẽ tìm hiểu về Android RenderScript. Thông thường các ứng dụng trên Android được thiết kế để tiêu thụ tài nguyên ...