2014-02-10 2 views
0

Я просто узнал о Android-регистрации и регистрации с помощью PHP, MySQL и SQLite от http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/but, как сделать сессионную функцию, чтобы я мог сделать на своем домашнем экране (dashboard.xml) имя, которое заходит. как приветствовать "имя пользователя, который получает логин". Я все еще новичок для android, большое вам спасибо за вашу помощь.Пользовательский сеанс Android

это мой loginactivity.java

package unai.skripsi.nexttry; 
import java.util.HashMap; 
import org.json.JSONException; 
import org.json.JSONObject; 
import unai.skripsi.nexttry.entity.DatabaseHandler; 
import unai.skripsi.nexttry.entity.UserFunctions; 
import android.app.Activity; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 



public class LoginActivity extends Activity { 
Button btnLogin; 
Button btnLinkToRegister; 
EditText inputEmail; 
EditText inputPassword; 
TextView loginErrorMsg; 


// JSON Response node names 
private static String KEY_SUCCESS = "success"; 
private static String KEY_ERROR = "error"; 
private static String KEY_ERROR_MSG = "error_msg"; 
private static String KEY_UID = "uid"; 
private static String KEY_NAME = "name"; 
private static String KEY_EMAIL = "email"; 
private static String KEY_CREATED_AT = "created_at"; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.login); 

    // Importing all assets like buttons, text fields 
    inputEmail = (EditText) findViewById(R.id.loginEmail); 
    inputPassword = (EditText) findViewById(R.id.loginPassword); 
    btnLogin = (Button) findViewById(R.id.btnLogin); 
    btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen); 
    loginErrorMsg = (TextView) findViewById(R.id.login_error); 

    // Login button Click Event 
    btnLogin.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 
      String email = inputEmail.getText().toString(); 
      String password = inputPassword.getText().toString(); 


      new MyAsyncTask().execute(email, password); 
     } 

      // check for login response 
     class MyAsyncTask extends AsyncTask<String, Void, JSONObject> { 

      protected JSONObject doInBackground(String... params) { 
       UserFunctions userFunction = new UserFunctions(); 
        if (params.length != 2) 
          return null; 
        JSONObject json = userFunction.loginUser(params[0], params[1]); 
        return json; 
      } 

      protected void onPostExecute(JSONObject json) { 
        try { 
       if (json != null && json.getString(KEY_SUCCESS) != null) { 
        loginErrorMsg.setText(""); 
        String res = json.getString(KEY_SUCCESS); 
        if(Integer.parseInt(res) == 1){ 
         // user successfully logged in 
         // Store user details in SQLite Database 
         DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 
         JSONObject json_user = json.getJSONObject("user"); 

         // Clear all previous data in database 
         UserFunctions userFunction = new UserFunctions(); 
         userFunction.logoutUser(getApplicationContext()); 
         db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));       

         // Launch Dashboard Screen 
         Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class); 

         // Close all views before launching Dashboard 
         dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
         startActivity(dashboard); 

         // Close Login Screen 
         finish(); 
        }else{ 
         // Error in login 
         loginErrorMsg.setText("Incorrect username/password"); 
        } 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     }} 
    }); 

    // Link to Register Screen 
    btnLinkToRegister.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 
      Intent i = new Intent(getApplicationContext(), 
        RegisterActivity.class); 
      startActivity(i); 
      finish(); 
     } 
    }); 
    } 
} 

это мой Registeractivity.java

package unai.skripsi.nexttry; 
import org.json.JSONException; 
import org.json.JSONObject; 
import unai.skripsi.nexttry.entity.DatabaseHandler; 
import unai.skripsi.nexttry.entity.UserFunctions; 
import android.app.Activity; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

public class RegisterActivity extends Activity { 
Button btnRegister; 
Button btnLinkToLogin; 
EditText inputFullName; 
EditText inputEmail; 
EditText inputPassword; 
TextView registerErrorMsg; 

// JSON Response node names 
private static String KEY_SUCCESS = "success"; 
private static String KEY_ERROR = "error"; 
private static String KEY_ERROR_MSG = "error_msg"; 
private static String KEY_UID = "uid"; 
private static String KEY_NAME = "name"; 
private static String KEY_EMAIL = "email"; 
private static String KEY_CREATED_AT = "created_at"; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.register); 

    // Importing all assets like buttons, text fields 
    inputFullName = (EditText) findViewById(R.id.registerName); 
    inputEmail = (EditText) findViewById(R.id.registerEmail); 
    inputPassword = (EditText) findViewById(R.id.registerPassword); 
    btnRegister = (Button) findViewById(R.id.btnRegister); 
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen); 
    registerErrorMsg = (TextView) findViewById(R.id.register_error); 

    // Register Button Click event 
    btnRegister.setOnClickListener(new View.OnClickListener() {   
     public void onClick(View view) { 
      String name = inputFullName.getText().toString(); 
      String email = inputEmail.getText().toString(); 
      String password = inputPassword.getText().toString(); 
      new MyAsyncTask().execute(name, email, password); 
     } 

      // check for login response 
     class MyAsyncTask extends AsyncTask<String, Void, JSONObject> { 

      protected JSONObject doInBackground(String... params) { 
       UserFunctions userFunction = new UserFunctions(); 
        if (params.length != 3) 
          return null; 
        JSONObject json = userFunction.registerUser(params[0], params[1], params[2]); 
        return json; 
      } 

      protected void onPostExecute(JSONObject json) { 
        // check for login response 
      try { 
       if (json != null && json.getString(KEY_SUCCESS) != null) { 
        registerErrorMsg.setText(""); 
        String res = json.getString(KEY_SUCCESS); 
        if(Integer.parseInt(res) == 1){ 
         // user successfully registred 
         // Store user details in SQLite Database 
         DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 
         JSONObject json_user = json.getJSONObject("user"); 

         // Clear all previous data in database 
         UserFunctions userFunction = new UserFunctions(); 
         userFunction.logoutUser(getApplicationContext()); 
         db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));       
         // Launch Dashboard Screen 
         Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class); 
         // Close all views before launching Dashboard 
         dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
         startActivity(dashboard); 
         // Close Registration Screen 
         finish(); 
        }else{ 
         // Error in registration 
         registerErrorMsg.setText("Error occured in registration"); 
        } 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     }} 
    }); 

    // Link to Login Screen 
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 
      Intent i = new Intent(getApplicationContext(), 
        LoginActivity.class); 
      startActivity(i); 
      // Close Registration View 
      finish(); 
     } 
    }); 
    } 
} 

это мой DashboardActivity.java

package unai.skripsi.nexttry; 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import unai.skripsi.nexttry.library.UserFunctions; 

public class DashboardActivity extends Activity { 
UserFunctions userFunctions; 
Button btnLogout; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    /** 
    * Dashboard Screen for the application 
    * */  
    // Check login status in database 
    userFunctions = new UserFunctions(); 
    if(userFunctions.isUserLoggedIn(getApplicationContext())){ 
    // user already logged in show databoard 
     setContentView(R.layout.dashboard); 
     btnLogout = (Button) findViewById(R.id.btnLogout); 

     btnLogout.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 
       userFunctions.logoutUser(getApplicationContext()); 
       Intent login = new Intent(getApplicationContext(), LoginActivity.class); 
       login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       startActivity(login); 
       // Closing dashboard screen 
       finish(); 
      } 
     }); 

    }else{ 
     // user is not logged in show login screen 
     Intent login = new Intent(getApplicationContext(), LoginActivity.class); 
     login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     startActivity(login); 
     // Closing dashboard screen 
     finish(); 
    }   
} 
} 

это мой login.xml

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:background="#3b3b3b" > 

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    android:padding="10dip" > 
    <!-- View Title Label --> 
    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginBottom="10dip" 
     android:text="LOGIN" 
     android:textSize="25dip" 
     android:textStyle="bold" /> 
    <!-- Email Label --> 
    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Email" /> 
    <!-- Email TextField --> 
    <EditText 
     android:id="@+id/loginEmail" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" /> 

    <!-- Password Label --> 
    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="15dip" 
     android:text="Password" /> 
    <!-- Password TextField --> 
    <EditText 
     android:id="@+id/loginPassword" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:password="true" /> 

    <!-- Error message --> 
    <TextView android:id="@+id/login_error" 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:textColor="#e30000" 
       android:padding="10dip" 
       android:textStyle="bold"/> 

    <!-- Login Button -->  
    <Button 
     android:id="@+id/btnLogin" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="20dip" 
     android:text="Login" /> 

    <!-- Link to Registration Screen --> 
    <Button 
     android:id="@+id/btnLinkToRegisterScreen" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="40dip" 
     android:background="@null" 
     android:text="I don&apos;t have account. Register Me!" 
     android:textColor="#21dbd4" 
     android:textStyle="bold" /> 
</LinearLayout> 

</ScrollView> 

это мой register.xml

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:background="#3b3b3b" > 

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    android:padding="10dip" > 
    <!-- View Title Label --> 
    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginBottom="10dip" 
     android:text="REGISTER" 
     android:textSize="25dip" 
     android:textStyle="bold" /> 
    <!-- Name Label --> 
    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Full Name" /> 
    <!-- Name TextField --> 
    <EditText 
     android:id="@+id/registerName" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" /> 

    <!-- Email Label --> 
    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Email" /> 
    <!-- Email TextField --> 
    <EditText 
     android:id="@+id/registerEmail" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" /> 

    <!-- Password Label --> 
    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="15dip" 
     android:text="Password" /> 
    <!-- Password TextField --> 
    <EditText 
     android:id="@+id/registerPassword" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:password="true" /> 

    <!-- Error message --> 
    <TextView android:id="@+id/register_error" 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:textColor="#e30000" 
       android:padding="10dip" 
       android:textStyle="bold"/> 

    <!-- Login Button -->  
    <Button 
     android:id="@+id/btnRegister" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="20dip" 
     android:text="Register" /> 

    <!-- Link to Login Screen --> 
    <Button 
     android:id="@+id/btnLinkToLoginScreen" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="40dip" 
     android:background="@null" 
     android:text="Already registred. Login Me!" 
     android:textColor="#21dbd4" 
     android:textStyle="bold" /> 
</LinearLayout> 

</ScrollView> 

это мой dashboard.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
android:background="#3b3b3b"> 

<TextView android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="WELCOME" 
      android:textSize="40dip" 
      android:gravity="center" 
      android:layout_marginTop="20dip"/> 

<Button android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Logout Me" 
    android:textSize="20dip" 
    android:textColor="#21dbd4" 
    android:textStyle="bold" 
    android:id="@+id/btnLogout" 
    android:layout_marginTop="80dip" 
    android:background="@null"/> 

</LinearLayout> 

ответ

0

Вы должны использовать shared preferences на мой взгляд,

This также является хорошим ресурсом для обучения о различных вариантах хранения

Смежные вопросы