Basic knowledge of Android [project training-achieve level 2 navigation "Today's activity" and read database] [5], android Training

Source: Internet
Author: User

Basic knowledge of Android [project training-achieve level 2 navigation "Today's activity" and read database] [5], android Training

[This project training is a comprehensive exercise of basic Android knowledge. Note: some pictures and materials will be used in the project and they will be organized at will. A resource will be uploaded later, includes the basic functions of this item, as well as image materials]

[Project title]: Comprehensive Case Study of campus ordering App design [Objective]

The main interface contains two subinterfaces: The activity interface and the bill interface. The following describes their implementation code and layout files.

1. The following is the Activity code of the Activity interface. Because the interface needs to read data from the database during loading, the implementation of all functions will involve some classes in the db package.

Note that this Activity also inherits the ActivityGroup

Public class DiscountFoodActivity extends ActivityGroup implements OnItemClickListener {TabHost innerTab; ListView promotionFoodList, audience; // promotion List data, List <FoodInfo> pdata; // List of discount List data <FoodInfo> ddata; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_discount_food); promotionFoodList = (ListView) findViewById (R. id. pr OmotionFoodList); discountFoodList = (ListView) findViewById (R. id. discountFoodList); innerTab = (TabHost) findViewById (R. id. innerTab_discount); // initialize the internal TabinitInnerTabHost (); initListView (); // initialize the list data // Add the listener, click promotionFoodList for the listener list item. setOnItemClickListener (this); discountFoodList. setOnItemClickListener (this);} // initialize the activity food list and discount food list private void initListView () {// obtain the database EatDbHelper dbh = new EatDbHelper (this, "foodd B. db3 ", null, 1); SQLiteDatabase db = dbh. getReadableDatabase (); pdata = new FoodDao (). queryFood (db," ispromotion =? ", New String [] {" 1 "}," price DESC "); FoodListAdapter fla = new FoodListAdapter (this, pdata, R. layout. foodlist_item); promotionFoodList. setAdapter (fla); ddata = new FoodDao (). queryFood (db, "discount <? ", New String [] {" 1 "}," price DESC "); fla = new FoodListAdapter (this, ddata, R. layout. foodlist_item); discountFoodList. setAdapter (fla);} private void initInnerTabHost () {innerTab. setup (getLocalActivityManager (); TabSpec t1 = innerTab. newTabSpec ("inner_dis_t1"); t1.setIndicator ("today's events", getResources (). getDrawable (R. drawable. ic_launcher); t1.setContent (R. id. innerTab_discount_tab1); TabSpec t2 = innerTab. newTabSpe C ("inner_dis_t2"); t2.setIndicator ("Today's discount", getResources (). getDrawable (R. drawable. ic_launcher); t2.setContent (R. id. innerTab_discount_tab2); innerTab. addTab (t1); innerTab. addTab (t2) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. discount_food, menu); return true;} @ Overridepublic void onItem Click (AdapterView <?> Lv, View view, int index, long arg3) {Intent intent = new Intent (this, FoodDetailActivity. class); Bundle bd = new Bundle (); // Log. I ("Msg", "Current click list" + lv + "" + lv. getId (); if (lv. getId () = R. id. promotionFoodList) {bd. putSerializable ("food", pdata. get (index); // Log. I ("Msg", "current selection:" + pdata. get (index ). getFoodName ();} else if (lv. getId () = R. id. discountFoodList) {bd. putSerializable ("food", ddata. get (index); // Log. I ("Msg", "current selection:" + ddata. get (index ). getFoodName ();} intent. putExtras (bd); startActivity (intent );}}
2. layout interface. A lot of resources are used in the project. Now we will show the results of these resources.


The Activity interface is activity_discount_food.xml. The code is:

<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=".DiscountFoodActivity" >    <TabHost        android:id="@+id/innerTab_discount"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true" >        <LinearLayout            android:layout_width="match_parent"            android:layout_height="match_parent"            android:orientation="vertical" >            <TabWidget                android:id="@android:id/tabs"                android:layout_width="match_parent"                android:layout_height="wrap_content" >            </TabWidget>            <FrameLayout                android:id="@android:id/tabcontent"                android:layout_width="match_parent"                android:layout_height="match_parent" >                <LinearLayout                    android:id="@+id/innerTab_discount_tab1"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:orientation="vertical"                     >                     <ListView                         android:id="@+id/promotionFoodList"                         android:layout_width="match_parent"                         android:layout_height="match_parent"                         >                     </ListView>                </LinearLayout>                <LinearLayout                    android:id="@+id/innerTab_discount_tab2"                    android:layout_width="match_parent"                    android:orientation="vertical"                    android:layout_height="match_parent" >                    <ListView                         android:id="@+id/discountFoodList"                         android:layout_width="match_parent"                         android:layout_height="match_parent"                         >                     </ListView>                </LinearLayout>            </FrameLayout>        </LinearLayout>    </TabHost></RelativeLayout>
In fact, this is also a tab navigation, but its label navigation is on top.
3. Two collections are prepared to read activity and discount food data.
// Promotion List data, List <FoodInfo> pdata; // discount List data List <FoodInfo> ddata;

Here, FoodInf is an entity class. Pay attention to comments on attributes.

Package com. example. entity; import java. io. serializable; import android. graphics. bitmap; public class FoodInfo implements Serializable {private String _ id, foodName; private String price; private String isPromotion; // whether or not there is an activity in promotion activity 1, 0 no activity private String discount = "1"; // discount private String category; // category of food, staple food, side dishes, drinks, other four categories of private String type; // cuisines, such as sour, sweet, bitter, and salty, and private String score such as luyue chuansu; // total score of dishes: private int shopId; // restaurant IDprivate ShopInfo shop; // restaurant private Bitmap img; private String imgId; private String description; // description of Food public String getFoodName () {return foodName;} public void setFoodName (String foodName) {this. foodName = foodName;} public String getPrice () {return price;} public void setPrice (String price) {this. price = price;} public String getCategory () {return category;} public void setCategory (String category) {this. category = category;} public String getType () {return type;} public void setType (String type) {this. type = type;} public String getScore () {return score;} public void setScore (String score) {this. score = score;} public ShopInfo getShop () {return shop;} public void setShop (ShopInfo shop) {this. shop = shop;} public String get_id () {return _ id;} public void set_id (String _ id) {this. _ id = _ id;} public int getShopId () {return shopId;} public void setShopId (int shopId) {this. shopId = shopId;} public String getIsPromotion () {return isPromotion;} public void setIsPromotion (String isPromotion) {this. isPromotion = isPromotion;} public String getDiscount () {return discount;} public void setDiscount (String discount) {this. discount = discount;} public Bitmap getImg () {return img;} public void setImg (Bitmap img) {this. img = img;} public String getImgId () {return imgId;} public void setImgId (String imgId) {this. imgId = imgId;} public String getDescription () {return description;} public void setDescription (String description) {this. description = description ;}@ Overridepublic String toString () {return "FoodInfo [_ id =" + _ id + ", foodName =" + foodName + ", price = "+ price +", isPromotion = "+ isPromotion +", discount = "+ discount +", category = "+ category +", type = "+ type + ", score = "+ score +", shopId = "+ shopId +", shop = "+ shop +", img = "+ img + ", imgId = "+ imgId +"] ";}}

4. The data in the above two sets is filled by db classes.

pdata =new FoodDao().queryFood(db, "ispromotion=?", new String[]{"1"}, "price DESC");
FoodDao is a class dedicated to reading food data. Its code is as follows:

Public class FoodDao {public List <FoodInfo> queryFood (SQLiteDatabase db, String sel, String [] selArg, String order) {List <FoodInfo> fs = new ArrayList <FoodInfo> (); cursor c = db. query ("tb_foodInfo", new String [] {"_ id", "foodName", "category", "type", "price", "score", "imgId ", "shopId", "discount", "isPromotion"}, sel, selArg, null, null, order); Log. I ("Msg", "number of records read:" + c. getCount (); c. moveToFirst (); while (! C. isAfterLast () {FoodInfo f = new FoodInfo (); f. set_id (c. getString (0); f. setFoodName (c. getString (1); f. setCategory (c. getString (2); f. setType (c. getString (3); f. setPrice (c. getString (4); f. setScore (c. getString (5); String imgId = c. getString (6); f. setImgId (Integer. parseInt (imgId. substring (2), 16) + ""); f. setShopId (c. getInt (7); f. setDiscount (c. getString (8); f. setIsPromotion (c. getString (9); // Log. I ("Msg", f. toString (); fs. add (f); c. moveToNext ();} c. close (); return fs ;}}
5. After reading the data, you can use an adapter to bind the data to the list.

FoodListAdapter fla = new FoodListAdapter (
This, pdata, R. layout. foodlist_item );

FoodListAdapter is an adapter that inherits the BaseAdapter. (This adapter is not commonly written but should be easy to understand)

The Code is as follows:

Public class FoodListAdapter extends BaseAdapter {private Context context; private List <FoodInfo> data; private int layout; public FoodListAdapter (Context context, List <FoodInfo> data, int layout) {super (); this. context = context; this. data = data; this. layout = layout;} @ Overridepublic int getCount () {return data. size () ;}@ Overridepublic Object getItem (int arg0) {// TODO Auto-generated method stubreturn data. get (arg0) ;}@ Overridepublic long getItemId (int arg0) {// TODO Auto-generated method stubreturn arg0 ;}@ Overridepublic View getView (int index, View arg1, ViewGroup arg2) {LayoutInflater inflater = LayoutInflater. from (context); View v = inflater. inflate (layout, null); ImageView iv = (ImageView) v. findViewById (R. id. foodlist_item_img); iv. setImageResource (Integer. parseInt (data. get (index ). getImgId (); TextView name = (TextView) v. findViewById (R. id. foodlist_item_name); name. setText (data. get (index ). getFoodName (); TextView category = (TextView) v. findViewById (R. id. foodlist_item_category); category. setText (data. get (index ). getCategory (); TextView type = (TextView) v. findViewById (R. id. foodlist_item_type); type. setText (data. get (index ). getType (); TextView price = (TextView) v. findViewById (R. id. foodlist_item_price); price. setText ("$" + data. get (index ). getPrice (); float zk = Float. parseFloat (data. get (index ). getDiscount (); if (zk <1) {TextView discount = (TextView) v. findViewById (R. id. foodlist_item_discount); discount. setText ("discount:" + (zk * 10) + "discount");} TextView score = (TextView) v. findViewById (R. id. foodlist_item_score); score. setText ("hundreds of meters:" + data. get (index ). getScore () + "meter"); return v ;}}

6. List
ListView promotionFoodList,discountFoodList;
The layout of their list items is the same, and the layout file is used in a unified manner:
</Pre> <pre code_snippet_id = "563089" snippet_file_name = "blog_20141226_11_5643964" name = "code" class = "java"> <pre name = "code" class = "html"> <? Xml version = "1.0" encoding = "UTF-8"?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "match_parent" android: layout_height = "match_parent"> <ImageView android: id = "@ + id/foodlist_item_img" android: layout_width = "60dp" android: layout_height = "60dp" android: background = "@ drawable/imgbg" android: src = "@ drawable/food_02"/> <TextView android: id = "@ + id/foodlist_item_name" android: layout_width = "wrap_c Ontent "android: layout_height =" wrap_content "android: layout_toRightOf =" @ id/foodlist_item_img "android: layout_marginLeft =" 8dp "android: text =" "android: textAppearance = "? Android: attr/textAppearanceLarge "/> <TextView android: id =" @ + id/foodlist_item_category "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_toRightOf = "@ id/foodlist_item_name" android: layout_marginLeft = "8dp" android: text = "Chinese food" android: textAppearance = "? Android: attr/textAppearanceMedium "/> <TextView android: id =" @ + id/foodlist_item_type "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_toRightOf = "@ id/foodlist_item_category" android: layout_marginLeft = "8dp" android: text = "sour" android: textAppearance = "? Android: attr/textAppearanceMedium "/> <TextView android: id =" @ + id/foodlist_item_price "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_below = "@ id/foodlist_item_name" android: layout_alignLeft = "@ id/foodlist_item_name" android: layout_marginTop = "8dp" android: text = "¥10.00" android: textAppearance = "? Android: attr/textAppearanceSmall "/> <TextView android: id =" @ + id/foodlist_item_discount "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_toRightOf = "@ id/foodlist_item_price" android: cursor = "@ id/foodlist_item_price" android: layout_marginLeft = "8dp" android: text = "" android: textAppearance = "? Android: attr/textAppearanceSmall "/> <TextView android: id =" @ + id/foodlist_item_score "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_toRightOf = "@ id/foodlist_item_discount" android: layout_alignBottom = "@ id/foodlist_item_discount" android: Rule = "true" android: layout_marginRight = "8dp" android: gravity = "right" android: text = "rating: 122" android: textAppear Ance = "? Android: attr/textAppearanceSmall "/> </RelativeLayout>


 

The discount page is complete. Next, the bill page is provided.

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.