Android practices (1)

Source: Internet
Author: User

I remember that I was worried about which development language I used to develop android in the previous article. Recently I used C # To develop android, which is not so nice. It is not convenient to query information, so I decided to use java for development. After all, I have learned java and the eclipse environment is no stranger. Let's get started. It's cold. First

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/12015410O-0.jpg "title =" QQ20131227213939.jpg "alt =" 221701997.jpg"/>

This figure is taken from the real machine. This is a logon interface. After the user enters the user name and password, the user passes the verification and jumps to another Activity. In this case, Android calls. net WebService.

OK. Check the Service first.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201544H3-1.jpg "title =" QQ20131227222103.jpg "alt =" 222008451.jpg"/>
Very familiar with simple structures. Let's take a brief look at the Service code.

Namespace GRLC. webService {// <summary> // Login summary description /// </summary> [WebService (Namespace = "http://tempuri.org/")] [WebServiceBinding (ConformsTo = WsiProfiles. none)] [System. componentModel. toolboxItem (false)] // to allow ASP.. net ajax calls this Web service from a script. uncomment the following lines. // [System. web. script. services. scriptService] public class LoginService: System. web. services. webService {[WebMethod] public LoginResponse CheckLogin (string userNo, string pwd) {return LoginBiz. getInstance (). checkLogin (userNo, pwd );}}}

There's nothing to say. Now let's look at the Biz layer.

public class LoginBiz   {       static LoginBiz loginBiz = new LoginBiz();       private LoginBiz()       { }       public static LoginBiz GetInstance()       {           return loginBiz;       }       public LoginResponse CheckLogin(string name, string pwd)       {           return LoginDAL.GetInstance().CheckLogin(name, pwd);       }   }

Nothing to say. Let's look at the Dal layer.

public class LoginDAL   {       static LoginDAL loginDAL = new LoginDAL();       private LoginDAL()       { }       public static LoginDAL GetInstance()       {           return loginDAL;       }       const string moduleName = "LoginModule";       BonusEntities bonusEntities = new BonusEntities();       private string PwdIsNotCorrect       {           get           {               return this.GetMessageByName("PwdNotCorrect");           }       }       private string UserNotExists       {           get           {               return this.GetMessageByName("UserNotExists");           }       }       private string GetMessageByName(string msgName)       {           return CommonFunction.GetMessageByModuleAndName(moduleName, msgName);       }       public LoginResponse CheckLogin(string name, string pwd)       {           User user = bonusEntities.User.SingleOrDefault(u => u.UseNo == name);           if (user != null)           {               string passWord = Cryptor.Decrypt(user.Pwd);               if (!passWord.Equals(pwd))               {                   return new LoginResponse() { IsSuccess = false, FailMsg = PwdIsNotCorrect };               }               return new LoginResponse() { IsSuccess = true };           }           else           {               return new LoginResponse() { IsSuccess = false, FailMsg = UserNotExists };           }       }   }

Here, EntityFrameWork is used as the real data access layer. I mapped all tables at one time.

Here we need to talk about the GetMessageByModuleAndName method.

public class CommonFunction    {        private static string BaseDirectory        {            get            {                return AppDomain.CurrentDomain.BaseDirectory;            }        }        private static List<ServiceMessage> GetMessageList()        {            List<ServiceMessage> messageList = new List<ServiceMessage>();            string messageConfigFolder = Path.Combine(BaseDirectory, ConfigHelper.MessageConfigFolder);            if (!Directory.Exists(messageConfigFolder)) return null;            string[] files = Directory.GetFiles(messageConfigFolder, "*.xml", SearchOption.TopDirectoryOnly);            foreach (string file in files)            {                ServiceMessage message = SerializeHelper.XmlDeSerializeByFile<ServiceMessage>(file);                messageList.Add(message);            }            return messageList;        }        public static string GetMessageByModuleAndName(string moduleName, string msgName)        {            string message = string.Empty;            ServiceMessage serviceMsg = new ServiceMessage();            List<ServiceMessage> serviceMessageList = CommonFunction.GetMessageList();            List<MessageEntityCollection> messageEntityCollection = serviceMessageList.Select(m => m.messageEntityCollection).ToList();            foreach (var msgEntityCollection in messageEntityCollection)            {                MessageEntity messageEntity = msgEntityCollection.SingleOrDefault(msgEntity => msgEntity.Module == moduleName && msgEntity.Name == msgName);                if (messageEntity != null)                {                    message = messageEntity.Content;                    break;                }            }            return message;        }    }

First, this method will first obtain the configuration folder of the prompt information from the configuration file, then traverse the xml file, and put the prompt information in all xml files into a List through deserialization, that is, the GetMessageList () method above. In fact, we can optimize the code here, as shown below:

private static List<ServiceMessage> _serviceMessageList;        private static List<ServiceMessage> ServiceMessageList        {            get            {                if (_serviceMessageList == null)                {                    _serviceMessageList = GetMessageList();                    return _serviceMessageList;                }                else                {                    return _serviceMessageList;                }            }        }

When obtaining the object, the system first checks whether _ serviceMessageList exists. If yes, the system no longer reads the object.

Let's take a look at this configuration file.

<? Xml version = "1.0" encoding = "UTF-8"?> <ServiceMessages> <Message Module = "LoginModule" Name = "PwdNotCorrect" Content = "Incorrect password! "> </Message> <Message Module =" LoginModule "Name =" UserNotExists "Content =" the user Name does not exist! "> </Message> </ServiceMessages>

The corresponding entity is as follows:

namespace GRLC.Model.Config{    [XmlRoot("ServiceMessages")]    public class ServiceMessage    {        [XmlElement("Message")]        public MessageEntityCollection messageEntityCollection { get; set; }    }    public class MessageEntityCollection : KeyedCollection<string, MessageEntity>    {        protected override string GetKeyForItem(MessageEntity messageEntity)        {            return messageEntity.Name;        }    }    [XmlRoot("Message")]    public class MessageEntity    {        [XmlAttribute("Name")]        public string Name { get; set; }        [XmlAttribute("Module")]        public string Module { get; set; }        [XmlAttribute("Content")]        public string Content { get; set; }    }}

Therefore, after obtaining the msg, you can obtain the corresponding content based on its module and name. Well, the above is the. net service end. After that, deploy it.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201541210-2.jpg "title =" QQ20131227220023.jpg "alt =" 230437715.jpg"/>

Note the following during deployment:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201542128-3.jpg "title =" QQ20131227220116.jpg "alt =" 230534281.jpg"/>

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201545126-4.jpg "title =" QQ20131227220247.jpg "alt =" 230552505.jpg"/>


Next, let's take a look at the development of the app.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201543555-5.jpg "title =" QQ20131227224509.jpg "alt =" 224421241.jpg"/>

We have a total of two activities: main and index. The main interface is successfully redirected to the index interface.

Let's take a look at the mai interface code.

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/layMain"    android:layout_width="fill_parent" android:layout_height="fill_parent"    android:paddingLeft="10dp" android:paddingRight="10dp"    android:orientation="vertical"    android:gravity="center_vertical">    <LinearLayout android:orientation="horizontal"        android:gravity="center_vertical" android:layout_width="fill_parent"        android:layout_height="wrap_content">        <TextView android:id="@+id/labUserName"            android:text="@string/labUserName"            android:layout_width="70dp"            android:layout_height="wrap_content"            android:textSize="18dp"            android:textStyle="bold"></TextView>        <EditText android:id="@+id/txtUserName"            android:hint="@string/hintInputUserNo"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:singleLine="true"></EditText>    </LinearLayout>    <LinearLayout android:orientation="horizontal"        android:layout_width="fill_parent" android:layout_height="wrap_content">        <TextView android:id="@+id/labPwd"            android:text="@string/labPwd"            android:layout_width="70dp"            android:layout_height="wrap_content"            android:textSize="18dp"            android:textStyle="bold"></TextView>        <EditText android:id="@+id/txtPwd"            android:hint="@string/hintInputUserPwd"            android:layout_height="wrap_content"            android:layout_width="fill_parent"            android:singleLine="true"            android:password="true"></EditText>    </LinearLayout>    <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent"        android:gravity="center_horizontal" android:layout_height="wrap_content">        <CheckBox android:id="@+id/chkDisplayPwd"        android:layout_width="130dp"        android:layout_height="wrap_content"        android:text="@string/chkDisplayPwd">        </CheckBox>        <Button android:id="@+id/btnLogin" android:text="@string/btnLoginText"            android:layout_width="80dp" android:layout_height="wrap_content"></Button>            <Button android:id="@+id/btnCancel" android:text="@string/btnCancelText"            android:layout_width="80dp" android:layout_height="wrap_content"></Button>    </LinearLayout></LinearLayout>

Linear layout is used. Running is the figure I posted at the beginning. OK. Let's take a look at OnCreate first.


final static String NAMESPACE = "http://tempuri.org/";    final static String METHOD_NAME = "CheckLogin";    final static String SOAP_ACTION = "http://tempuri.org/CheckLogin";    final static String URL = "http://10.0.2.2:2000/LoginService.asmx?wsdl";    EditText txtUserno;    EditText txtPwd;    Button btnLogin;    Button btnCancel;    CheckBox chkDisplay;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        btnLogin = (Button) this.findViewById(R.id.btnLogin);        btnCancel=(Button) this.findViewById(R.id.btnCancel);        txtUserno = (EditText) this.findViewById(R.id.txtUserName);        txtPwd = (EditText) this.findViewById(R.id.txtPwd);        chkDisplay = (CheckBox) this.findViewById(R.id.chkDisplayPwd);        btnLogin.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                String userNo = txtUserno.getText().toString().trim();                String pwd = txtPwd.getText().toString().trim();                Login(userNo, pwd);            }        });        btnCancel.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                txtUserno.setText("");                txtPwd.setText("");            }        });        chkDisplay.setOnCheckedChangeListener(new OnCheckedChangeListener() {            public void onCheckedChanged(CompoundButton cmpButton,                    boolean isChecked) {                if (isChecked) {                    txtPwd                            .setTransformationMethod(HideReturnsTransformationMethod                                    .getInstance());                } else {                    txtPwd.setTransformationMethod(PasswordTransformationMethod                            .getInstance());                }            }        });    }

The webservice information we need to call is declared at the top of the page. Note that 10.0.2.2 is the built-in android IP address, which is the IP address used by android to access your local computer. If you use 127.0.0.1, you are accessing your mobile phone. In the Oncreate method of your local machine, we have registered the event response for the button. Login and cancellation, we also see a checkBox, which is used to show the plaintext of the password. If not selected, as shown in the following figure

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201542152-6.jpg "title =" QQ20131227230256.jpg "alt =" 230208396.jpg"/> 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201543A1-7.jpg "title =" QQ20131227230149.jpg "alt =" 230309988.jpg"/>

OK. After reading the checkBox, we can see the logon.

Public void Login (String userNo, String passWord) {if (! CheckUserInput (userNo, passWord) {return;} SoapObject response = this. getServerResponse (userNo, passWord); boolean isSuccess = Boolean. valueOf (response. getProperty ("IsSuccess "). toString (); if (! IsSuccess) {String failMsg = response. getProperty ("FailMsg "). toString (); new AlertDialog. builder (this ). setTitle (R. string. warningMsgTitle ). setMessage (failMsg ). setIcon (R. drawable. warning ). setPositiveButton ("OK", null ). show () ;}else {Intent intent = new Intent (); Bundle bundle = new Bundle (); bundle. putString ("userNo", userNo); intent. putExtras (bundle); intent. setClass (main. this, index. class); startActivityForResult (intent, 0); finish ();}}

When logging on, the system will first checkInput.

Private boolean CheckUserInput (String userNo, String passWord) {if (userNo. equals ("") {new AlertDialog. builder (this ). setTitle (R. string. warningMsgTitle ). setMessage (R. string. userNoIsEmpty ). setIcon (R.drawable.info ). setPositiveButton ("OK", new DialogInterface. onClickListener () {public void onClick (DialogInterface dialoginterface, int I) {txtUserno. requestFocus ();}}). show (); return false;} if (passWord. equals ("") {new AlertDialog. builder (this ). setTitle (R. string. warningMsgTitle ). setMessage (R. string. userPWdIsEmpty ). setIcon (R.drawable.info ). setPositiveButton ("OK", new DialogInterface. onClickListener () {public void onClick (DialogInterface dialoginterface, int I) {txtPwd. requestFocus ();}}). show (); return false;} return true ;}

CheckInput is very simple. If it is null, a prompt is displayed, as shown below:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201542P5-8.jpg "title =" QQ20131227231027.jpg "alt =" 231011783.jpg"/> 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201542443-9.jpg "title =" QQ20131227231126.jpg "alt =" 231029559.jpg"/>

OK. If the input is not empty, two parameters are required to call WebService.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201542246-10.jpg "title =" QQ20131227231544.jpg "alt =" 231438392.jpg"/>

Take a look at the code

private SoapObject GetServerResponse(String userNo, String passWord) {        SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);        PropertyInfo pi = new PropertyInfo();        pi.setName("userNo");        pi.setType(String.class);        pi.setValue(userNo);        Request.addProperty(pi);        pi = new PropertyInfo();        pi.setName("pwd");        pi.setType(String.class);        pi.setValue(passWord);        Request.addProperty(pi);        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(                SoapEnvelope.VER11);        soapEnvelope.dotNet = true;        soapEnvelope.setOutputSoapObject(Request);        HttpTransportSE httpTS = new HttpTransportSE(URL);        try {            httpTS.call(SOAP_ACTION, soapEnvelope);        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (XmlPullParserException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        SoapObject result = null;        try {            result = (SoapObject) soapEnvelope.getResponse();        } catch (SoapFault e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return result;    }

Call WebService and return the SoapObject object. Do not forget to reference ksoap when calling WebService.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201544436-11.jpg "title =" QQ20131227231851.jpg "alt =" 231730297.jpg"/>

If not, download one by yourself. After a successful call is returned, if IsSuccess is true, it will jump directly to the index and pass the userNo that has been successfully logged on to the index. If logon fails, a prompt message is displayed. However, the tragedy is that my real machine reported an error and did not access webservice. Later, I connected the wlan with my mobile phone, and the IP address was changed or an error was reported.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1201543119-12.jpg "title =" QQ20131228000214.jpg "alt =" 000058489.jpg"/>

There is no problem with accessing the wireless IP address on the computer, as shown below:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/120154O11-13.jpg "title =" QQ20131228000337.jpg "alt =" 000215771.jpg"/>

However, the real machine cannot be connected, but the simulator can be accessed normally with 10.0.2.2. Please wait for the next article to solve this problem.

This article is from the "technology creates value" blog, please be sure to keep this source http://leelei.blog.51cto.com/856755/1345860

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.