亚洲国产爱久久全部精品_日韩有码在线播放_国产欧美在线观看_中文字幕不卡在线观看

Volley庫 注冊、登錄和注銷含代碼

Volley庫 注冊、登錄和注銷

在本教程中,我們將使用Volley庫和JSON創(chuàng)建基本的用戶注冊和登錄模塊。愛掏網(wǎng) - it200.comVolley是一個提供網(wǎng)絡(luò)連接功能的HTTP庫。愛掏網(wǎng) - it200.com

使用Volley庫的優(yōu)勢如下:

  • 更簡單和更快的請求管理。愛掏網(wǎng) - it200.com
  • 提供高效的網(wǎng)絡(luò)管理。愛掏網(wǎng) - it200.com

在服務(wù)器端數(shù)據(jù)處理方面,我們使用PHP和XAMPP服務(wù)器以及MySQL進(jìn)行數(shù)據(jù)操作。愛掏網(wǎng) - it200.com

在創(chuàng)建Android應(yīng)用程序模塊之前,讓我們先在PHP和MySQL中創(chuàng)建服務(wù)器端數(shù)據(jù)處理API代碼,用于注冊和登錄。愛掏網(wǎng) - it200.com

1. 使用名稱 registerlogin 創(chuàng)建一個數(shù)據(jù)庫,并在其中創(chuàng)建名為 users 的表,該表包含以下字段。愛掏網(wǎng) - it200.com

2. 使用PHP和數(shù)據(jù)庫內(nèi)的以下連接建立代碼,位于 C:\xampp\htdocs\androidphpmysql目錄愛掏網(wǎng) - it200.com

androidphpmysql (您的項目位置)目錄中,創(chuàng)建一個 connection.php 文件并編寫以下代碼。愛掏網(wǎng) - it200.com

connection.php

<?php  
servername = "localhost";username = "root";  
password = "";database = "registerlogin";  
conn = new mysqli(servername, username,password, database);  
if (conn->connect_error) {  
    die("Connection failed: " . $conn->connect_error);  
}  
?>  

3. 在 androidphpmysql 目錄下創(chuàng)建 registrationapi.php 文件,并寫入以下代碼。愛掏網(wǎng) - it200.com該文件處理來自安卓應(yīng)用的請求,并將響應(yīng)以JSON數(shù)組的形式返回給安卓應(yīng)用。愛掏網(wǎng) - it200.com

registrationapi.php

<?php   
  require_once 'connection.php';  
  response = array();   if(isset(_GET['apicall'])){  
  switch(_GET['apicall']){   case 'signup':     if(isTheseParametersAvailable(array('username','email','password','gender'))){username = _POST['username'];email = _POST['email'];password = md5(_POST['password']);gender = _POST['gender'];stmt = conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?");stmt->bind_param("ss", username,email);  
    stmt->execute();stmt->store_result();  

    if(stmt->num_rows>0){response['error'] = true;  
        response['message'] = 'User already registered';stmt->close();  
    }  
    else{  
        stmt =conn->prepare("INSERT INTO users (username, email, password, gender) VALUES (?, ?, ?, ?)");  
        stmt->bind_param("ssss",username, email,password, gender);  

        if(stmt->execute()){  
            stmt =conn->prepare("SELECT id, id, username, email, gender FROM users WHERE username = ?");   
            stmt->bind_param("s",username);  
            stmt->execute();stmt->bind_result(userid,id, username,email, gender);stmt->fetch();  

            user = array(             'id'=>id,   
            'username'=>username,              'email'=>email,  
            'gender'=>gender             );stmt->close();  

            response['error'] = false;response['message'] = 'User registered successfully';   
            response['user'] =user;   
        }  
    }  

}  
else{  
    response['error'] = true;response['message'] = 'required parameters are not available';   
}  
break;   
case 'login':  
  if(isTheseParametersAvailable(array('username', 'password'))){  
    username =_POST['username'];  
    password = md5(_POST['password']);   

    stmt =conn->prepare("SELECT id, username, email, gender FROM users WHERE username = ? AND password = ?");  
    stmt->bind_param("ss",username, password);stmt->execute();  
    stmt->store_result();     if(stmt->num_rows > 0){  
    stmt->bind_result(id, username,email, gender);stmt->fetch();  
    user = array(     'id'=>id,   
    'username'=>username,      'email'=>email,  
    'gender'=>gender     );response['error'] = false;   
    response['message'] = 'Login successfull';response['user'] = user;   }  else{response['error'] = false;   
    response['message'] = 'Invalid username or password';  }  
}  
break;   
default:response['error'] = true;   
 response['message'] = 'Invalid Operation Called';  
}  
}  
else{response['error'] = true;   
 response['message'] = 'Invalid API Call';  
}  
echo json_encode(response);  
function isTheseParametersAvailable(params){  
foreach(params as param){  if(!isset(_POST[$param])){  
     return false;   
  }  
}  
return true;   
}  
?>  

檢查您的PHP API是否正常工作,您可以使用Postman工具等REST客戶端。愛掏網(wǎng) - it200.com

要檢查API的注冊代碼,您可以使用參數(shù)來傳遞注冊的URL。愛掏網(wǎng) - it200.com

同樣,您可以通過傳遞有效的參數(shù)來檢查登入操作的URL。愛掏網(wǎng) - it200.com

現(xiàn)在,在Android應(yīng)用程序中,我們將為用戶注冊、用戶登入和在主活動中顯示用戶詳細(xì)信息(作為個人資料)創(chuàng)建三個Activity類。愛掏網(wǎng) - it200.com

在布局中創(chuàng)建一個 activity_main.xml 并添加以下代碼。愛掏網(wǎng) - it200.com此活動用于顯示用戶的詳細(xì)信息作為個人資料。愛掏網(wǎng) - it200.com

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>  
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.volleyregistrationloginsystem.MainActivity">  

    <LinearLayout  
        android:layout_width="match_parent"  
        android:layout_height="fill_parent"  
        android:layout_marginBottom="8dp"  
        android:layout_marginEnd="8dp"  
        android:layout_marginStart="8dp"  
        android:layout_marginTop="8dp"  
        android:orientation="vertical"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintHorizontal_bias="0.0"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toTopOf="parent"  
        app:layout_constraintVertical_bias="0.0">  

        <TextView  
            android:layout_width="fill_parent"  
            android:layout_height="wrap_content"  
            android:gravity="center"  
            android:text="Welcome to Profile"  
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />  

        <TableLayout  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_marginTop="50dp">  


            <TableRow>  

                <TextView  
                    android:layout_width="wrap_content"  
                    android:layout_height="wrap_content"  
                    android:padding="10dp"  
                    android:text="Id"  
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />  

                <TextView  
                    android:id="@+id/textViewId"  
                    android:layout_width="wrap_content"  
                    android:layout_height="wrap_content"  
                    android:padding="10dp"  
                    android:text="id"  
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />  

            </TableRow>  

            <TableRow>  

                <TextView  
                    android:layout_width="wrap_content"  
                    android:layout_height="wrap_content"  
                    android:padding="10dp"  
                    android:text="Username"  
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />  

                <TextView  
                    android:id="@+id/textViewUsername"  
                    android:layout_width="wrap_content"  
                    android:layout_height="wrap_content"  
                    android:padding="10dp"  
                    android:text="username"  
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />  

            </TableRow>  

            <TableRow>  

                <TextView  
                    android:layout_width="wrap_content"  
                    android:layout_height="wrap_content"  
                    android:padding="10dp"  
                    android:text="Email"  
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />  

                <TextView  
                    android:id="@+id/textViewEmail"  
                    android:layout_width="wrap_content"  
                    android:layout_height="wrap_content"  
                    android:padding="10dp"  
                    android:text="useremail"  
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />  

            </TableRow>  

            <TableRow>  

                <TextView  
                    android:layout_width="wrap_content"  
                    android:layout_height="wrap_content"  
                    android:padding="10dp"  
                    android:text="Gender"  
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />  

                <TextView  
                    android:id="@+id/textViewGender"  
                    android:layout_width="wrap_content"  
                    android:layout_height="wrap_content"  
                    android:padding="10dp"  
                    android:text="gender"  
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />  

            </TableRow>  


        </TableLayout>  

        <Button  
            android:id="@+id/buttonLogout"  
            android:layout_width="210dp"  
            android:layout_height="50dp"  
            android:layout_marginTop="150dp"  
            android:layout_marginLeft="75dp"  
            android:text="Logout" />  
    </LinearLayout>  

</android.support.constraint.ConstraintLayout>  

現(xiàn)在,在布局目錄中創(chuàng)建一個名為activity_login.xml的文件,其中包含以下代碼。愛掏網(wǎng) - it200.com此活動用于用戶登錄界面。愛掏網(wǎng) - it200.com

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>  
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.volleyregistrationloginsystem.LoginActivity">  

    <TextView  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:layout_marginEnd="8dp"  
        android:layout_marginStart="8dp"  
        android:layout_marginTop="16dp"  
        android:gravity="center"  
        android:text="Login"  
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintHorizontal_bias="1.0"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toTopOf="parent" />  

    <EditText  
        android:id="@+id/etUserName"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:layout_marginBottom="8dp"  
        android:layout_marginEnd="8dp"  
        android:layout_marginStart="8dp"  
        android:layout_marginTop="8dp"  
        android:ems="10"  
        android:inputType="textPersonName"  
        android:hint="user name"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintHorizontal_bias="0.0"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toTopOf="parent"  
        app:layout_constraintVertical_bias="0.144" />  

    <EditText  
        android:id="@+id/etUserPassword"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:layout_marginEnd="8dp"  
        android:layout_marginStart="8dp"  
        android:layout_marginTop="8dp"  
        android:hint="password"  
        android:ems="10"  
        android:inputType="textPassword"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toBottomOf="@+id/etUserName" />  

    <Button  
        android:id="@+id/btnLogin"  
        android:layout_width="210dp"  
        android:layout_height="50dp"  
        android:layout_marginBottom="8dp"  
        android:layout_marginEnd="8dp"  
        android:layout_marginStart="8dp"  
        android:layout_marginTop="8dp"  
        android:text="Login"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toBottomOf="@+id/etUserName"  
        app:layout_constraintVertical_bias="0.754" />  

    <TextView  
        android:id="@+id/tvRegister"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_marginBottom="8dp"  
        android:layout_marginEnd="8dp"  
        android:layout_marginStart="8dp"  
        android:layout_marginTop="8dp"  
        android:gravity="center"  
        android:text="Create New Account\n Register Here"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toBottomOf="@+id/btnLogin"  
        app:layout_constraintVertical_bias="0.405" />  

    <ProgressBar  
        android:id="@+id/progressBar"  
        android:visibility="gone"  
        style="?android:attr/progressBarStyle"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_marginBottom="8dp"  
        android:layout_marginEnd="8dp"  
        android:layout_marginStart="8dp"  
        android:layout_marginTop="8dp"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toTopOf="parent"  
        app:layout_constraintVertical_bias="0.456" />  

</android.support.constraint.ConstraintLayout>  

在layout目錄中創(chuàng)建一個activity_register.xml文件,內(nèi)容如下。愛掏網(wǎng) - it200.com該活動用于用戶注冊界面。愛掏網(wǎng) - it200.com

activity_register.xml

<?xml version="1.0" encoding="utf-8"?>  
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.volleyregistrationloginsystem.RegisterActivity">  


    <LinearLayout  
        android:layout_width="match_parent"  
        android:layout_height="519dp"  
        android:layout_centerVertical="true"  
        android:layout_marginBottom="8dp"  
        android:layout_marginEnd="8dp"  
        android:layout_marginStart="8dp"  
        android:layout_marginTop="8dp"  
        android:orientation="vertical"  
        android:padding="10dp"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toTopOf="parent"  
        app:layout_constraintVertical_bias="0.0">  

        <TextView  
            android:layout_width="fill_parent"  
            android:layout_height="wrap_content"  
            android:text="Register"  
            android:gravity="center"  
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />  

        <EditText  
            android:id="@+id/editTextUsername"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_marginBottom="8dp"  
            android:layout_marginTop="20dp"  
            android:hint="Username"  
            android:inputType="text" />  

        <EditText  
            android:id="@+id/editTextEmail"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_marginBottom="8dp"  
            android:layout_marginTop="8dp"  
            android:hint="Email"  
            android:inputType="textEmailAddress" />  

        <EditText  
            android:id="@+id/editTextPassword"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_marginBottom="8dp"  
            android:layout_marginTop="8dp"  
            android:fontFamily="sans-serif"  
            android:hint="Password"  
            android:inputType="textPassword" />  

        <RadioGroup  
            android:id="@+id/radioGender"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_marginBottom="8dp"  
            android:layout_marginTop="8dp"  
            android:orientation="horizontal">  

            <RadioButton  
                android:id="@+id/radioButtonMale"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:checked="true"  
                android:text="Male" />  


            <RadioButton  
                android:id="@+id/radioButtonFemale"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:text="Female" />  

        </RadioGroup>  

        <Button  
            android:id="@+id/buttonRegister"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_marginBottom="8dp"  
            android:layout_marginTop="90dp"  
            android:text="Register" />  

        <TextView  
            android:id="@+id/textViewLogin"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_marginBottom="8dp"  
            android:layout_marginTop="8dp"  
            android:text="Already Registered?\nLogin Here"  
            android:textAlignment="center"  
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />  
    </LinearLayout>  

    <ProgressBar  
        android:visibility="gone"  
        android:id="@+id/progressBar"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_centerHorizontal="true"  
        android:layout_centerVertical="true" />  

</android.support.constraint.ConstraintLayout>  

build.gradle 文件中添加 volley 庫依賴。愛掏網(wǎng) - it200.com

build.gradle

implementation 'com.android.volley:volley:1.0.0'

創(chuàng)建一個名為 User.java 的數(shù)據(jù)模型類,包含以下代碼。愛掏網(wǎng) - it200.com

User.java

package example.javatpoint.com.volleyregistrationloginsystem;


public class User {
    private int id;
    private String name, email, gender;

    public User(int id, String name, String email, String gender) {
        this.id = id;
        this.email = email;
        this.gender = gender;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }


    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

我們需要定義一個調(diào)用服務(wù)器端API的URL。愛掏網(wǎng) - it200.com

創(chuàng)建一個URLs.java類并定義URL。愛掏網(wǎng) - it200.com

URLs.java

package example.javatpoint.com.volleyregistrationloginsystem;  

public class URLs {
    private static final String ROOT_URL = "http://192.168.1.35/androidphpmysql/registrationapi.php?apicall=";
    public static final String URL_REGISTER = ROOT_URL + "signup";
    public static final String URL_LOGIN= ROOT_URL + "login";
}

VolleySingleton.java

package example.javatpoint.com.volleyregistrationloginsystem;  

import android.content.Context;  
import com.android.volley.Request;  
import com.android.volley.RequestQueue;  
import com.android.volley.toolbox.Volley;  

public class VolleySingleton {  
    private static VolleySingleton mInstance;  
    private RequestQueue mRequestQueue;  
    private static Context mCtx;  

    private VolleySingleton(Context context) {  
        mCtx = context;  
        mRequestQueue = getRequestQueue();  
    }  

    public static synchronized VolleySingleton getInstance(Context context) {  
        if (mInstance == null) {  
            mInstance = new VolleySingleton(context);  
        }  
        return mInstance;  
    }  

    public RequestQueue getRequestQueue() {  
        if (mRequestQueue == null) {  
            // getApplicationContext() is key, it keeps you from leaking the  
            // Activity or BroadcastReceiver if someone passes one in.  
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());  
        }  
        return mRequestQueue;  
    }  

    public <T> void addToRequestQueue(Request<T> req) {  
        getRequestQueue().add(req);  
    }  
}  

創(chuàng)建一個名為SharedPreferences.java的類。愛掏網(wǎng) - it200.com在這個類中,我們使用SharedPreferences類來存儲用戶詳細(xì)信息。愛掏網(wǎng) - it200.comSharedPreferences類包含以下四個方法:

  • userLogin(): 此方法用于在登錄后將用戶信息存儲在SharedPreferences中。愛掏網(wǎng) - it200.com
  • isLoggedIn(): 此方法檢查用戶是否已登錄。愛掏網(wǎng) - it200.com
  • getUser(): 此方法在登錄狀態(tài)下獲取用戶信息。愛掏網(wǎng) - it200.com
  • logout(): 此方法清除SharedPreferences數(shù)據(jù)并注銷用戶。愛掏網(wǎng) - it200.com

SharedPrefManager.java

package example.javatpoint.com.volleyregistrationloginsystem;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class SharedPrefManager {

    private static final String SHARED_PREF_NAME = "volleyregisterlogin";
    private static final String KEY_USERNAME = "keyusername";
    private static final String KEY_EMAIL = "keyemail";
    private static final String KEY_GENDER = "keygender";
    private static final String KEY_ID = "keyid";
    private static SharedPrefManager mInstance;
    private static Context ctx;

    private SharedPrefManager(Context context) {
        ctx = context;
    }
    public static synchronized SharedPrefManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SharedPrefManager(context);
        }
        return mInstance;
    }

    //this method will store the user data in shared preferences
    public void userLogin(User user) {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(KEY_ID, user.getId());
        editor.putString(KEY_USERNAME, user.getName());
        editor.putString(KEY_EMAIL, user.getEmail());
        editor.putString(KEY_GENDER, user.getGender());
        editor.apply();
    }

    //this method will checker whether user is already logged in or not
    public boolean isLoggedIn() {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(KEY_USERNAME, null) != null;
    }

    //this method will give the logged in user
    public User getUser() {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return new User(
                sharedPreferences.getInt(KEY_ID, -1),
                sharedPreferences.getString(KEY_USERNAME, null),
                sharedPreferences.getString(KEY_EMAIL, null),
                sharedPreferences.getString(KEY_GENDER, null)
        );
    }

    //this method will logout the user
    public void logout() {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
        ctx.startActivity(new Intent(ctx, LoginActivity.class));
    }
}

現(xiàn)在,在 MainActivity.java 類中,如果用戶登錄,則顯示用戶信息,否則跳轉(zhuǎn)到 LoginActivity.java 類。愛掏網(wǎng) - it200.com當(dāng)點擊按鈕時,使用 onClick() 方法退出登錄。愛掏網(wǎng) - it200.com

MainActivity.java

package example.javatpoint.com.volleyregistrationloginsystem;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    TextView id,userName,userEmail,gender;
    Button btnLogout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(SharedPrefManager.getInstance(this).isLoggedIn()){
            id = findViewById(R.id.textViewId);
            userName = findViewById(R.id.textViewUsername);
            userEmail = findViewById(R.id.textViewEmail);
            gender = findViewById(R.id.textViewGender);
            btnLogout = findViewById(R.id.buttonLogout);
            User user = SharedPrefManager.getInstance(this).getUser();

            id.setText(String.valueOf(user.getId()));
            userEmail.setText(user.getEmail());
            gender.setText(user.getGender());
            userName.setText(user.getName());

            btnLogout.setOnClickListener(this);
        }
        else{
            Intent  intent = new Intent(MainActivity.this,LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }
    public void onClick(View view){
        if(view.equals(btnLogout)){
            SharedPrefManager.getInstance(getApplicationContext()).logout();
        }
    }
}

在 LoginActivity.java 類中,我們檢查用戶是否已經(jīng)登錄,如果是,則重定向到 MainActivity.java 類,否則允許用戶登錄。愛掏網(wǎng) - it200.com

StringRequest 類是 Volley 庫中用于網(wǎng)絡(luò)模塊的類。愛掏網(wǎng) - it200.comStringRequest類的對象接受請求方法類型、URL和響應(yīng)的參數(shù)。愛掏網(wǎng) - it200.com

LoginActivity.java

package example.javatpoint.com.volleyregistrationloginsystem;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity {
    EditText etName, etPassword;
    ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        if (SharedPrefManager.getInstance(this).isLoggedIn()) {
            finish();
            startActivity(new Intent(this, MainActivity.class));
        }

        progressBar = findViewById(R.id.progressBar);
        etName = findViewById(R.id.etUserName);
        etPassword = findViewById(R.id.etUserPassword);



        //調(diào)用userLogin()方法登錄用戶
        findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userLogin();
            }
        });

        //如果用戶點擊未注冊的文本,則調(diào)用RegisterActivity
        findViewById(R.id.tvRegister).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
            }
        });
    }

    private void userLogin() {
        //首先獲取值
        final String username = etName.getText().toString();
        final String password = etPassword.getText().toString();
        //驗證輸入
        if (TextUtils.isEmpty(username)) {
            etName.setError("請輸入用戶名");
            etName.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            etPassword.setError("請輸入密碼");
            etPassword.requestFocus();
            return;
        }

        //如果一切都沒問題
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressBar.setVisibility(View.GONE);

                        try {
                            //將響應(yīng)轉(zhuǎn)換為JSONObject對象
                            JSONObject obj = new JSONObject(response);

                            //如果響應(yīng)中沒有錯誤
                            if (!obj.getBoolean("error")) {
                                Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                                //從響應(yīng)中獲取用戶信息
                                JSONObject userJson = obj.getJSONObject("user");

                                //創(chuàng)建一個新的用戶對象
                                User user = new User(
                                        userJson.getInt("id"),
                                        userJson.getString("username"),
                                        userJson.getString("email"),
                                        userJson.getString("gender")
                                );

                                //將用戶存儲在共享首選項中
                                SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
                                //啟動個人資料頁面
                                finish();
                                startActivity(new Intent(getApplicationContext(), MainActivity.class));
                            } else {
                                Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();

                    }
                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("username", username);
                params.put("password", password);
                return params;
            }
        };

        VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
    }
}

RegisterActivity.java類用于用戶注冊。愛掏網(wǎng) - it200.com這個類最初檢查用戶登錄,如果登錄成功,則重定向至MainActivity.java類;否則,允許用戶進(jìn)行注冊。愛掏網(wǎng) - it200.com

與LoginActivity.java類類似,我們使用Volley庫的StringRequest類進(jìn)行網(wǎng)絡(luò)連接,并傳遞請求方法、URL和響應(yīng)參數(shù)。愛掏網(wǎng) - it200.comResponse.Listener< String >()方法處理服務(wù)器生成的響應(yīng)。愛掏網(wǎng) - it200.com

RegisterActivity.java類

package example.javatpoint.com.volleyregistrationloginsystem;  

import android.content.Intent;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.text.TextUtils;  
import android.view.View;  
import android.widget.EditText;  
import android.widget.ProgressBar;  
import android.widget.RadioButton;  
import android.widget.RadioGroup;  
import android.widget.Toast;  
import com.android.volley.AuthFailureError;  
import com.android.volley.Request;  
import com.android.volley.Response;  
import com.android.volley.VolleyError;  
import com.android.volley.toolbox.StringRequest;  
import org.json.JSONException;  
import org.json.JSONObject;  
import java.util.HashMap;  
import java.util.Map;  

public class RegisterActivity extends AppCompatActivity {  
    EditText editTextUsername, editTextEmail, editTextPassword;  
    RadioGroup radioGroupGender;  
    ProgressBar progressBar;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_register);  
        progressBar = findViewById(R.id.progressBar);  

        //if the user is already logged in we will directly start the MainActivity (profile) activity  
        if (SharedPrefManager.getInstance(this).isLoggedIn()) {  
            finish();  
            startActivity(new Intent(this, MainActivity.class));  
            return;  
        }  

        editTextUsername = findViewById(R.id.editTextUsername);  
        editTextEmail = findViewById(R.id.editTextEmail);  
        editTextPassword = findViewById(R.id.editTextPassword);  
        radioGroupGender = findViewById(R.id.radioGender);  


        findViewById(R.id.buttonRegister).setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                //if user pressed on button register  
                //here we will register the user to server  
                registerUser();  
            }  
        });  

        findViewById(R.id.textViewLogin).setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                //if user pressed on textview that already register open LoginActivity  
                finish();  
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));  
            }  
        });  

    }  

    private void registerUser() {  
        final String username = editTextUsername.getText().toString().trim();  
        final String email = editTextEmail.getText().toString().trim();  
        final String password = editTextPassword.getText().toString().trim();  

        final String gender = ((RadioButton) findViewById(radioGroupGender.getCheckedRadioButtonId())).getText().toString();  

        //first we will do the validations  
        if (TextUtils.isEmpty(username)) {  
            editTextUsername.setError("Please enter username");  
            editTextUsername.requestFocus();  
            return;  
        }  

        if (TextUtils.isEmpty(email)) {  
            editTextEmail.setError("Please enter your email");  
            editTextEmail.requestFocus();  
            return;  
        }  

        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {  
            editTextEmail.setError("Enter a valid email");  
            editTextEmail.requestFocus();  
            return;  
        }  

        if (TextUtils.isEmpty(password)) {  
            editTextPassword.setError("Enter a password");  
            editTextPassword.requestFocus();  
            return;  
        }  

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_REGISTER,  
                new Response.Listener<String>() {  
                    @Override  
                    public void onResponse(String response) {  
                        progressBar.setVisibility(View.GONE);  

                        try {  
                            //converting response to json object  
                            JSONObject obj = new JSONObject(response);  
                            //if no error in response  
                            if (!obj.getBoolean("error")) {  
                                Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();  

                                //getting the user from the response  
                                JSONObject userJson = obj.getJSONObject("user");  

                                //creating a new user object  
                                User user = new User(  
                                        userJson.getInt("id"),  
                                        userJson.getString("username"),  
                                        userJson.getString("email"),  
                                        userJson.getString("gender")  
                                );  

                                //storing the user in shared preferences  
                                SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);  

                                //starting the profile activity  
                                finish();  
                                startActivity(new Intent(getApplicationContext(), MainActivity.class));  
                            } else {  
                                Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();  
                            }  
                        } catch (JSONException e) {  
                            e.printStackTrace();  
                        }  
                    }  
                },  
                new Response.ErrorListener() {  
                    @Override  
                    public void onErrorResponse(VolleyError error) {  
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();  
                    }  
                }) {  
            @Override  
            protected Map<String, String> getParams() throws AuthFailureError {  
                Map<String, String> params = new HashMap<>();  
                params.put("username", username);  
                params.put("email", email);  
                params.put("password", password);  
                params.put("gender", gender);  
                return params;  
            }  
        };  

        VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);  
    }  
} 

將以下權(quán)限添加到 AndroidManifest.xml 文件中

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.javatpoint.com.volleyregistrationloginsystem">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginActivity" />
        <activity android:name=".RegisterActivity"></activity>
    </application>

</manifest>

輸出:

聲明:所有內(nèi)容來自互聯(lián)網(wǎng)搜索結(jié)果,不保證100%準(zhǔn)確性,僅供參考。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進(jìn)行處理。
發(fā)表評論
更多 網(wǎng)友評論0 條評論)
暫無評論

返回頂部

亚洲国产爱久久全部精品_日韩有码在线播放_国产欧美在线观看_中文字幕不卡在线观看

    
    

    欧美巨乳在线观看| 国产欧美日韩免费| 激情丁香综合| 欧美国产亚洲精品久久久8v| 久久伊人免费视频| 欧美成人黄色小视频| 在线综合亚洲| 欧美伊人久久久久久久久影院| 久久精品官网| 欧美风情在线| 国产精品国产三级国产专区53 | 欧美在线网址| 99综合电影在线视频| 一区二区高清视频| 欧美一区二区免费| 欧美成ee人免费视频| 国产精品v欧美精品v日本精品动漫 | 欧美成人首页| 国产精品成人av性教育| 狠狠色综合网| 亚洲色无码播放| 日韩图片一区| 亚洲国产视频一区| 在线欧美影院| 国产性色一区二区| 亚洲人成在线观看一区二区| 亚洲午夜未删减在线观看| 亚洲日本无吗高清不卡| 在线看视频不卡| 亚洲午夜视频在线| 欧美.www| 国产一区二区三区精品欧美日韩一区二区三区 | 亚洲欧美一区二区三区极速播放| 久久蜜桃av一区精品变态类天堂| 国产精品qvod| 亚洲精品久久久久久久久久久| 欧美在线观看视频在线 | 欧美在线日韩| 国产精品国产| 亚洲美女电影在线| 久久婷婷综合激情| 国产人久久人人人人爽| 亚洲一区二区久久| 欧美日韩亚洲三区| 欧美视频精品一区| 在线免费观看视频一区| 欧美一级淫片aaaaaaa视频| 久久九九99| 猛男gaygay欧美视频| 欧美91大片| 永久免费精品影视网站| 久久久欧美精品| 红桃视频国产一区| 欧美在线播放一区| 国产一区二区成人| 亚洲高清视频一区二区| 久久久美女艺术照精彩视频福利播放 | 亚洲国产婷婷综合在线精品| 久久久久久免费| 精品av久久707| 久久久久青草大香线综合精品| 国产主播一区二区三区四区| 久久aⅴ国产紧身牛仔裤| 国产乱码精品| 久久久xxx| 亚洲福利专区| 午夜国产一区| 国产亚洲精品成人av久久ww| 久久国产视频网站| 在线观看欧美日本| 欧美另类在线播放| 中文欧美字幕免费| 国产精品自在欧美一区| 久久国产精品亚洲77777| 好看的日韩视频| 欧美成人精品在线视频| 在线亚洲高清视频| 国产精品一区二区女厕厕| 久久成人18免费观看| 亚洲福利视频一区二区| 欧美日韩视频一区二区| 激情视频一区| 欧美精品一区二区在线播放| 一本色道久久综合亚洲精品按摩| 国产精品电影在线观看| 久久精品一区四区| 日韩视频免费看| 国产精品视区| 欧美不卡福利| 亚洲欧美另类在线观看| 在线日韩欧美| 国产精品xnxxcom| 久久久爽爽爽美女图片| 99视频精品| 国内激情久久| 欧美视频专区一二在线观看| 久久gogo国模裸体人体| 99re这里只有精品6| 国产亚洲aⅴaaaaaa毛片| 欧美经典一区二区三区| 久久久福利视频| 日韩一级在线观看| 激情小说亚洲一区| 国产精品久久久久毛片大屁完整版| 久久久人成影片一区二区三区 | 久久婷婷国产综合国色天香| 一区二区三区久久网| 国产综合网站| 国产精品免费看| 欧美激情久久久久| 亚洲精品乱码久久久久| 国产精品视频久久一区| 欧美精品一区三区在线观看| 久久精品亚洲一区| 午夜久久黄色| 亚洲一区二区三区高清| 亚洲免费福利视频| 亚洲国产精品视频| 在线播放日韩专区| 国产在线视频不卡二| 国产精品一区视频| 国产精品免费观看视频| 欧美午夜电影网| 欧美精品国产精品日韩精品| 老色批av在线精品| 久久久国产91| 久久人人97超碰精品888| 欧美一区成人| 久久狠狠亚洲综合| 销魂美女一区二区三区视频在线| 亚洲视频在线观看三级| 一卡二卡3卡四卡高清精品视频| 在线播放日韩| 亚洲成在人线av| 在线观看中文字幕亚洲| 亚洲福利视频专区| 亚洲国产日韩欧美在线99| 在线观看视频一区二区欧美日韩| 在线观看91精品国产麻豆| 在线精品视频一区二区| 亚洲国产天堂久久综合| 最新国产精品拍自在线播放| 最新高清无码专区| 日韩视频在线观看| 亚洲性av在线| 亚洲欧美日韩区| 欧美在线亚洲一区| 久久日韩粉嫩一区二区三区| 蜜乳av另类精品一区二区| 欧美 日韩 国产在线| 欧美伦理一区二区| 国产精品久久夜| 国产主播一区| 亚洲国产精品久久精品怡红院| 亚洲欧洲一区| 一区二区免费在线观看| 亚洲欧美日韩爽爽影院| 亚洲日本国产| 亚洲网站啪啪| 久久成人久久爱| 男同欧美伦乱| 国产精品久久亚洲7777| 国产亚洲成av人在线观看导航 | 国产伦精品一区二区三区| 精品动漫3d一区二区三区免费版| 亚洲国产日韩欧美| 亚洲午夜未删减在线观看| 欧美中文字幕在线观看| 欧美极品在线观看| 国产伦理精品不卡| 亚洲精品日韩在线观看| 亚洲一区二区在线免费观看视频| 久久精品中文| 欧美午夜激情小视频| 欧美了一区在线观看| 国产欧美日韩综合一区在线观看| 在线精品一区| 亚洲女性裸体视频| 欧美成人免费在线观看| 国产精品一区免费视频| 亚洲美女尤物影院| 麻豆成人av| 欧美激情成人在线| 国产亚洲第一区| 一区二区三区回区在观看免费视频| 久久精品女人| 欧美视频在线视频| 亚洲国产小视频| 久久国产精品99精品国产| 国产精品国产三级国产a| 亚洲国产视频直播| 久久久久成人精品| 国产精品久久久久久一区二区三区| 亚洲区第一页| 久久夜色精品亚洲噜噜国产mv| 久久综合狠狠综合久久综青草| 国产精品免费网站在线观看| 日韩一级黄色片| 欧美高清免费| 亚洲国产精品一区二区第一页|