After clicking on the login, how to write the data returned by the server to the specified control? , how does Android achieve Nikki? Below we through the concrete code carries on the analysis and the realization, hoped can to you, in the study Android knowledge to be helpful.
Here's a code description:
Package www.csdn.net.lesson03;
Import Java.io.ByteArrayOutputStream;
Import Java.io.InputStream;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import Java.net.URLEncoder;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.text.TextUtils;
Import Android.view.View;
Import Android.widget.EditText;
Import Android.widget.TextView;
Import Android.widget.Toast;
public class Loginactivity extends Activity {
Declaring a Control object
Private EditText et_name, Et_pass;
Declares a control object that returns a database
Private TextView Tv_result;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Set the displayed view
Setcontentview (R.layout.activity_login);
A control object that obtains a user name through the Findviewbyid (ID) method
Et_name = (EditText) Findviewbyid (r.id.et_name);
Control object that gets the user's password through the Findviewbyid (ID) method
Et_pass = (EditText) Findviewbyid (R.id.et_pass);
//Gets the control object that displays the returned data through the Findviewbyid (ID) method
Tv_result = (TextView) Findviewbyid (r.id.tv_result);
}
/**
* by android:onclick= the method specified by "Login", you are required to accept the parameter V of the control object in this method
*
* @param v
*/
public void Login (View v) {
Gets the ID of the click Control
int id = V.getid ();
How to handle the judgment based on the ID
Switch (ID) {
Handling of Login Events
Case R.id.btn_login:
Get user Name
Final String userName = Et_name.gettext (). toString ();
Get user Password
Final String Userpass = Et_pass.gettext (). toString ();
if (Textutils.isempty (userName) | | Textutils.isempty (Userpass)) {
Toast.maketext (This, "User name or password cannot be empty", Toast.length_long). Show ();
} else {
System.out
. println ("----------------------send request to Server----------------------");
Access the network (requires a network of permissions) <uses-permission
Android:name= "Android.permission.INTERNET"/>
Access to the network (time-consuming operations) avoid blocking the main thread (UI) by opening new child threads to handle
New Thread () {
public void Run () {
Calling the Loginbyget method
Loginbyget (UserName, Userpass);
};
}.start ();
}
Break
Default
Break
}
}
/**
* Requests sent by Get mode
*
* @param userName
* @param userpass
*/
public void Loginbyget (string userName, String userpass) {
try {
Set the requested address via Urlencoder.encode (string s, String enc)
Converts a string to the application/x-www-form-urlencoded format using the specified encoding mechanism
String spec = "Http://172.16.237.200:8080/video/login.do?username="
+ Urlencoder.encode (userName, "UTF-8") + "&userpass="
+ Urlencoder.encode (userpass, "UTF-8");
Create a URL object from an address (the URL of a network access)
URL url = new URL (spec);
Url.openconnection () Open Network link
HttpURLConnection URLConnection = (httpurlconnection) URL
. OpenConnection ();
Urlconnection.setrequestmethod ("GET");//How to set the request
Urlconnection.setreadtimeout (5000);//Set Time to timeout
Urlconnection.setconnecttimeout (5000);//Set link time-out
Set the header of the request
URLConnection
. Setrequestproperty ("User-agent",
"mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) gecko/20100101 firefox/27.0 ");
Get the status code for the response 404 200 505 302
if (urlconnection.getresponsecode () = = 200) {
Gets the input stream object for the response
InputStream is = Urlconnection.getinputstream ();
Creating a byte output stream object
Bytearrayoutputstream OS = new Bytearrayoutputstream ();
Defines the length of the read
int len = 0;
Defining buffers
byte buffer[] = new byte[1024];
Loop through the size of the buffer
while (len = is.read (buffer))! =-1) {
Writes to the OS object based on the length of the read
Os.write (buffer, 0, Len);
}
Freeing resources
Is.close ();
Os.close ();
return string
String result = new String (Os.tobytearray ());
System.out.println ("***************" + result+ "******************");
Here's what happens when you write the returned data on the control, Nikki.
Tv_result.settext (result);
} else {
System.out.println ("------------------link failed-----------------");
}
} catch (Exception e) {
E.printstacktrace ();
}
}
}
By adding red code for implementation, you will find the following bug:
05-24 06:38:37.987:w/system.err (1170): Android.view.viewrootimpl$calledfromwrongthreadexception:only the original Thread that created a view hierarchy can touch it views.05-24 06:38:37.997:w/system.err (1170): at Android.view.ViewRootI Mpl.checkthread (viewrootimpl.java:6094) 05-24 06:38:37.997:w/system.err (1170): at Android.view.ViewRootImpl.requestLayout (viewrootimpl.java:824) 05-24 06:38:38.007:w/system.err (1170): at Android.view.View.requestLayout (view.java:16431) 05-24 06:38:38.007:w/system.err (1170): at Android.view.View.requestLayout (view.java:16431) 05-24 06:38:38.007:w/system.err (1170): at Android.view.View.requestLayout (view.java:16431) 05-24 06:38:38.007:w/system.err (1170): at Android.view.View.requestLayout (view.java:16431) 05-24 06:38:38.007:w/system.err (1170): at Android.widget.RelativeLayout.requestLayout (relativelayout.java:352) 05-24 06:38:38.007:w/system.err (1170): at Android.view.View.requestLayout (view.java:16431) 05-24 06:38:38.007:w/system.err (1170): at ANDROID.WIdget. Textview.checkforrelayout (textview.java:6600) 05-24 06:38:38.007:w/system.err (1170): at Android.widget.TextView.setText (textview.java:3813) 05-24 06:38:38.007:w/system.err (1170): at Android.widget.TextView.setText (textview.java:3671) 05-24 06:38:38.017:w/system.err (1170): at Android.widget.TextView.setText (textview.java:3646) 05-24 06:38:38.017:w/system.err (1170): at Www.csdn.net.lesson03.LoginActivity.loginByGet (loginactivity.java:134) 05-24 06:38:38.027:w/system.err (1170): at Www.csdn.net.lesson03.loginactivity$1.run (loginactivity.java:67)
The cause of the error is:
only the original Threads created by View Hierarchy you can touch its controls. Therefore, the content of the returned data control is set only in the main thread.
So how to achieve the effect, we can use the activity to provide us with the Runonuithread (action), the implementation of the method, we want to set the return data control of the content in this method can be. The specific part of the code is as follows:
Returns a string of final strings result = new String (Os.tobytearray ()); System.out.println ("***************" + result+ "******************"); LoginActivity.this.runOnUiThread (New Runnable () {///) Modify UI control content in the main thread @overridepublic void run () {///to write the returned data on the control here What happens to Nick Tv_result.settext (result);});
The test results are as follows:
The above code is only for reference study, if you have questions please leave a message