登陆界面,记住密码提交网络数据

来源:互联网 发布:销售管理数据流程图 编辑:程序博客网 时间:2024/05/16 09:33
package com.example.at;import java.security.PublicKey;import java.util.HashMap;import org.json.JSONException;import org.json.JSONObject;import com.example.at.httpUtil.HttpUtil;import android.support.v7.app.ActionBarActivity;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.SharedPreferences;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.CompoundButton.OnCheckedChangeListener;import android.widget.EditText;import android.widget.ImageButton;import android.widget.TextView;import android.widget.Toast;public class Login extends Activity {private ImageButton loginButton;private EditText nameEditText;private EditText passwordeEditText;private CheckBox checkBox;SharedPreferences preferences; //用于存储用户名密码实现记住密码功能private static final String urlString = "http://v.cc-railway.xzh-soft.com:8082/oa/login.json";    //handler接收网络请求resultpublic Handler handler = new Handler(){    public void handleMessage(android.os.Message msg) {    try {JSONObject result = new JSONObject((String)msg.obj);String st = (String) result.get("error");Toast.makeText(Login.this, st, 2).show();} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}    };    };    @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_login);initview();initevent();}//初始化组件public void initview() {loginButton = (ImageButton) this.findViewById(R.id.login_bt);nameEditText = (EditText) this.findViewById(R.id.nameEditText);passwordeEditText = (EditText) this.findViewById(R.id.passwordeEditText);checkBox = (CheckBox) this.findViewById(R.id.checkbox);    preferences = getPreferences(Activity.MODE_PRIVATE);String username = preferences.getString("username", "");String password = preferences.getString("password", "");if(username!=null&&password!=null&&!username.equals("")&&!password.equals("")){nameEditText.setText(username);passwordeEditText.setText(password);}}//注册事件监听public void initevent() {loginButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stub                          final HashMap<String, String> nameValues = new HashMap<String, String>();              nameValues.put(nameEditText.getText().toString(),passwordeEditText.getText().toString() );             //新起线程提交网络数据  android最近的版本访问网络为了防止OOM必需在新的线程中进行无论操作是否复杂。              new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubString result = HttpUtil.dopost(Login.this, urlString, nameValues);Message msg= handler.obtainMessage();msg.obj = result;handler.sendMessage(msg);}}).start();              //将用户名密码放入sharedPreferences              if (checkBox.isChecked()) {              preferences = getPreferences(Activity.MODE_PRIVATE);  SharedPreferences.Editor editor = preferences.edit();  editor.putString("username", nameEditText.getText().toString());  editor.putString("password", passwordeEditText.getText().toString());  editor.commit();}                            Toast.makeText(Login.this, "登录", 2).show();}});checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {// TODO Auto-generated method stubif (isChecked) {//buttonView.setBackgroundResource(R.drawable.img_switch_on);preferences = getPreferences(Activity.MODE_PRIVATE);SharedPreferences.Editor editor = preferences.edit();editor.putString("username", nameEditText.getText().toString());editor.putString("password", passwordeEditText.getText().toString());editor.commit();               } else {//buttonView.setBackgroundResource(R.drawable.img_switch_off);}}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.login, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}

以上是 login登录逻辑。下面是布局

<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:background="@drawable/bg_login"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.at.Login" >    <LinearLayout        android:id="@+id/linearLayout1"        android:layout_width="250dp"        android:layout_height="60dp"        android:layout_below="@+id/imageView1"        android:layout_centerHorizontal="true"        android:layout_marginTop="14dp"        android:background="@drawable/bg_login_text"        android:orientation="vertical" >        <EditText            android:id="@+id/nameEditText"            android:layout_width="fill_parent"            android:layout_height="30dp"            android:background="@null"            android:hint="用户名"            android:inputType="textPersonName"           android:layout_marginLeft="5dp"            android:paddingRight="0dp"            android:textSize="15dp" />        <ImageView            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:src="@drawable/bg_login_line" />        <EditText            android:id="@+id/passwordeEditText"            android:layout_width="fill_parent"            android:layout_height="30dp"            android:gravity="center_vertical"            android:hint="密码"            android:inputType="textPassword"            android:background="@null"            android:layout_marginLeft="5dp"            android:textSize="15dp" />    </LinearLayout>    <ImageButton        android:id="@+id/login_bt"        android:layout_width="250dp"        android:layout_height="35dp"        android:layout_below="@+id/linearLayout1"        android:layout_centerHorizontal="true"        android:layout_marginTop="10dp"                android:background="@drawable/btn_login" />    <CheckBox        android:id="@+id/checkbox"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/login_bt"        android:layout_below="@+id/login_bt"        android:layout_marginTop="10dp"        android:text="記住密碼" />    <ImageView        android:id="@+id/imageView1"        android:layout_width="200dp"        android:layout_height="100dp"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:layout_marginTop="26dp"        android:src="@drawable/img_logo" /></RelativeLayout>

工具类httputil


import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import org.apache.http.HttpEntity;import org.apache.http.HttpRequest;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.BasicHttpContext;import org.apache.http.protocol.HTTP;import org.apache.http.protocol.HttpContext;import com.example.at.Login;import android.app.Activity;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.content.DialogInterface.OnClickListener;import android.widget.Toast;public class HttpUtil {public Context context;public HttpUtil(Context context){this.context = context;}public HttpUtil(){}public static String dopost(Context context,String urlString,HashMap<String, String> nameValues){String result = "";HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(urlString);List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();Iterator iterator = nameValues.entrySet().iterator();while(iterator.hasNext()){Map.Entry entry= (Entry) iterator.next();String key =  (String) entry.getKey();String value = (String) entry.getValue();nameValuePairs.add(new BasicNameValuePair(key, value));}System.out.println(nameValuePairs);try {post.setEntity(new UrlEncodedFormEntity(nameValuePairs ,HTTP.UTF_8));HttpResponse response = client.execute(post);if (response.getStatusLine().getStatusCode() == 403) {new AlertDialog.Builder(context).setTitle("登录提示").setMessage("异地登陆,请重新登录").setNegativeButton("确定", new OnClickListener() {@Overridepublic void onClick(DialogInterface arg0, int arg1) {// TODO Auto-generated method stub}}).show();}else if(response.getStatusLine().getStatusCode() !=200){new AlertDialog.Builder(context).setTitle("登录提示").setMessage("登錄失敗").setNegativeButton("确定", new OnClickListener() {@Overridepublic void onClick(DialogInterface arg0, int arg1) {// TODO Auto-generated method stub}}).show();}else {//Toast.makeText(context, "dljdl", 2).show();HttpEntity entry = response.getEntity();if (entry != null) {BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entry.getContent(),"UTF-8"));String lineString = "";while ((lineString = bufferedReader.readLine())!=null) {result+=lineString;}if (entry != null) {entry.consumeContent();}}}post.abort();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(result);return result;}//public String doPost(Activity activity,String url,String[][] nameValues) {//HttpClient httpclient = new DefaultHttpClient(); ////String returnStr = "";//HttpContext context = new BasicHttpContext();//HttpEntity entity = null;//HttpPost httppost = new HttpPost(url);//try {//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); ////Your DATA //for (int i = 0; i < nameValues.length; i++) {//nameValuePairs.add(new BasicNameValuePair(nameValues[i][0], nameValues[i][1])); //}//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8)); ////HttpResponse response = httpclient.execute(httppost, context);//if(response.getStatusLine().getStatusCode() == 403){////TotalActivity.showLoginOutDialog();//new AlertDialog.Builder(activity)//.setTitle("登录提示")//.setMessage("当前帐户已在异地登陆,请重新登录!")//.setNegativeButton("取消", new DialogInterface.OnClickListener() {////@Override//public void onClick(DialogInterface dialog, int which) {//// TODO Auto-generated method stub////}//}).setNeutralButton("确定", new DialogInterface.OnClickListener() {////@Override//public void onClick(DialogInterface dialog, int which) {//// TODO Auto-generated method stub//}//}).show();//}else {//entity = response.getEntity();//if (entity != null) {//BufferedReader reader = new BufferedReader(//new InputStreamReader(entity.getContent(), "UTF-8"));//String line = null;//while ((line = reader.readLine()) != null) {//returnStr += line;//}//if (entity != null) {//entity.consumeContent();//}//// 释放资源给manger//}//httppost.abort();//}////} catch (UnsupportedEncodingException e) {//e.printStackTrace();//} catch (ClientProtocolException e) {//e.printStackTrace();//} catch (IllegalStateException e) {//e.printStackTrace();//} catch (IOException e) {//e.printStackTrace();//}catch (Exception e) {//// TODO: handle exception//}//System.out.println("returnstr:"+returnStr);//return returnStr;//}}



0 0
原创粉丝点击