Android development example-Application of admission scores to colleges and universities

Source: Internet
Author: User

Android development example-Application of admission scores to colleges and universities

This series of articles provides a simple Android Application Development example method. The steps are as follows:

1. Obtain the data source required by the application

Data sources generally come from the Internet, personal data collection, or other methods.

2. Application uidesign

Each application requires a simple UI design sketch for developers to better implement coding.

3. Application Implementation

Complete Android applications

 

It is hereby stated that the data sources in this series of articles are obtained through the Internet, and are only used as an example.

Application Introduction

It provides the number-of-each-row admission query function of each university and serves as a reference for students to fill in their volunteers for the college entrance examination. Finally:

I. Information Loading

1. Obtain school information from Assets. The school storage format is:

1 #10001 # Peking University
1 #10002 # Renmin University of China
#1 #10003 # Tsinghua University
1 #10004 # Beijing Jiaotong University

1 indicates the province ID, 10001 indicates the school ID, and the last one is the school name.

We create a new FileUtils class to obtain files under Assets:

 

public static List
 
   loadFileContentForList(String filePath, Context ctx) throws IOException {InputStream is = ctx.getAssets().open(filePath);BufferedReader br = new BufferedReader(new InputStreamReader(is, gbk));ArrayList
  
    results = new ArrayList
   
    ();String readLine = null;while((readLine = br.readLine()) != null) {results.add(readLine);}return results;}
   
  
 
The above method loads the data in the file to the list by row. Because the data source is saved in ASCII format, gbk is used for loading.

 

2. obtain university query results from the network

The HttpClient provided by Android is used for implementation. We first encapsulate a simple HttpUtils processing class and provide the httpGet request method:

 

/*** Get the result of the specified URL request, return request content in String mode * @ param url request address * @ param request parameter * @ return */public static String httpGet (String url, HashMap
 
  
Param) {HttpParams httpParams = new BasicHttpParams (); HttpConnectionParams. setConnectionTimeout (httpParams, 5000); HttpConnectionParams. setSoTimeout (httpParams, 5000); HttpClient mHttpClient = new DefaultHttpClient (httpParams); String mUrl = url; if (param! = Null & param. size ()> 0) {StringBuilder sb = new StringBuilder (); sb. append (url); sb. append (?); For (Entry
  
   
M: param. entrySet () {sb. append (m. getKey (); sb. append (=); sb. append (m. getValue (); sb. append (&);} mUrl = sb. substring (0, sb. length ()-1);} HttpGet httpRequest = new HttpGet (mUrl); try {HttpResponse httpResponse = mHttpClient.exe cute (httpRequest); if (httpResponse. getStatusLine (). getStatusCode () = HttpURLConnection. HTTP_ OK) {String str = EntityUtils. toString (httpResponse. getEntity (); return str ;}} catch (Exception e) {e. printStackTrace ();} finally {httpRequest. abort ();} return null ;}
  
 
3. To facilitate data rendering by controls, we convert all the data into an ArrayList format that SimpleAdapter can recognize. >

 

The MUtils class provides data conversion:

The loadSchool method is used to convert all school information. The Map key indicates the province ID, and the value indicates the school list.

 

@SuppressLint(UseSparseArrays)public static HashMap
  
   >> loadSchool(Context ctx) {HashMap
   
    >> result = new HashMap
    
     >>();try {List
     
       contents = FileUtils.loadFileContentForList(m/data, ctx);for(int i = 0, len = contents.size(); i < len; i++) {String[] item = contents.get(i).split(#);HashMap
      
        data = new HashMap
       
        ();data.put(id, item[1]);data.put(name, item[2]);ArrayList
        
         > itemList = result.get(Integer.parseInt(item[0]));if(itemList == null) {itemList = new ArrayList
         
          >();result.put(Integer.parseInt(item[0]), itemList);}itemList.add(data);}} catch (IOException e) {e.printStackTrace();}return result;}
         
        
       
      
     
    
   
  
The loadResult method is used to convert the query result information obtained by the network, mainly processing the returned JSON format.

 

 

Public static ArrayList
  
   
> LoadResult (final String schoolId, final int type, final int prov2) throws Exception {// obtain the query result from the network. The returned format is JSONString netStr = HttpUtils. httpGet (BASE_URL, new HashMap
   
    
() {Put (_ action, collegescore); put (num, 0); put (provid, prov2); put (wl, type); put (collegeid, schoolId) ;}}); if (netStr = null) {// returns nullreturn null if an exception occurs;} JSONArray resultArray = new JSONArray (netStr); ArrayList
    
     
> Result = new ArrayList
     
      
> (); For (int I = 0, len = resultArray. length (); I <len; I ++) {// process each piece of data in sequence JSONObject jobj = resultArray. getJSONObject (I); HashMap
      
       
D = new HashMap
       
         (); Int tempInt; d. put (year, jobj. getString (syear); tempInt = jobj. optInt (plan,-1); d. put (plan, (tempInt <= 0? --: + TempInt); tempInt = jobj. optInt (score_min,-1); d. put (score_min, tempInt <= 0? --: + TempInt); tempInt = jobj. optInt (score_avg,-1); d. put (score_avg, (tempInt <= 0? --: + TempInt); tempInt = jobj. optInt (score_td,-1); d. put (score_td, (tempInt <= 0? --: + TempInt); tempInt = jobj. optInt (score_max,-1); d. put (score_max, (tempInt <= 0? --: + TempInt); d. put (batch, batchMap. get (jobj. getString (batch); d. put (batch_diff, jobj. getString (batch_diff); result. add (d);} return result;} public static final HashMap
        
          BatchMap = new HashMap
         
           () {Put (00, unknown); put (01, undergraduate approval in advance); put (11, undergraduate batch); put (12, undergraduate batch 2 ); put (13, three undergraduate courses); put (123, two and three undergraduate courses); put (21, specialist );}};
         
        
       
      
     
    
   
  
BASE_URL = http://kaoshi.edu.sina.com.cn/iframe/ I _collegescore.php, batchMap from the original data site to obtain and initialize data

 

Ii. Activity implementation

All variables in Activity are defined as follows:

 

// Select the province ID, the user's location ID, the school number, and the liberal arts type int prov1, prov2, school, type; ArrayList
  
   
> ResultData; // query the admission result HashMap
   
    
> Datas; // save the school information in the province. // select the pop-up window for the province, the pop-up window for the school, and the pop-up window for the text and science respectively. PopupWindow provWindow, schoolWindow, typeWindow, TextView prov1Sel, typeSel, prov2Sel, tipView, resultTitleView; ListView provList, schoolList, resultList; LinearLayout resultLayout; Button queryButton; // provincial information and scientific information (from strings. obtained in xml) String [] provs, types;
   
  

The province pop-up window is implemented as follows:

 

 

/*** Display the province pop-up window. Type = 0 indicates the school province pop-up window, = 1 indicates the province where the user is located pop-up window * @ param type */public void showProvWindow (final int type) {if (provWindow = null) {View v = LayoutInflater. from (this ). inflate (R. layout. pop_list, null); provList = (ListView) v. findViewById (R. id. pop_list); provList. setAdapter (new ArrayAdapter
  
   
(This, R. layout. pop_list_item, R. id. pop_list_item_name, provs); provWindow = new PopupWindow (v, Utils. screenWidth, Utils. screenHeight/2, true);} provList. setOnItemClickListener (new OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView
   Av, View arg1, int position, long arg3) {// ID is the serial number + 1if (type = 0) {prov1 = position + 1; prov1Sel. setText (provs [position]);} else {prov2 = position + 1; prov2Sel. setText (provs [position]);} if (provWindow! = Null) {provWindow. dismiss () ;}}); if (type = 0 & prov1> 0) {provList. setSelection (prov1-1);} else if (type = 1 & prov2> 0) {provList. setSelection (prov2-1);} else {provList. setSelection (0);} provWindow. showAsDropDown (type = 0? Prov1Sel: prov2Sel, 0, 0); provWindow. update ();}
  
The pop-up window of the liberal arts and sciences type is implemented as follows:

 

 

public void showTypeWindow() {if (typeWindow == null) {View v = LayoutInflater.from(this).inflate(R.layout.pop_list, null);ListView tList = (ListView) v.findViewById(R.id.pop_list);tList.setAdapter(new ArrayAdapter
  
   (this, R.layout.pop_list_item,R.id.pop_list_item_name, types));typeWindow = new PopupWindow(v, Utils.screenWidth / 2,Utils.screenHeight / 2, true);tList.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView
    av, View arg1,int position, long arg3) {type = position;typeSel.setText(types[position]);if (typeWindow != null) {typeWindow.dismiss();}}});}typeWindow.showAsDropDown(typeSel, 0, 0);typeWindow.update();}
  
The school drop-down pop-up window is implemented as follows:

 

 

Public void showSchoolWindow () {if (prov1 <= 0) {Toast. makeText (this, select a province first !, Toast. LENGTH_SHORT ). show (); return;} if (schoolWindow = null) {View v = LayoutInflater. from (this ). inflate (R. layout. pop_list, null); schoolList = (ListView) v. findViewById (R. id. pop_list); schoolList. setOnItemClickListener (new OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView
  Av, View arg1, int position, long arg3) {school = position; schoolSel. setText (String) datas. get (prov1 ). get (school ). get (name); if (schoolWindow! = Null) {schoolWindow. dismiss () ;}}); schoolWindow = new PopupWindow (v, Utils. screenWidth, Utils. screenHeight/2, true);} // data needs to be updated each time you click to prevent the province from changing schoolList. setAdapter (new SimpleAdapter (this, datas. get (prov1), R. layout. pop_list_item, new String [] {name}, new int [] {R. id. pop_list_item_name}); schoolList. setSelection (school); schoolWindow. showAsDropDown (schoolSel, 0, 0); schoolWindow. update ();}
Because Http requests cannot be implemented in the main thread, we use the new thread and Handler to implement UI refresh. The request query and rendering results are as follows:

 

 

@ Overridepublic void run () {try {resultData = MUtils. loadResult (String) datas. get (prov1 ). get (school ). get (id), type + 1, prov2);} catch (Exception e) {resultData = null;} handler. sendEmptyMessage (0);} public void search () {if (! Utils. canAccessNetwork (this) {tipView. setText (unable to connect to the network !); ChangeView (false); return;} if (prov1 <= 0) {tipView. setText (select school !); ChangeView (false); return;} if (prov2 <= 0) {tipView. setText (select your location !); ChangeView (false); return;} tipView. setText (loading ...); changeView (false); new Thread (this ). start ();} Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {if (resultData = null) {tipView. setText (failed to get the result. Please try again later !); ChangeView (false);} else {StringBuilder sb = new StringBuilder (); sb. append (
); Sb. append (); sb. append (datas. get (prov1 ). get (school ). get (name); sb. append (); sb. append (in); sb. append (); sb. append (provs [prov2-1]); sb. append (); sb. append (); sb. append (types [type]); sb. append (recording line); sb. append (); resultTitleView. setText (Html. fromHtml (sb. toString (); resultList. setAdapter (new SimpleAdapter (MainActivity. this, resultData, R. layout. result_item, new String [] {year, score_max, score_avg, score_td, plan, batch, batch_diff}, new int [] {R. id. result_item_year, R. id. result_item_max, R. id. result_item_avg, R. id. result_item_real, R. id. result_item_persons, R. id. result_item_pici, R. id. result_item_xiancha}); changeView (true) ;}};}; public void changeView (boolean flag) {if (flag) {resultLayout. setVisibility (View. VISIBLE); tipView. setVisibility (View. GONE);} else {resultLayout. setVisibility (View. GONE); tipView. setVisibility (View. VISIBLE );}}
The complete Activity code is as follows:

 

 

Package com. gklq. zl; import java. util. arrayList; import java. util. hashMap; import java. util. timer; import java. util. timerTask; import com. my. lib. utils; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. text. html; import android. view. keyEvent; import android. view. layoutInflater; import android. view. view; import android. view. view. onClickListener; import android. widget. AdapterView. onItemClickListener; import android. widget. adapterView; import android. widget. arrayAdapter; import android. widget. button; import android. widget. linearLayout; import android. widget. listView; import android. widget. popupWindow; import android. widget. simpleAdapter; import android. widget. textView; import android. widget. toast; public class MainActivity extends Activity implements OnClickListener, Run Nable {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); if (Utils. screenHeight <= 0) {Utils. initSize (this);} if (datas = null) {datas = MUtils. loadSchool (this);} setContentView (R. layout. activity_main); prov1Sel = (TextView) findViewById (R. id. prov1_sel); prov1Sel. setOnClickListener (this); schoolSel = (TextView) findViewById (R. id. school_sel); schoolSel. setOn ClickListener (this); typeSel = (TextView) findViewById (R. id. type_sel); typeSel. setOnClickListener (this); prov2Sel = (TextView) findViewById (R. id. prov2_sel); prov2Sel. setOnClickListener (this); queryButton = (Button) findViewById (R. id. query_btn); queryButton. setOnClickListener (this); tipView = (TextView) findViewById (R. id. text_tip); resultLayout = (LinearLayout) findViewById (R. id. layout_result); resultTitleV Iew = (TextView) findViewById (R. id. text_result); resultList = (ListView) findViewById (R. id. list_result); provs = getResources (). getStringArray (R. array. province); types = getResources (). getStringArray (R. array. type);} public void onClick (android. view. view v) {switch (v. getId () {case R. id. prov1_sel: showProvWindow (0); break; case R. id. prov2_sel: showProvWindow (1); break; case R. id. type_sel: showTypeWindow (); br Eak; case R. id. school_sel: showSchoolWindow (); break; case R. id. query_btn: search (); break; default: break; }}@ Overridepublic void run () {try {resultData = MUtils. loadResult (String) datas. get (prov1 ). get (school ). get (id), type + 1, prov2);} catch (Exception e) {resultData = null;} handler. sendEmptyMessage (0);} public void search () {if (! Utils. canAccessNetwork (this) {tipView. setText (unable to connect to the network !); ChangeView (false); return;} if (prov1 <= 0) {tipView. setText (select school !); ChangeView (false); return;} if (prov2 <= 0) {tipView. setText (select your location !); ChangeView (false); return;} tipView. setText (loading ...); changeView (false); new Thread (this ). start ();} Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {if (resultData = null) {tipView. setText (failed to get the result. Please try again later !); ChangeView (false);} else {StringBuilder sb = new StringBuilder (); sb. append (

 




 

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.