Sie sind auf Seite 1von 13

Login Activity

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.ArrayList;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.json.JSONException;

import org.json.JSONObject;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.os.StrictMode;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

// Email, password edittext

EditText txtUsername, txtPassword;

// login button

Button btnLogin;

// Alert Dialog Manager

AlertDialogManager alert = new AlertDialogManager();

// Session Manager Class

SessionManager session;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_login);

// Session Manager

session = new SessionManager(getApplicationContext());


// Email, Password input text

txtUsername = (EditText) findViewById(R.id.txtUsername);

txtPassword = (EditText) findViewById(R.id.txtPassword);

// Login button

btnLogin = (Button) findViewById(R.id.btnLogin);

// Login button click event

btnLogin.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

String result = null;

InputStream is = null;

// Get username, password from EditText

String username = txtUsername.getText().toString();

String password = txtPassword.getText().toString();

// Check if username, password is filled

if(username.trim().length() > 0 && password.trim().length() > 0){


ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("f1", username));

nameValuePairs.add(new BasicNameValuePair("f2", password));

StrictMode.setThreadPolicy(policy);

try {

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new


HttpPost("http://192.168.254.103:80/hsu/hsulogin.php");

httppost.setEntity(new
UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

HttpEntity entity = response.getEntity();

is = entity.getContent();

Log.e("log_tag", "connection success");

} catch (Exception e) {

// TODO: handle exception

Log.e("log_tag", "Error in http connection"+e.toString());

Toast.makeText(getApplicationContext(), "connection fail",


Toast.LENGTH_SHORT).show();

try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is,"iso-8859-1"),8);

StringBuilder sb = new StringBuilder();

String line = null;

while((line = reader.readLine()) !=null)

sb.append(line+"\n");

is.close();

result=sb.toString();

} catch (Exception e) {

// TODO: handle exception

Log.e("log_tag", "Error converting result"+e.toString());

try {

JSONObject json_data = new JSONObject(result);

CharSequence w = (CharSequence)json_data.getString("re");

if(w.equals(username)){

// Creating user login session

// For testing i am stroing name, email as follow

// Use user real data

session.createLoginSession(""+w, "anroidhive@gmail.com");
// Staring MainActivity

Intent i = new Intent(getApplicationContext(), MainActivity.class);

startActivity(i);

finish();

if(w.equals("ala")){

alert.showAlertDialog(LoginActivity.this, "Login failed..",


""+w, false);

} catch (JSONException e) {

// TODO: handle exception

Log.e("log_tag", "Error parsing data"+e.toString());

Toast.makeText(getApplicationContext(), "jsonArray fail",


Toast.LENGTH_SHORT).show();

}else{

// user didn't entered username or password

// Show alert asking him to enter the details

alert.showAlertDialog(LoginActivity.this, "Login failed..", "Please enter username and


password", false);

});

}
}

Session manager
package pedroid.bitsm.projj;

import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SessionManager {


// Shared Preferences
SharedPreferences pref;

// Editor for Shared preferences


Editor editor;

// Context
Context _context;

// Shared pref mode


int PRIVATE_MODE = 0;

// Sharedpref file name


private static final String PREF_NAME = "AndroidHivePref";

// All Shared Preferences Keys


private static final String IS_LOGIN = "IsLoggedIn";

// User name (make variable public to access from outside)


public static final String KEY_NAME = "name";

// Email address (make variable public to access from outside)


public static final String KEY_EMAIL = "email";

// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String name, String email){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);

// Storing name in pref


editor.putString(KEY_NAME, name);

// Storing email in pref


editor.putString(KEY_EMAIL, email);

// commit changes
editor.commit();
}

/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin(){
// Check login status
if(!this.isLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

// Add new Flag to start new Activity


i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

// Staring Login Activity


_context.startActivity(i);
}

/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));

// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

// return user
return user;
}

/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();

// After logout redirect user to Loing Activity


Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

// Add new Flag to start new Activity


i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

// Staring Login Activity


_context.startActivity(i);
}

/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}

MainActivity
public class MainActivity extends ListActivity implements FetchDataListener{
private ProgressDialog dialog;

// Alert Dialog Manager


AlertDialogManager alert = new AlertDialogManager();

// Session Manager Class


SessionManager session;

// Button Logout
Button btnLogout;

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

// Session class instance


session = new SessionManager(getApplicationContext());

TextView lblName = (TextView) findViewById(R.id.lblName);

// Button logout
btnLogout = (Button) findViewById(R.id.btnLogout);

/**
* Call this function whenever you want to check user login
* This will redirect user to LoginActivity is he is not
* logged in
* */
session.checkLogin();

// get user data from session


HashMap<String, String> user = session.getUserDetails();

// name
String name = user.get(SessionManager.KEY_NAME);

// email
String email = user.get(SessionManager.KEY_EMAIL);

// displaying user data


lblName.setText(Html.fromHtml("Name: <b>" + name + "</b>"));

initView();

/**
* Logout button click event
* */
btnLogout.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// Clear the session data
// This will clear all session data and
// redirect user to LoginActivity
session.logoutUser();
}
});
}
}

AlertDialogmanager
public class MainActivity extends ListActivity implements FetchDataListener{
private ProgressDialog dialog;

// Alert Dialog Manager


AlertDialogManager alert = new AlertDialogManager();

// Session Manager Class


SessionManager session;

// Button Logout
Button btnLogout;

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

// Session class instance


session = new SessionManager(getApplicationContext());

TextView lblName = (TextView) findViewById(R.id.lblName);

// Button logout
btnLogout = (Button) findViewById(R.id.btnLogout);

/**
* Call this function whenever you want to check user login
* This will redirect user to LoginActivity is he is not
* logged in
* */
session.checkLogin();

// get user data from session


HashMap<String, String> user = session.getUserDetails();

// name
String name = user.get(SessionManager.KEY_NAME);

// email
String email = user.get(SessionManager.KEY_EMAIL);

// displaying user data


lblName.setText(Html.fromHtml("Name: <b>" + name + "</b>"));
/**
* Logout button click event
* */
btnLogout.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// Clear the session data
// This will clear all session data and
// redirect user to LoginActivity
session.logoutUser();
}
});
}

Activity_login.mxl
<LinearLayout 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:orientation="vertical"
android:padding="10dip">

<!-- Email Label -->


<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Username (Enter 'test')"
android:singleLine="true"
android:layout_marginBottom="5dip"/>

<!-- Email input text -->


<EditText android:id="@+id/txtUsername"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dip"/>

<!-- Password Label -->


<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Password (Enter 'test')"
android:layout_marginBottom="5dip"/>

<!-- Password input text -->


<EditText android:id="@+id/txtPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:password="true"
android:singleLine="true"/>

<!-- Login button -->


<Button android:id="@+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login"/>

</LinearLayout>

Activity_main.xml
<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:orientation="vertical" >

<TextView
android:id="@+id/lblName"
android:layout_width="wrap_content"
android:layout_height="63dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/btnLogout"
android:layout_toRightOf="@+id/imageView1"
android:singleLine="true"
android:width="10dp" />

<Button
android:id="@+id/btnLogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Logout" />

</RelativeLayout>

Das könnte Ihnen auch gefallen