Android : 简单login

本文介绍了一个基于Android平台的登录功能实现案例。通过使用HttpPost发送登录请求,并利用SharedPreferences存储用户名和密码,实现了用户登录验证及自动登录功能。文章还展示了如何进行HTTP请求、处理响应结果以及简单的UI交互。
  1 import java.io.BufferedReader;
  2 import java.io.IOException;
  3 import java.io.InputStream;
  4 import java.io.InputStreamReader;
  5 import java.io.UnsupportedEncodingException;
  6 import java.util.ArrayList;
  7 import java.util.List;
  8 import org.apache.http.HttpEntity;
  9 import org.apache.http.HttpResponse;
 10 import org.apache.http.HttpStatus;
 11 import org.apache.http.client.ClientProtocolException;
 12 import org.apache.http.client.HttpClient;
 13 import org.apache.http.client.entity.UrlEncodedFormEntity;
 14 import org.apache.http.client.methods.HttpGet;
 15 import org.apache.http.client.methods.HttpPost;
 16 import org.apache.http.impl.client.DefaultHttpClient;
 17 import org.apache.http.message.BasicNameValuePair;
 18 import org.omg.CORBA.NameValuePair;
 19 import android.app.Activity;
 20 import android.content.Context;
 21 import android.content.Intent;
 22 import android.content.SharedPreferences;
 23 import android.content.res.Resources;
 24 import android.os.Bundle;
 25 import android.util.Log;
 26 import android.view.View;
 27 import android.widget.Button;
 28 import android.widget.EditText;
 29 import android.widget.Toast;
 30 
 31 public class LoginActivity extends Activity {
 32     private EditText edittext_UserName;
 33     private EditText edittext_UserPassword;
 34     private Button btn_login;
 35     private String username, password;
 36 
 37     @Override
 38     protected void onCreate(Bundle savedInstanceState) {
 39         super.onCreate(savedInstanceState);
 40         setContentView(R.layout.login);
 41         edittext_UserName = (EditText) findViewById(R.id.edittext_UserName);
 42         edittext_UserPassword = (EditText) findViewById(R.id.edittext_UserPassword);
 43         btn_login = (Button) findViewById(R.id.btn_login);
 44         btn_login.setOnClickListener(new View.OnClickListener() {
 45 
 46             @Override
 47             public void onClick(View v) {
 48                 // TODO Auto-generated method stub
 49                 username = edittext_UserName.getText().toString();
 50                 password = edittext_UserPassword.getText().toString();
 51                 doLogin();
 52             }
 53         });
 54     }
 55 
 56     void doLogin() {
 57         Resources res = getResources();
 58         if (username != null && password != null
 59                 && !res.getString(R.string.hint_name).equals(username)
 60                 && !res.getString(R.string.hint_password).equals(password)) {
 61 
 62             String url = "http://www.zbwen.com/testPrj/login.action";
 63             List<NameValuePair> params = new ArrayList<NameValuePair>();
 64             params.add(new BasicNameValuePair("user.name", username));
 65             params.add(new BasicNameValuePair("user.password", password));
 66 
 67             String result = HttpUtil.sendPostHttpRequest(url, params);
 68             if (result != null && result.equals("success")) {
 69                 Storage.saveString(this"username", username);
 70                 Storage.saveString(this"password", password);
 71                 Intent intent = new Intent();
 72                 intent.setClass(LoginActivity.this, WelcomeActivity.class);
 73                 LoginActivity.this.startActivity(intent);
 74                 Toast.makeText(LoginActivity.this"Login success",
 75                         Toast.LENGTH_LONG).show();
 76             } else {
 77                 System.out.println("fail the request");
 78             }
 79         }
 80         else{
 81             System.out.println("fail the request");            
 82         }
 83         return;
 84     }
 85 
 86 }
 87 
 88 class HttpUtil {
 89 
 90     private static HttpClient httpClient = null;
 91 
 92     public static HttpClient getHttpClient() {
 93         if (httpClient == null) {
 94             httpClient = new DefaultHttpClient();
 95         }
 96         return httpClient;
 97     }
 98 
 99     public static String getJSONData(String url)
100             throws ClientProtocolException, IOException {
101         String result = "";
102         HttpGet httpGet = new HttpGet(url);
103         HttpClient httpClient = getHttpClient();
104         HttpResponse httpResponse = null;
105 
106         try {
107             httpResponse = httpClient.execute(httpGet);
108             HttpEntity httpEntity = httpResponse.getEntity();
109             if (httpEntity != null) {
110                 InputStream inputStream = httpEntity.getContent();
111                 result = convertStreamToString(inputStream);
112             }
113         } catch (ClientProtocolException e) {
114             // TODO Auto-generated catch block
115             e.printStackTrace();
116         } catch (IOException e) {
117             throw e;
118         } finally {
119             httpClient.getConnectionManager().shutdown();
120             httpResponse = null;
121         }
122         return result;
123 
124     }
125 
126     public static String sendPostHttpRequest(String url,
127             List<NameValuePair> params) {
128         HttpPost httpPost = new HttpPost(url);
129         try {
130             // HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8");
131             // httpPost.setEntity(httpEntity);
132             HttpClient httpClient = getHttpClient();
133             HttpResponse httpResponse = httpClient.execute(httpPost);
134             if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
135                 String result = "";
136                 if (httpResponse.getEntity() != null) {
137                     InputStream is = httpResponse.getEntity().getContent();
138                     result = convertStreamToString(is);
139                     return result.trim();
140                 }
141             } else {
142                 System.out.println("fail the request");
143             }
144 
145         } catch (Exception e) {
146             e.printStackTrace();
147         }
148         return null;
149     }
150 
151     public static String convertStreamToString(InputStream is) {
152         BufferedReader reader = null;
153         try {
154             reader = new BufferedReader(new InputStreamReader(is, "UTF-8"),
155                     512 * 1024);
156         } catch (UnsupportedEncodingException e1) {
157 
158             e1.printStackTrace();
159         }
160         StringBuilder sb = new StringBuilder();
161 
162         String line = null;
163         try {
164             while ((line = reader.readLine()) != null) {
165                 sb.append(line + "\n");
166             }
167         } catch (IOException e) {
168             Log.e("DataProvier convertStreamToString", e.getLocalizedMessage(),
169                     e);
170         } finally {
171             try {
172                 is.close();
173             } catch (IOException e) {
174                 e.printStackTrace();
175             }
176         }
177         return sb.toString();
178     }
179 }
180 
181 class Storage {
182     private static SharedPreferences getSharedPreferences(Context context) {
183         SharedPreferences sharedPreferences = context.getSharedPreferences(
184                 "userInfo", Context.MODE_WORLD_READABLE);
185         return sharedPreferences;
186     }
187 
188     public static void saveString(Context context, String key, String value) {
189         SharedPreferences sharedPreferences = getSharedPreferences(context);
190         sharedPreferences.edit().putString(key, value).commit();
191 
192     }
193 
194     public static String getString(Context context, String key) {
195         return getSharedPreferences(context).getString(key, "");
196     }
197 }

转载于:https://www.cnblogs.com/kofzhoubiwen/archive/2011/07/18/2109599.html

<?xml version="1.0" encoding="utf-8"?> <layout 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"> <data> <variable name="model" type="com.fshr.app.bean.sms.MyJobApplyBean" /> <import type="com.fshr.baseproject.utils.ConfigData" /> </data> <androidx.cardview.widget.CardView android:id="@+id/parent" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" app:cardCornerRadius="12dp" app:cardElevation="2dp"> <!-- Reduced elevation for a flatter look --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp"> <!-- Increased padding --> <!-- Application ID --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="申请表ID:" android:textColor="@color/grey_600" <!-- Lighter gray --> android:textSize="14sp" /> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_weight="1" android:text="@{model.id}" android:textColor="@color/black" android:textSize="16sp" android:textStyle="bold" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:background="@drawable/rounded_corner_reason_bg" android:gravity="center" android:paddingHorizontal="8dp" android:paddingVertical="4dp" android:text="@{ConfigData.INSTANCE.getParamLabel(ConfigData.INSTANCE.busi_work_appliacnt_status,model.applicationStatus,`待提交`)}" app:txColor="@{ConfigData.INSTANCE.getParamColor(ConfigData.INSTANCE.busi_work_appliacnt_status,model.applicationStatus)}" tools:text="Type" /> </LinearLayout> <!-- Applicant Information --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="12dp" <!-- Increased spacing --> android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="关联作业项目:" android:textColor="@color/grey_600" android:textSize="14sp" /> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_weight="1" android:text="@{model.project.projectName}" android:textColor="@color/black" android:textSize="16sp" /> </LinearLayout> <!-- Receiver Information --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="申请编号:" android:textColor="@color/grey_600" android:textSize="14sp" /> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_weight="1" android:text="@{model.project.operationNo}" android:textColor="@color/black" android:textSize="16sp" /> </LinearLayout> <!-- Expected Access Time --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="是否提级审批:" android:textColor="@color/grey_600" android:textSize="14sp" /> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_weight="1" android:text="@{ConfigData.INSTANCE.getParamLabel(ConfigData.INSTANCE.busi_common_yes_no,model.isHighLevel)}" android:textColor="@color/black" android:textSize="16sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="是否有危险源辨识和风险评价表:" android:textColor="@color/grey_600" android:textSize="14sp" /> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_weight="1" android:text="@{ConfigData.INSTANCE.getParamLabel(ConfigData.INSTANCE.busi_common_yes_no,model.isHazard)}" android:textColor="@color/black" android:textSize="16sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="是否有作业方案及评审情况:" android:textColor="@color/grey_600" android:textSize="14sp" /> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_weight="1" android:text="@{ConfigData.INSTANCE.getParamLabel(ConfigData.INSTANCE.busi_common_yes_no,model.isWorkPlan)}" android:textColor="@color/black" android:textSize="16sp" /> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:text="其他安全防护措施:" android:textColor="@color/grey_600" android:textSize="14sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:layout_marginTop="8dp" android:background="@drawable/rounded_corner_reason_bg" android:text="@{model.otherSafe }" android:textColor="@color/black" android:textSize="16sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/text_risk" android:layout_marginStart="8dp" android:text="管理危险辨识与风险评价" android:textColor="@color/blue" android:textSize="16sp" /> <TextView android:id="@+id/text_scheme" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_weight="1" android:gravity="right" android:visibility="@{model.isWorkPlan().equals(`1`)}" android:text="管理作业方案" android:textColor="@color/blue" android:textSize="16sp" /> </LinearLayout> <LinearLayout android:id="@+id/lin_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:orientation="horizontal" android:visibility="@{!ConfigData.INSTANCE.jobJsUpdate(model.applicationStatus)}"> <Button android:id="@+id/btn_appover" android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="1" android:background="@drawable/button_approve_background" android:stateListAnimator="@null" android:text="修改" android:textColor="@color/white" android:textSize="16sp" /> <Button android:id="@+id/btn_reject" android:layout_width="0dp" android:layout_height="40dp" android:layout_marginStart="16dp" android:layout_weight="1" android:background="@drawable/button_reject_background" android:stateListAnimator="@null" android:text="删除" android:textColor="@color/white" android:textSize="16sp" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> </layout> 从美观上帮我重新设计下排版,要求输入完整内容
07-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值