显示简单的记录排序和筛选 : 排序搜索 « 基于J2ME « Java

En
Java
1. 图形用户界面
2. 三维图形动画
3. 高级图形
4. 蚂蚁编译
5. Apache类库
6. 统计图
7. 
8. 集合数据结构
9. 数据类型
10. 数据库JDBC
11. 设计模式
12. 开发相关类
13. EJB3
14. 电子邮件
15. 事件
16. 文件输入输出
17. 游戏
18. 泛型
19. GWT
20. Hibernate
21. 本地化
22. J2EE平台
23. 基于J2ME
24. JDK-6
25. JNDI的LDAP
26. JPA
27. JSP技术
28. JSTL
29. 语言基础知识
30. 网络协议
31. PDF格式RTF格式
32. 映射
33. 常规表达式
34. 脚本
35. 安全
36. Servlets
37. Spring
38. Swing组件
39. 图形用户界面
40. SWT-JFace-Eclipse
41. 线程
42. 应用程序
43. Velocity
44. Web服务SOA
45. 可扩展标记语言
Java 教程
Java » 基于J2ME » 排序搜索屏幕截图 
显示简单的记录排序和筛选
显示简单的记录排序和筛选


/* License
 
 * Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  
 *  * Redistribution of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 
 *  * Redistribution in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *  
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *  
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility. 
 */

import java.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;

// Demonstrates simple record sorting and filtering

public class EnumDemoMIDlet extends MIDlet
                      implements CommandListener {

    // Data members we need

    private Display              display;
    private RecordStore          rs;
    private EnumList             enumListScreen;
    private SortOptions          sortOptionsScreen;
    private String               firstName;
    private String               lastName;
    private byte[]               data = new byte[200];
    private ByteArrayInputStream bin =
      new ByteArrayInputStreamdata );
    private DataInputStream      din =
      new DataInputStreambin );

    // Define the four commands we use

    private Command exitCommand = new Command"Exit",
                                    Command.EXIT, );
    private Command sortCommand = new Command"Sort",
                                  Command.SCREEN, );
    private Command cancelCommand = new Command"Cancel",
                                  Command.CANCEL, );
    private Command okCommand = new Command"OK",
                                      Command.OK, );

    // Define the sorting modes

    private static final int SORT_NONE = 0;
    private static final int SORT_FIRST_LAST = 1;
    private static final int SORT_LAST_FIRST = 2;

    // Define the filtering modes

    private static final int FILTER_NONE = 0;
    private static final int FILTER_STARTSWITH = 1;
    private static final int FILTER_CONTAINS = 2;

    // A simple class to hold the parts of a record

    private static class Record {
        String firstName;
        String lastName;
    }

    // Precanned names

    private static final String[][] names = {
        "Eric""Giguere" },
        "John""Doe" },
        "Lisa""Munro" },
        "Stephanie""Kwaly" },
        "Dave""Boyer" },
        "Gwen""Stephens" },
        "Jennifer""Lopert" },
        "Ed""Ort" },
    };

    // Constructor

    public EnumDemoMIDlet(){
    }

    // Clean up

    protected void destroyAppboolean unconditional )
                   throws MIDletStateChangeException {
        exitMIDlet();
    }

    // Close the record store for now

    protected void pauseApp(){
        closeRecordStore();
    }

    // Initialize things and reopen record store
    // if not open

    protected void startApp() throws
      MIDletStateChangeException {
        ifdisplay == null ){ // first time called...
            initMIDlet();
        }

        ifrs == null ){
            openRecordStore();
        }
    }

    // Once-only initialization code

    private void initMIDlet(){
        display = Display.getDisplaythis );
        enumListScreen = new EnumList();
        sortOptionsScreen = new SortOptions();

        ifopenRecordStore() ){
            enumListScreen.resort();
            display.setCurrentenumListScreen );
        }
    }

    // Termination code

    public void exitMIDlet(){
        closeRecordStore();
        notifyDestroyed();
    }

    // Add a first-last name pair to the record store

    private void addNameString first, String last,
                          ByteArrayOutputStream bout,
                          DataOutputStream dout ){
        try {
            dout.writeUTFfirst );
            dout.writeUTFlast );
            dout.flush();
            byte[] data = bout.toByteArray();
            rs.addRecorddata, 0, data.length );
            bout.reset();
        }
        catchException e ){
        }
    }

    // Fill record store with some precanned names

    private void fillRecordStore(){
        ByteArrayOutputStream bout =
          new ByteArrayOutputStream();
        DataOutputStream dout =
          new DataOutputStreambout );

        forint i = 0; i < names.length; ++i ){
            addNamenames[i][0], names[i][1], bout,
                                             dout );
        }
    }

    // Open record store, if empty then fill it

    private boolean openRecordStore(){
        try {
            ifrs != null closeRecordStore();

            rs = RecordStore.openRecordStore(
                            "EnumDemo"true );
            ifrs.getNumRecords() == ){
                fillRecordStore();
            }
            return true;
        }
        catchRecordStoreException e ){
            return false;
        }
    }

    // Close record store

    private void closeRecordStore(){
        ifrs != null ){
            try {
                rs.closeRecordStore();
            }
            catchRecordStoreException e ){
            }

            rs = null;
        }
    }

    // Move to and read in a record

    private boolean readRecordint id, Record r ){
        boolean ok = false;


        r.firstName = null;
        r.lastName = null;

        ifrs != null ){
            try {
                rs.getRecordid, data, );
                r.firstName = din.readUTF();
                r.lastName = din.readUTF();
                din.reset();

                ok = true;
            }
            catchException e ){
            }
        }

        return ok;
    }

    // Event handling

    public void commandActionCommand c, Displayable d ){
        ifc == exitCommand ){
            exitMIDlet();
        else ifc == sortCommand ){
            display.setCurrentsortOptionsScreen );
        else ifd == sortOptionsScreen ){
            ifc == okCommand ){
                enumListScreen.resort();
            }

            display.setCurrentenumListScreen );
        }
    }

    // Main screen -- a list of names

    class EnumList extends List
                   implements RecordComparator,
                                 RecordFilter {
        private int    sortBy;
        private int    filterBy;
        private String filterText;
        private Record r1 = new Record();
        private Record r2 = new Record();



        // Constructor

        EnumList(){
            super"Enum Demo", IMPLICIT );
            addCommandexitCommand );
            addCommandsortCommand );
            setCommandListenerEnumDemoMIDlet.this );
        }

        // Resort the data and refill the list

        public void resort(){
          sortBy = sortOptionsScreen.getSortType();
          filterBy = sortOptionsScreen.getFilterType();
          filterText = sortOptionsScreen.getFilterText();

            RecordComparator comparator = null;
            RecordFilter     filter = null;

            ifsortBy != ){
                comparator = this;
            }

            iffilterBy != ){
                filter = this;
            }

            deleteAll();

            try {
              RecordEnumeration e = rs.enumerateRecords(
                          filter, comparator, false );
              Record            r = new Record();

              whilee.hasNextElement() ){
                    int id = e.nextRecordId();
                    ifreadRecordid, r ) ){
                      ifsortBy == SORT_LAST_FIRST ){
                            appendr.lastName + ", " +
                                    r.firstName, null );
                        else {
                            appendr.firstName + " " +
                                     r.lastName, null );
                        }
                    }
                }


                e.destroy();
            }
            catchRecordStoreException e ){
            }
        }

        // Delete all items in the list

        public void deleteAll(){
            int n = size();
            whilen > ){
                delete--n );
            }
        }

        // The comparator

        public int comparebyte[] rec1, byte[] rec2 ){
            try {
                ByteArrayInputStream  bin =
                     new ByteArrayInputStreamrec1 );
                DataInputStream       din =
                           new DataInputStreambin );

                r1.firstName = din.readUTF();
                r1.lastName = din.readUTF();

                bin = new ByteArrayInputStreamrec2 );
                din = new DataInputStreambin );

                r2.firstName = din.readUTF();
                r2.lastName = din.readUTF();

                ifsortBy == SORT_FIRST_LAST ){
                    int cmp = r1.firstName.compareTo(
                                       r2.firstName );
                 System.out.printlnr1.firstName +
                  " compares to " + r2.firstName +
                                    " gives " + cmp );
                    ifcmp != return (
                       cmp < ? PRECEDES : FOLLOWS );
                    cmp = r2.lastName.compareTor2.lastName );
                    ifcmp != return (
                       cmp < ? PRECEDES : FOLLOWS );
                else ifsortBy == SORT_LAST_FIRST ){
                    int cmp = r1.lastName.compareTo(

                                        r2.lastName );
                    ifcmp != return (
                        cmp < ? PRECEDES : FOLLOWS );
                    cmp = r2.firstName.compareTo(
                                        r2.firstName );
                    ifcmp != return (
                                  cmp < ? PRECEDES :
                                            FOLLOWS );
                }
            }
            catchException e ){
            }

            return EQUIVALENT;
        }

        // The filter

        public boolean matchesbyte[] rec ){
            try {
                ByteArrayInputStream  bin =
                      new ByteArrayInputStreamrec );
                DataInputStream       din =
                           new DataInputStreambin );

                r1.firstName = din.readUTF();
                r1.lastName = din.readUTF();

                iffilterBy == FILTER_STARTSWITH ){
                    returnr1.firstName.startsWith(
                                         filterText )
                            ||
                          r1.lastName.startsWith(
                                       filterText ) );
                else iffilterBy ==
                  FILTER_CONTAINS ){
                    returnr1.firstName.indexOf(
         filterText )
          >=||
          r1.lastName.indexOf(
        filterText>= 0);  
                }
            }
            catchException e ){
            }

            return false;
        }
    }

    // The options screen for choosing which sort and
    // filter modes to use, including the filter text

    class SortOptions extends Form {

        // Constructor

        SortOptions(){
            super"Sort Options" );
            addCommandokCommand );
            addCommandcancelCommand );
            setCommandListenerEnumDemoMIDlet.this );

            appendsortTypes );
            appendfilterTypes );
            appendfilterText );
        }

        // Return current sort type

        public int getSortType(){
            return sortTypes.getSelectedIndex();
        }

        // Return current filter type

        public int getFilterType(){
            return filterTypes.getSelectedIndex();
        }

        // Return current filter text

        public String getFilterText(){
            return filterText.getString();
        }

        // Labels and user interface components


        private String[] sortLabels =
                         "None""First Last",
                                "Last, First" };

        private String[] filterLabels =
                           "None""Starts With",
                                      "Contains" };

        private ChoiceGroup sortTypes =
                                 new ChoiceGroup(
                                        "Sort Type:",
                                ChoiceGroup.EXCLUSIVE,
                                   sortLabels, null );

        private ChoiceGroup filterTypes =
                                 new ChoiceGroup(
                                       "Filter Type:",
                                ChoiceGroup.EXCLUSIVE,
                                 filterLabels, null );

        private TextField filterText = new TextField(
                                       "Filter Text:",
                                        null, 20);
    }
}


           
       
Related examples in the same category
1. 一个简单的类,显示各种功能的有效值一个简单的类,显示各种功能的有效值
2. Sort records that contain multiple Java data types. Sort using String type.Sort records that contain multiple Java data types. Sort using String type.
3. 生日数据库生日数据库
4. J2ME的数据管理:记录管理系统J2ME的数据管理:记录管理系统
5. 收件阅读示例收件阅读示例
6. 我的记录监听
7. 简单排序的有效值简单排序的有效值
8.  Display a Form and TextField for searching records. Each record contains a String object. Display a Form and TextField for searching records. Each record contains a String object.
9. 搜索流搜索流
10. 整数类型分类整数类型分类
www.java2java.com | Contact Us
Copyright 2010 - 2030 Java Source and Support. All rights reserved.
All other trademarks are property of their respective owners.