Discover----Android Demo

Source: Internet
Author: User
Tags blank page

Time quietly walk, an instant to internship has been three months, three months of time, small series of slowly growing, from the beginning of the e-commerce project to the current car satin project, small series in a project through one after another, went through one after another to overcome their own miracles, each encounter a new technology point, small series began to Tinker, Tinkering with this matter, really need courage, pounded drum, duang, function out, good happy ' (*∩_∩*), ability is often done will get, and not have the ability to do, girl refueling. Small partners may have seen some of the features found on the app, click on the Found button to automatically load the most popular information, in the small part of the recent project has this function, after a few days of tinkering, finally fresh out of the oven, today this blog small series to simple introduction how to click the Discovery button, We need to automatically load the relevant information, hoping to help the needs of the small partners, but also ask the small partners to teach ' (*∩_∩*).

First, let's write our physical layer, which requires two entities, and the first content is as follows:

Package Com.jczb.car.bean;import Java.util.date;import java.util.list;import android. R.integer;import Android. r.integer;/** * Description: Satin Content Entity * Ding * Time: September 10, 2015 10:41:43 */@SuppressWarnings ("Serial") public class content extends entity {/** content table ID */private int uid;/** display title */private string title;/** video or picture path */private string path;/** details */private string deta ils;/** Channel type */private string channeltype;/** channel name */private string channelname;/** author */private string author;/** recommended */ Private String isrecommend;/** Read or play quantity */private int browsenumber;/** comments */private int commentbrowsenumber;/** likes */ private int praisenumber;/** step */private int treadnumber;/** release time */private String issuetime;/** whether to bookmark */private int iscollect;/** associated video */private list<videorelation> content;public String getTitle () {return title;} public void Settitle (String title) {this.title = title;} Public String GetPath () {return path;} public void SetPath (String path) {this.path = path;} Public String Getdetails () {return details;} public void SetdeTails (String details) {this.details = details;} Public String Getchanneltype () {return channeltype;} public void Setchanneltype (String channeltype) {this.channeltype = Channeltype;} Public String Getauthor () {return author;} public void Setauthor (String author) {this.author = author;} Public String Getisrecommend () {return isrecommend;} public void Setisrecommend (String isrecommend) {this.isrecommend = Isrecommend;} public int Getbrowsenumber () {return browsenumber;} public void Setbrowsenumber (int browsenumber) {this.browsenumber = Browsenumber;} public int Getcommentbrowsenumber () {return commentbrowsenumber;} public void Setcommentbrowsenumber (int commentbrowsenumber) {this.commentbrowsenumber = Commentbrowsenumber;} public int Getpraisenumber () {return praisenumber;} public void Setpraisenumber (int praisenumber) {this.praisenumber = Praisenumber;} public int Gettreadnumber () {return treadnumber;} public void Settreadnumber (int treadnumber) {this.treadnumber = Treadnumber;} Public String GetissuetIME () {return issuetime;} public void Setissuetime (String issuetime) {this.issuetime = Issuetime;} Public String Getchannelname () {return channelname;} public void Setchannelname (String channelname) {this.channelname = ChannelName;} public int Getiscollect () {return iscollect;} public void Setiscollect (int iscollect) {this.iscollect = Iscollect;} Public list<videorelation> getcontent () {return Content;} public void SetContent (list<videorelation> content) {content = content;} public int Getuid () {return UID;} public void SetUid (int uid) {this.uid = uid;}}
The second entity is contentvo, and the specific code is as follows:

Package Com.jczb.car.bean;import java.util.list;/** * Description: Content collection for JSON string parsing * Ding * Time: September 10, 2015 10:38:38 */@ Suppresswarnings ("Serial") public class Contentvo extends Entity {/** server returns result: TRUE or false */private String result;/** The JSON string returned by the server resolves to List combined */private list<content> content;public String getresult () {return result;} public void Setresult (String result) {This.result = result;} Public list<content> getcontent () {return Content;} public void SetContent (list<content> content) {content = content;}}
Next, to write our interface method that needs to be called, the code looks like this:

/** * Description: Found * @user Ding * @date 2015-8-31 pm 2:10:59 */public Contentvo Discover (boolean isFirst, int contentvoid) throws Appexception {Contentvo Contentvo = null;//Build cache file KeyString K EY = "Contentvo_" + contentvoid;//1. If the network first obtains data from the server if (isnetworkconnected () && (Isreaddatacache (key) | | isFirst ) {try {//Gets a collection of content from the server Contentvo = Apiclient.discover (this);//If you can obtain data from the server and save it to the local cache, only the guaranteed data is not empty. and gets the result to true when cached to local if (contentvo! = null && contentvo.getresult (). Equals ("false")) {Contentvo.setcachekey ( key); Saveobject (Contentvo, key);}} catch (Appexception e) {//If an access is interrupted, get the data in the local cache Contentvo = (contentvo) readobject (key), or if the data in the local cache is empty, throw an exception if ( Contentvo = = null) {throw e;}}} 2. If not networked, get data from the cache else {Contentvo = (contentvo) readobject (key), if (Contentvo = = null) {Contentvo = new Contentvo ();} return contentvo;} return contentvo;}  
In the third step, we'll write our XML layout, as shown in the following code:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/    Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:background=" #F7F7F7 "        android:orientation= "vertical" > <linearlayout style= "@style/top_title_style" > <!--the layout of angle brackets-- <imagebutton android:id= "@+id/about_us_back" android:layout_width= "14DP" Androi            d:layout_height= "25.5DP" android:layout_gravity= "center_vertical" android:layout_marginleft= "10DP" android:background= "@drawable/back"/> <!--car Satin layout-<textview style= "@sty Le/top_title_word_style "android:text=" Car Satin "/> </LinearLayout> <!--search and <relative Layout android:id= "@+id/rl_search_id" android:layout_width= "match_parent" android:layout_height= "wrap _content "Android:layout_margintop= "2DP" android:orientation= "horizontal" > <textview android:id= "@+id/et_seachkey_id" Android:layout_width= "Match_parent" android:layout_height= "50DP" android:background= "@dra Wable/search_photo "android:textsize=" 15sp "/> <imageview android:id=" @+id/iv_search_id "Android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layout _gravity= "center" android:layout_marginleft= "290DP" android:layout_margintop= "15DP" Andro id:background= "@drawable/search"/> <textview android:id= "@+id/iv_search_id" android:l            Ayout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "center"            android:layout_marginleft= "10DP" android:layout_margintop= "15DP" android:textsize= "15SP" Android:hint= "Please enterSearch keyword "/> </RelativeLayout> <!--favorite--<linearlayout android:layout_width=" Match_paren        T "android:layout_height=" 50DP "android:layout_margintop=" 5DP "android:orientation=" vertical ">            <textview android:layout_width= "wrap_content" android:layout_height= "Wrap_content"            android:layout_gravity= "Center" android:gravity= "center" android:text= "@string/hot_channels_str" Android:textcolor= "@color/light_blue" android:textsize= "25sp"/> <view androi            D:layout_width= "Match_parent" android:layout_height= "1DP" android:layout_margintop= "2DP" android:background= "@color/lightgray"/> </LinearLayout> <!--favorite Content--<linearlayout an Droid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:minheight= "? android:attr/list    Preferreditemheight "    android:orientation= "vertical" > <listview android:id= "@+id/lv_hotchannel_id" Andro            Id:layout_width= "Match_parent" android:layout_height= "wrap_content" android:divider= "@null" android:minheight= "200DP" > </ListView> </LinearLayout></LinearLayout>
      Fourth, write the code required inside the Java class as follows:
Package Com.jczb.car.ui;import Java.util.arraylist;import Java.util.hashmap;import java.util.list;import Java.util.map;import Android.app.activity;import Android.content.intent;import Android.os.Bundle;import Android.os.handler;import Android.os.message;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import Android.widget.edittext;import Android.widget.imageview;import Android.widget.listview;import Android.widget.relativelayout;import Android.widget.simpleadapter;import Android.widget.textview;import Android.widget.toast;import Com.jczb.car.appcontext;import Com.jczb.car.appexception;import Com.jczb.car.R;import Com.jczb.car.bean.content;import com.jczb.car.bean.contentvo;/** * Description: Discovery Feature page * Ding * Time: 2015-9-2 pm 2:02:58 */public Class Discoveryactivity extends Activity implements Onclicklistener,onitemclicklistener {//relativelayout Rlfoundsearch;//imageview ivtubiaosearch;//Declaration of the use of severalControl private TextView etsearch;private ImageView ivsearch;private ListView lvhotchannel;private relativelayout Rlfoundsearchempty;//private ImageView ivtubiao;/** parsing Discovery interface with entity class */private Contentvo Contentvo = null;/** List*/private List<map<string used to populate the ListView, object>> data = new arraylist<map<string,object> > ();/** The discovery content collection used to obtain the server interface */private list<content> discovercontent; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.discovery); findViewById ();// Initialize the page control Initview ();/* Jump to the blank page of the search keyword */rlfoundsearchempty.setonclicklistener (this);//ivtubiao.setonclicklistener ( this);//start child thread, get Server Data Discoverthread.start ();} private void Findviewbyid () {//TODO auto-generated method stubrlfoundsearchempty= (relativelayout) Findviewbyid ( R.ID.RL_SEARCH_ID);//ivtubiao= (ImageView) Findviewbyid (r.id.iv_search_tubiao_id);} @Overridepublic void OnClick (View v) {switch (V.getid ()) {/*case R.id.iv_search_tubiao_id:break; */case r.id.rl_search_id:intent intentfoundserch = new Intent (this,searchresourceactivity.class); StartActivity (intentfoundserch); break;default:break;}} /** * Description: Initialize control and Listen event * Ding * Time: 2015-9-2 pm 2:12:49 */public void Initview () {//Initialize control Etsearch = (TextView) Findviewbyid (r.id. ET_SEACHKEY_ID); ivsearch = (ImageView) Findviewbyid (r.id.iv_search_id); Lvhotchannel = (ListView) Findviewbyid ( R.ID.LV_HOTCHANNEL_ID);//rlfoundsearch= (relativelayout) Findviewbyid (r.id.rl_search_id);// Initialize Listener Event Ivsearch.setonclicklistener (this);// The ListView wants to implement the Click event this activity must implement the Onitemclicklistener interface Lvhotchannel.setonitemclicklistener (new Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> arg0, View arg1, int position,long arg3) {// Click on the item to get the parameters to be carried according to the click location to jump to the search results page Intent intent = new Intent (discoveryactivity.this, vedioinfoactivity.class); Intent.putextra ("Channeltype", discovercontent.get (position). Getchanneltype ()); Intent.putextra ("Id", Discovercontent.get (position). GetId ()); StartActivity (inteNT);});};/ * * Description: Get and load data from server side into ListView * Ding * Time: 2015-9-2 pm 2:54:27 */public void LoadData () {}/** * Define a thread to wait */Handler handle R = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg);// You need to determine the return value of the MSG that is passed in the thread-the what value of the message is 1, the null what is-1, the exception is 0switch (msg.what) {case 1://get the server data Contentvo = (contentvo  ) Msg.obj;discovercontent = Contentvo.getcontent ();//assigns data to the List<map<>> collection for (int i = 0; i< discovercontent.size (); i++) {map<string, object> Map = new hashmap<string, object> ();//map.put ("Id", Discovercontent.get (i). getId ());//map.put ("Channeltype", Discovercontent.get (i) getchanneltype ()); Map.put ("title", Discovercontent.get (i). GetTitle ()); Map.put ("ChannelName", Discovercontent.get (i). Getchannelname ());d ata.add (map); Define the adapter that fills the ListView and populate it in the ListView//string[]{} The names entered in the map must remain consistent simpleadapter Contentadapter = new Simpleadapter ( Discoveryactivity.this, data, r.layout.discovery_item,new string[]{"title", "ChannelName"}, new INT[]{R.ID.TV_CHANNELTOPNEWS_ID,R.ID.TV_CHANNELNAME_ID}); Lvhotchannel.setadapter (ContentAdapter); Break;case-1: Toast.maketext (Discoveryactivity.this, "Data is empty!", Toast.length_long). Show (); Break;case 0:toast.maketext ( Discoveryactivity.this, "Data acquisition failed!", Toast.length_long). Show (); break;default:break;}}};/ * * Open a Discovery sub-thread */thread discoverthread = new Thread (new Runnable () {@Overridepublic void run () {message msg = new Message ( );//Get Global object Applicationappcontext AppContext = (appContext) getapplication (); try {//get server data Contentvo = Appcontext.discover (True, 1);//returns CONTENTVO the what value of the message is 1, what is null what is-1, the exception is 0if (contentvo! = null) {Msg.what = 1;msg.obj = Contentvo;} else {msg.what =-1;}} catch (Appexception e) {msg.what = 0;e.printstacktrace ();} Handler.sendmessage (msg);}); * * Description: Display different toast prompts according to the type of handler * Ding * Time: 2015-9-2 pm 3:53:30 */public void showtoast (int what) {switch -1:toast.maketext (Discoveryactivity.this, "Data is empty!", Toast.length_long). Show (); Break;case 0:toast.maketext ( DiscoveryaCtivity.this, "Data acquisition failed!", Toast.length_long). Show ();d Efault:break;}}  @Overridepublic void Onitemclick (adapterview<?> arg0, View arg1, int arg2, long arg3) {//TODO auto-generated method Stub}}

Here we find a line of this function to go down, and finally, let's take a look at our running effect as follows:

Small Series of words: The realization of the discovery of the function, the small part of the simple introduction to here, found that the realization, but the small part to the present or foggy, but it does not matter, small series will be more and more brave, this is the meaning of life, or that sentence For the small part, is not only the challenge is the opportunity, because the knowledge are interlinked, moreover, in the small part of the process of life, leaving the most precious memories, although the later small not necessarily engaged in the Android industry, the code world, a lot of things, some sweet, some warm, some of the euphemism into songs, and some stretches, in these stories The only thing we have in common is that one year, one month, some placid day, I loved you very much! Love You-the days of this internship, Android brought to the small series of various surprises. In the next blog post, the teenager and the small partners to share, how to enter keywords, search for the corresponding content, please look forward to ' (*∩_∩*)!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Discover----Android Demo

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.