2017-09-15 48 views
-1

我想從登錄會話我想從登錄會話獲取用戶當前登錄,而在另一個活動顯示它

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

    inputEmail = (EditText) findViewById(R.id.email); 
    inputPassword = (EditText) findViewById(R.id.password); 
    btnLogin = (Button) findViewById(R.id.btnLogin); 
    btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen); 

    // Progress dialog 
    pDialog = new ProgressDialog(this); 
    pDialog.setCancelable(false); 

    // Session manager 
    session = new SessionManager(getApplicationContext()); 

    // Check if user is already logged in or not 

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

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

      // Check for empty data in the form 
      if (email.trim().length() > 0 && password.trim().length() > 0) { 
       // login user 
       checkLogin(email, password); 
      } else { 
       // Prompt user to enter credentials 
       Toast.makeText(getApplicationContext(), 
         "Please enter the credentials!", Toast.LENGTH_LONG) 
         .show(); 
      } 
     } 

    }); 

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

     public void onClick(View view) { 
      Intent i = new Intent(getApplicationContext(), 
        Activity_Register.class); 
      startActivity(i); 
      finish(); 
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); 
     } 
    }); 

    } 

/** 
* function to verify login details in mysql db 
* */ 
private void checkLogin(final String email, final String password) { 
    // Tag used to cancel the request 
    String tag_string_req = "req_login"; 

    pDialog.setMessage("Logging in ..."); 
    showDialog(); 

    StringRequest strReq = new StringRequest(Method.POST, 
      Config_URL.URL_REGISTER, new Response.Listener<String>() { 

     @Override 
     public void onResponse(String response) { 
      Log.d(TAG, "Login Response: " + response.toString()); 
      hideDialog(); 

      try { 
       JSONObject jObj = new JSONObject(response); 
       boolean error = jObj.getBoolean("error"); 

       // Check for error node in json 
       if (!error) { 
        // user successfully logged in 
        // Create login session 
        session.setLogin(true); 

        // Launch main activity 
        Intent intent = new Intent(Activity_Login.this, 
          AdminLanding.class); 
        intent.putExtra("username",inputEmail.getText().toString()); 
        startActivity(intent); 
        finish(); 
       } else { 
        // Error in login. Get the error message 
        String errorMsg = jObj.getString("error_msg"); 
        Toast.makeText(getApplicationContext(), 
          errorMsg, Toast.LENGTH_LONG).show(); 
       } 
      } catch (JSONException e) { 
       // JSON error 
       e.printStackTrace(); 
      } 

     } 
    }, new Response.ErrorListener() { 

     @Override 
     public void onErrorResponse(VolleyError error) { 
      Log.e(TAG, "Login Error: " + error.getMessage()); 
      Toast.makeText(getApplicationContext(), 
        error.getMessage(), Toast.LENGTH_LONG).show(); 
      hideDialog(); 
     } 
    }) { 

     @Override 
     protected Map<String, String> getParams() { 
      // Posting parameters to login url 
      Map<String, String> params = new HashMap<String, String>(); 
      params.put("tag", "login"); 
      params.put("email", email); 
      params.put("password", password); 

      return params; 
     } 

    }; 

    // Adding request to request queue 
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req); 
} 

private void showDialog() { 
    if (!pDialog.isShowing()) 
     pDialog.show(); 
} 

private void hideDialog() { 
    if (pDialog.isShowing()) 
     pDialog.dismiss(); 
} 
} 

此登錄活動得到InputEmail並將它傳遞給本次活動中的用戶名的TextView沒有對的起它的意圖

public class ViewOrder extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_view_order); 
    Button confirm; 
    TextView username; 
    confirm=(Button)findViewById(R.id.vieworderbutton); 
    username=(TextView) findViewById(R.id.orderv); 


} 
} 

**這是我的sqlite的處理類,我想用getuserdetails方法來獲得當前登錄的用戶,但我無法弄清楚**

public class SQLiteHandler extends SQLiteOpenHelper { 

private static final String TAG = SQLiteHandler.class.getSimpleName(); 

// All Static variables 
// Database Version 
private static final int DATABASE_VERSION = 1; 

// Database Name 
private static final String DATABASE_NAME = "android_api"; 

// Login table name 
private static final String TABLE_LOGIN = "login"; 

// Login Table Columns names 
private static final String KEY_ID = "id"; 
private static final String KEY_NAME = "name"; 
private static final String KEY_EMAIL = "email"; 
private static final String KEY_UID = "uid"; 
private static final String KEY_CREATED_AT = "created_at"; 

public SQLiteHandler(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
} 

// Creating Tables 
@Override 
public void onCreate(SQLiteDatabase db) { 
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "(" 
      + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," 
      + KEY_EMAIL + " TEXT UNIQUE," + KEY_UID + " TEXT," 
      + KEY_CREATED_AT + " TEXT" + ")"; 
    db.execSQL(CREATE_LOGIN_TABLE); 

    Log.d(TAG, "Database tables created"); 
} 

// Upgrading database 
@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // Drop older table if existed 
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN); 

    // Create tables again 
    onCreate(db); 
} 

/** 
* Storing user details in database 
* */ 
public void addUser(String name, String email, String uid, String created_at) { 
    SQLiteDatabase db = this.getWritableDatabase(); 

    ContentValues values = new ContentValues(); 
    values.put(KEY_NAME, name); // Name 
    values.put(KEY_EMAIL, email); // Email 
    values.put(KEY_UID, uid); // Email 
    values.put(KEY_CREATED_AT, created_at); // Created At 

    // Inserting Row 
    long id = db.insert(TABLE_LOGIN, null, values); 
    db.close(); // Closing database connection 

    Log.d(TAG, "New user inserted into sqlite: " + id); 
} 

/** 
* Getting user data from database 
* */ 
public HashMap<String, String> getUserDetails() { 
    HashMap<String, String> user = new HashMap<String, String>(); 
    String selectQuery = "SELECT * FROM " + TABLE_LOGIN; 

    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor cursor = db.rawQuery(selectQuery, null); 
    // Move to first row 
    cursor.moveToFirst(); 
    if (cursor.getCount() > 0) { 
     user.put("name", cursor.getString(1)); 
     user.put("email", cursor.getString(2)); 
     user.put("uid", cursor.getString(3)); 
     user.put("created_at", cursor.getString(4)); 
    } 
    cursor.close(); 
    db.close(); 
    // return user 
    Log.d(TAG, "Fetching user from Sqlite: " + user.toString()); 

    return user; 
} 

/** 
* Getting user login status return true if rows are there in table 
* */ 
public int getRowCount() { 
    String countQuery = "SELECT * FROM " + TABLE_LOGIN; 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor cursor = db.rawQuery(countQuery, null); 
    int rowCount = cursor.getCount(); 
    db.close(); 
    cursor.close(); 

    // return row count 
    return rowCount; 
} 

/** 
* Re crate database Delete all tables and create them again 
* */ 
public void deleteUsers() { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    // Delete All Rows 
    db.delete(TABLE_LOGIN, null, null); 
    db.close(); 

    Log.d(TAG, "Deleted all user info from sqlite"); 
} 

}

會話管理器類

public class SessionManager 
{ 
// LogCat tag 
private static String TAG = SessionManager.class.getSimpleName(); 

// Shared Preferences 
SharedPreferences pref; 

Editor editor; 
Context _context; 

// Shared pref mode 
int PRIVATE_MODE = 0; 

// Shared preferences file name 
private static final String PREF_NAME = "AndroidHiveLogin"; 

private static final String KEY_IS_LOGGEDIN = "isLoggedIn"; 

public SessionManager(Context context) 
{ 
    this._context = context; 
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); 
    editor = pref.edit(); 
} 

public void setLogin(boolean isLoggedIn) 
{ 
    editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn); 

    // commit changes 
    editor.commit(); 

    Log.d(TAG, "User login session modified!"); 
} 

public boolean isLoggedIn() 
{ 
    return pref.getBoolean(KEY_IS_LOGGEDIN, false); 
} 

}

回答

0

當用戶在應用商店獲取的記錄用戶在會話管理器中的ID(或要顯示的數據), ,並根據需要將其顯示在活動中。

你可以做這樣的事情。

SessionManager session = new SessionManager(getApplicationContext()); 
if(session.isLoggedIn()){ 
     //Do your stuff here 
     //fetch the data from your database using the id 
} else{ 
    //Do your stuff 
} 
相關問題