Detailed Android socket communications, list loading more, spinner Drop-down list _android

Source: Internet
Author: User
Tags addall flush getdate socket xmlns port number

There are two main modes of communication between Android and Server, one is HTTP communication and the other is socket communication. The biggest difference between the two is that the HTTP connection uses a "request-response" approach, where the connection channel is established at the request, and the server can return the data to the client after the client sends a request to the server. While the socket communication is to establish a connection after the two sides can directly carry out data transmission, in connection with the implementation of the information of the active push, and do not need every time the client wants to send the server request. So, what is a socket? Socket, also known as sockets, in the program to provide a communication with the outside port, that is, port communication. By establishing the socket connection, it can provide the channel for the data transmission of both sides of communication. The main features of the socket are low data loss rate, easy to use and easy to transplant.

1.1 What is a socket

is an abstraction layer through which applications can send and receive data, and sockets allow applications to be added to the network to communicate with other applications on the same network. In short, the socket provides a port for the program to communicate with the outside world and provides a data transfer channel for both sides of the communication.

Classification of 1.2Socket

Depending on the underlying protocol, the socket is implemented in a variety of ways. This guide describes only the contents of the TCP/IP protocol family, where the main socket type is a stream socket (streamsocket) and a datagram socket (datagramsocket). Stream sockets offer TCP as its End-to-end protocol, which provides a reliable word throttling service. Datagram sockets use the UDP protocol to provide data packaging and delivery services. Next, let's take a look at the basic implementation model for both types of sockets.

1.3Socket Simple example:

Server-side Socket service code:

public class MyServer {public
  static void Main (string[] args) throws exception{serversocket
    ss = new Serversocke T (555);
    Socket s = ss.accept ();
    DataInputStream dis = new DataInputStream (S.getinputstream ());
    DataOutputStream dos = new DataOutputStream (S.getoutputstream ());
    String str = DIS.READUTF ();
    System.out.print ("Client is connected");
    Dos.writeutf ("Server:" +str);
    Dos.flush ();
    Dis.close ();
    S.close ();
    Ss.close ();
  } 

Code for the Android client:

public class Mainactivity extends activity {public static Button MyButton = null;//Send socket request public static TextView MyText = null;//Displays the value returned by the server @Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinst
    Ancestate);
    Setcontentview (R.layout.activity_main);
    MyButton = (Button) Findviewbyid (R.id.button);
    MyText = (TextView) Findviewbyid (R.id.text);

  Mybutton.setonclicklistener (New Mybuttonlistener ());
    //button Click event class Mybuttonlistener implements onclicklistener{printstream out = null;
    BufferedReader buf = null;
    Socket s = null; public void OnClick (View v) {try {s = new socket ("10.20.90.3", 555);//Create an IP address: 10.20.90.3, port number: 555 Socket Object DataOutputStream dos = new DataOutputStream (S.getoutputstream ());//get an output stream datainputstream dis = new Da Tainputstream (S.getinputstream ())//get an input stream Dos.writeutf ("The ACM Association of Henan Polytechnic University");//Request value sent to the server String str = dis.read
      UTF ()//Get the parameters returned by the server  Mytext.settext (str);
        Dos.flush ();
        Dos.close ();
        Dis.close ();
      S.close ();
      catch (Unknownhostexception e) {e.printstacktrace ();
      catch (IOException e) {e.printstacktrace ();
 }
    }
  }
}

The simplest of a server <---> Client socket case is implemented, before the client program executes, need to first start the server-side program, when the server-side startup is complete, we can send the socket request through the Android client. In this case, we send to the server side: "The ACM Association of Henan Polytechnic University" field, the server returned to us: "Server: the ACM Association of Henan Polytechnic University". The code is very simple, of course, the knowledge of the socket is absolutely not only contains these, the rest is to see whether the small partners are interested.

For the list on the slide load more, the network has a lot of open source control, the next I will lead you to study together, how to achieve the list on the slide load more.

First is the layout file for our main activity, and the layout file has no other content but one ListView control:

<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 "
tools:context= "${relativepackage}.${activityclass}" >
  <listview 
    android:id= "@+id/listview"
    android:layout_width= "fill_parent"
    android:layout_height= "wrap_content"
    android:visibility= "Gone" >
  </ListView>
</RelativeLayout>

Our main activity code:

public class Mainactivity extends activity {private ListView ListView;//list container private list<string> data = NE
  W arraylist<string> ()//temporary storage of data containers private arrayadapter<string> adapter; Private final int number = 30;//of data per page private final int maxpage = number of pages of 5;//data private int itemcount;//display Records private
  int nextpage; Private Boolean flag = true;  Indicates whether loading data completes private View tipview;//footer View @SuppressLint ("Inflateparams") @Override protected void OnCreate (Bundle
    Savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.listview_main);
    ListView = (ListView) Findviewbyid (R.id.listview); Listview.setonscrolllistener (New Scrolllistener ())//Sliding Event monitor Listview.setonitemclicklistener (new
     Onitemclicklistener ())//Click event Monitor Tipview = Getlayoutinflater (). Inflate (R.layout.listview_tip, null);/Get load more footers/* * First load/data.addall (new Datascroll (). GetDate (0, 30))//Get the data that the first page needs to display adapter = new arrayadapter&Lt String> (Getapplicationcontext (), R.layout.listview_item, R.id.textview, data)//matching data to the corresponding data display page * * Add footer must be based on Face Format/Listview.addfooterview (Tipview);//Add footer (before loading data) Listview.setadapter (adapter);/must load footer before this sentence listvi
    Ew.removefooterview (Tipview)//delete footer Display} Public final class Scrolllistener implements onscrolllistener{@Override public void onscrollstatechanged (Abslistview view, int scrollstate) {} @Override public void Onscroll (ABSL Istview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {int lastitemid = listview.ge Tlastvisibleposition ()//To obtain the ID if ((lastitemid+1) ==totalitemcount) of the last record of screen item {//To determine if it has been dragged to the page no if (Totalitemcou NT > 0) {//To determine if the data being loaded is the last page of data int currentpage = totalitemcount%number==0? totalitemcount/number:totalitemcoun
          t/number+1;
          NextPage = currentpage + 1;
            if (nextpage<=maxpage && flag) {flag = false; IteMcount = Totalitemcount; Listview.addfooterview (Tipview)//Show load more footers new Thread (new Runnable () {@Override P
                ublic void Run () {//Analog Network Load data try {thread.sleep (3000);//Analog Network Load
                catch (Interruptedexception e) {e.printstacktrace ();
                } datascroll Datascroll = new Datascroll ();
                list<string> result = Datascroll.getdate (nextpage, number);
              Hand.sendmessage (hand.obtainmessage, result);
          }). Start (); }} if (0==firstvisibleitem) {if (Firstvisibleitem < 0) {Toast.maketext (mainactiv
        Ity.this, "Refresh", Toast.length_short). Show (); }}//Back to main thread execution Handler Hand = new Handler () {@SuppressWarnings ("unchecked") @SuppressLint ("H Andlerleak ") public void Handlemessage (msg) {daTa.addall ((list<string>) msg.obj);
        Adapter.notifydatasetchanged ()///Tell ListView data has changed, request Update ListView interface if (Listview.getfooterviewscount () >0) {
      Listview.removefooterview (Tipview);
    } flag = true;
  }
  }; Click event class Onitemclicklistener implements onitemclicklistener{@Override public void Onitemclick for item in list (Ad Apterview<?> Parent, view view, int position, long id) {Toast.maketext (Getapplicationcontext (), posit
    ion+ "" +id, Toast.length_short). Show ();
 }
  }
}

Next we need to add the layout of our item (listview_item.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=" Wrap_content "
  android:background= "#aa00ff"  tools:context= "${relativepackage}.${activityclass}" >
  <textview
    android:id= "@+id/textview"
    android:layout_width= "fill_parent"
    android:layout_height= "60DP"
    android:textsize= "18SP"
    android:textcolor= "#aa0000"
    android:singleline= "true"
    />
</RelativeLayout>

Of course since it is loaded more, we also need a prompt user is loading more than one footer (listview_tip.xml):

<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 "
tools:context= "${relativepackage}.${activityclass}" >
  <progressbar
    android:id= "@+id/ ProgressBar1 "
    android:layout_width=" wrap_content "
    android:layout_height=" Wrap_content "
    android: Layout_alignparentleft= "true"
    android:layout_below= "@+id/textview"/>
  <textview
    android:id = "@+id/textview"
    android:layout_width= "wrap_content"
    android:layout_height= "Wrap_content"
    Android:layout_gravity= "center_vertical"
    android:textsize= "18sp"
    android:textcolor= "#000000"
    Android:singleline= "true"
    android:text= "Data Loading ..."/>
</LinearLayout>

Of course, the most important loading data here is that we do not load more data over the network for the sake of simplicity, but a simulated load (Datascroll.java) implemented by a simulated load function class:


 * * Simulation to obtain paging data
/public class Datascroll {public
  list<string> getDate (int nextpage, int Maxresult) {
    int offset = 0;
    if (nextpage!=0) {
      offset = (nextpage-2) *maxresult;
    }
    list<string > List = new arraylist<string> ();
    for (int i=0; i<maxresult; i++) {
      list.add ("List data batch load" + ++offset);
    }
    return list;
  }

Well, our top slide load more implementation for everyone to share over, on the slide refresh, the small partners can monitor the user through the slide event, from the line research, very simple believe that everyone can achieve, there are questions welcome to the message discussion.

Spinner:android provides a drop-down list control , next I will pass 5 small examples, to introduce you to the Spinner system with the style and custom style, of course, the system with a relatively simple style, we start with a simple, For everyone to introduce the use of spinner.

The first is the layout file:

<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 "Tools:context" = "${relativepackage}.${activityclass}" > <linearlayout android:id= "@+id/linearone" android:layout_width= " Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical "> <textview A Ndroid:id= "@+id/textview" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Andro id:text= "spinner Drop-down List" android:textsize= "25dip" android:layout_gravity= "Center_horizontal"/> <spinne 
      R android:id= "@+id/spinner1" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:entries= "@array/arr android:spinnermode=" dropdown "/> <spinner android:id=" @+id/ Spinner2 "Android:layout_width=" wrap_content"Android:layout_height=" wrap_content "android:entries=" @array/brr "android:spinnermode=" dialog " /> <spinner android:id= "@+id/spinner3" android:layout_width= "Wrap_content" Android:layout_heig
      ht= "Wrap_content"/> <spinner android:id= "@+id/spinner4" android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:spinnermode= "dialog"/> <spinner android:i D= "@+id/spinner5" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:spin
      nermode= "dialog"/> <button android:id= "@+id/buttonone" android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:text= "next page"/> </LinearLayout> </relativelayout&
 Gt

The first two controls use the Android spinner Drop-down list style, and the red part is the value I set in the Res->values->strings file:

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
  <string name= "app_name" > Drop-down list </ string> <string name= hello_world ">hello world!</string> <string-array name=" arr "
  >
    <item> Default effect </item>
    <item> Henan </item>
    <item> Beijing </item>
    < item> Shanghai </item>
  </string-array>
  <string-array name= "BRR" >
    <item> Pop-up Effect </item>
    <item> Henan </item>
    <item> Beijing </item>
    <item> Shanghai </item >
  </string-array>
</resources>

Main Activity code:

public class Activityone extends activity {private Spinner spin1;//default Spinner, display private Spinner below the button spin2;//default Spinn Er, in the form of dialog for the user to show the private Spinner spin3;//custom Spinner, under the button display private Spinner spin4;//custom Spinner, through the form of dialog for users to show P
  Rivate Spinner spin5;//Custom Spinner, in the form of dialog to show the user private Button buttonone;
  Private String [] array = new string [] {array reference, ' rep ', ' group leader ', ' Little Sister '};
  Private String [] arrayadapt = new string [] {"ARRAYADAPT reference", "representative", "leader", "Little Sister"};
  Private list<string> List = new arraylist<string> ();
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_one);
    List.add ("list Reference");
    List.add ("representative");
    List.add ("group leader");
    List.add ("Little Sister");
    Buttonone= (Button) Findviewbyid (R.id.buttonone);
    spin1= (Spinner) Findviewbyid (r.id.spinner1);
    Spin2= (Spinner) Findviewbyid (R.ID.SPINNER2); Spin3= (SpinNER) Findviewbyid (R.ID.SPINNER3);
    spin4= (Spinner) Findviewbyid (R.ID.SPINNER4);
    spin5= (Spinner) Findviewbyid (R.ID.SPINNER5); arrayadapter<string> arrayadapter = new Arrayadapter<string> (Activityone.this, Android.
    R.layout.simple_spinner_item, ARRAYADAPT);
    Spin5.setadapter (Arrayadapter);
    Baseadapter Baseadapterone = new Baseadapterone ();
    Spin3.setadapter (Baseadapterone);
    Baseadapter baseadaptertwo = new Baseadaptertwo ();
    Spin4.setadapter (Baseadaptertwo); Set the click Result Selection prompt Spin4.setonitemselectedlistener (new Onitemselectedlistener () {@Override public void Onitemse  Lected (adapterview<?> Parent, view view, int position, long id) {Toast.maketext (Activityone.this,
      List.get (position), Toast.length_short). Show ();
    @Override public void onnothingselected (adapterview<?> parent) {}});

  Buttonone.setonclicklistener (New Mybuttonistener ()); } Private Class BaseadapterOne extends baseadapter{@Override public int GetCount () {return array.length;
    @Override public Object getitem (int position) {return null;
    @Override public long getitemid (int position) {return 0; @Override public View getview (int position, View Convertview, ViewGroup parent) {TextView TextView = new
      TextView (Activityone.this);
      Textview.settext (Array[position]);
    return TextView; } private class Baseadaptertwo extends baseadapter{@Override public int GetCount () {return list.siz
    E ();
    @Override public Object getitem (int position) {return null;
    @Override public long getitemid (int position) {return 0; @Override public View getview (int position, View Convertview, ViewGroup parent) {TextView TextView = new
      TextView (Activityone.this);
      Textview.settext (List.get (position));
    return TextView; }} Class Mybuttonistener implements onclicklistener{@Override public void OnClick (View v) {Intent Intent = new Int
      ENT (Activityone.this,activitytwo.class);
    Activityone.this.startActivity (Intent);
 }    
  }
}

OK about today's content introduction to this introduction, the content is very simple, we are interested in the words can be achieved. Novice learning, Master Exchange.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

Related Article

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.