Demonstrates simple record sorting and filtering : Sort Search « J2ME « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » J2ME » Sort SearchScreenshots 
Demonstrates simple record sorting and filtering
Demonstrates simple record sorting and filtering


/* 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. A simple class that shows various functionality of RMS.A simple class that shows various functionality of RMS.
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. Birthday DatabaseBirthday Database
4. J2ME Data Management: Record Management SystemJ2ME Data Management: Record Management System
5. Write Read ExampleWrite Read Example
6. My Record Listener
7. Simple Sort for RMSSimple Sort for RMS
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. Search StreamsSearch Streams
10. Int SortInt Sort
www_.__j_av___a__2_s.__co___m__ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.