J2ME登录和搜索记录存储

时间:2012-04-21 22:17:13

标签: search java-me login

我是J2ME的新手,我正在上课,我们使用它。我使用选择组文本字段等创建了一个简单的旅行预订MIDlet。然后我添加了一个记录存储来捕获这些信息。我现在有一个只需要用户名的用户登录,但我不知道如何验证用户名是否在Record Store中,所以只要用户名的Textfield不为空,我就接受任何一个用户名。 。我的第一个问题是如何验证用户是否存在,我已经可以创建一个帐户了。第二个问题是我如何不通过id搜索记录存储,而是在Record存储的每一行使用特定范围内的字符串。

到目前为止,这是我的代码:

$import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.util.Date;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.*;

/**
* @author XayBlu
*/
public class tripMe extends MIDlet implements CommandListener {
Form startForm, airForm, trainForm, cruiseForm, autoForm, Ext, Pass,home,login, create; 
Command Exit, Trip, Cinfo, AutC,AiC,CrC, info,Tme,trainC, logC,signC, createC, prev, newTrip, Home;
ChoiceGroup trans,hCAP, passCNT,airT,airC,AuC,AuT,CrL,CcabT,Tseat,TOP;
Display Xdisplay;
TextField Eneed, uName, uName2; 
Alert Final, FinalT, Sucess, nope;
DateField dDate, rDate;
Date d,r;
Image [] image;
String details =" ",tt="", Trav, Rdate, Ddate, extraA, Pcount,specialA, TT,AIR2, AIR,AUTO,AUTO2,CRUISE,CRUISE2,TRAIN,TRAIN2, USERS="USERS";
String op[] = {"Air","Auto","Cruise","Train"}; //Array Items for Choice Groups
String ep[] = {"Wheel Chair","Baby Seat","Extended Seatbelt","Extra Pillows","Oxygen Tank","GPS"};
String count[] = {"1","2","3","4","5","6","7","8"};
String AL []= {"American Airlines","Delta","US Airways","South West Airlines","United Airlines"};
String Rental [] = {"Alamo","Avis","Budget","Enteprise","Dollar","Hertz"};
String CL [] = {"Carnival","Norwegian","Royal Caribbean","Celebrity X","MSC"};
String CT [] = {"Compact","Standard","Full","SUV","Luxury","Sports"};
String Cabin [] = {"Suite","Ocean Balcony","Standard","Economy"};
String tCAB[] = {"Standard Seat","Sleeper Cart"};
String Toptions[] ={"Extra Luggage room","Salad Buffet","Wifi Access","Extra Blanket"};
RecordStore usr,itt;
RecordEnumeration recEnum = null;
RecordFilter filter = null;
int Umax=5;
int tran1 =6;
String last;
Byte [] data = new Byte[Umax];

 /* NEW COMMANDS FOR FLEXIBLE USER INPUT TO RECORD STORES */

public void writeRecord(String str){ // User to insert user input to record stores
byte[] rec = str.getBytes();
try{
usr.addRecord(rec, 0, rec.length);
}catch (Exception e){}
}

public void writeInfo(String str){ // User to insert user input to record stores
byte[] rec = str.getBytes();
try{
usr.addRecord(rec, tran1, rec.length);
}catch (Exception e){}
}

public void updateRecord(String str){
try{
usr.setRecord(1, str.getBytes(), 0, str.length());
}catch (Exception e){}
}

public void deleteRecord(){
try{
usr.deleteRecord(1);
}catch (Exception e){}
}

public void closeRecord(){
try{
usr.closeRecordStore();
}catch (Exception e){}
}

public void deleteRecStore(){
if (RecordStore.listRecordStores() != null){
try{
RecordStore.deleteRecordStore(USERS);
}catch (Exception e){}
}  
}


public void openRecStore()
{
try
{
  // The second parameter indicates that the record store
  // should be created if it does not exist
  usr = RecordStore.openRecordStore(USERS, true );
}
catch (Exception e)
{
  System.out.print("Could not open record store");
}
}

   public void readRecords()
{
try
{
  // Intentionally make this too small to test code below
  byte[] recData = new byte[5]; 
  int len;

  for (int i = 1; i <= usr.getNumRecords(); i++)      
  {
    if (usr.getRecordSize(i) > recData.length)
      recData = new byte[usr.getRecordSize(i)];

    len = usr.getRecord(i, recData, 0);
    home.append(new String(recData,0,len));
   // System.out.println("Record #" + i + ": " + new String(recData, 0, len));
   // System.out.println("------------------------------");                        
  }
}
catch (Exception e)
{
  nope = new Alert("Sorry no match!",null,null,AlertType.INFO);
  nope.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
  Xdisplay.setCurrent(nope, login);
}
}

}

class Filter implements RecordFilter {
private String search = null;

private ByteArrayInputStream inputstream = null;

private DataInputStream datainputstream = null;

public Filter(String search) {
this.search = search.toLowerCase();
}

  public void filterClose() {
try {
  if (inputstream != null) {
    inputstream.close();
  }
  if (datainputstream != null) {
    datainputstream.close();
  }
} catch (Exception error) {
}
}
}

public tripMe (){

    try{ //Initializing individual images for Choice Group Icons
        Image car = Image.createImage("/car2.png");
        Image plane = Image.createImage("/plane2.png");
        Image train = Image.createImage("/train2.png");
        Image cruise = Image.createImage("/cruise2.png");

       image = new Image[] {plane,car,cruise,train}; //Initializing Image array for ChoiceGroup
    }
    catch (java.io.IOException err) {System.out.print("Could not load pics"); } //Throws exception if pic cannot be found

    startForm = new Form("Get Away Today"); //Initialization of forms
    Pass = new Form ("Passenger Information");
    airForm = new Form("Low Prices!");
    autoForm = new Form("Find the best car for you");
    Ext = new Form("Itinerary Details");
    Ext.setTicker(new Ticker("Enjoy Your Vacation"));
    cruiseForm = new Form("Sail Away Today");
    trainForm = new Form("Chuuu- Chuuu");

    login = new Form("Sign up Today");
    home = new Form("Welcome Back");
    create = new Form("Create an account");

    trans = new ChoiceGroup("Select travel type",ChoiceGroup.EXCLUSIVE,op,image); //Transport tation choice group initialized with corresponding string and image array
    Exit = new Command("Exit", Command.EXIT,1);//Adding necessary commands
    Trip = new Command("Go", Command.SCREEN,2);//Adding go command which allows you to select travel type

    signC = new Command("Sign up",Command.SCREEN,2);
    logC = new Command("Log in",Command.SCREEN,2);
    createC = new Command("OK",Command.SCREEN,2);
    prev = new Command("History",Command.SCREEN,2);
    newTrip = new Command("Reservations",Command.SCREEN,2);
    Home = new Command("Log out",Command.SCREEN,1);

    hCAP = new ChoiceGroup("Extra Assistance", ChoiceGroup.MULTIPLE,ep,null);//Passenger Info items
    passCNT = new ChoiceGroup("Number of Passengers:",ChoiceGroup.POPUP,count,null);
    rDate = new DateField("Return Date",DateField.DATE_TIME);//Could not get the DateField to return string date value
    dDate = new DateField("Departure Date",DateField.DATE_TIME);
    Eneed = new TextField("Special Needs","",50,TextField.ANY);

    uName = new TextField("User Name","",5,TextField.ANY);
    uName2 = new TextField("User Name","",5,TextField.ANY);

    info = new Command("Next",Command.SCREEN,2);
    AiC = new Command("Complete",Command.SCREEN,2);//Air travel option items
    airT = new ChoiceGroup("Choose Airline", ChoiceGroup.POPUP,AL,null);//Airline selection
    airC = new ChoiceGroup("Select Class",ChoiceGroup.EXCLUSIVE);//Economy or first cass?
    airC.append("First Class", null);//Adding elements to Choice Group
    airC.append("Economy", null);

    AuC = new ChoiceGroup("Choose rental company", ChoiceGroup.POPUP,Rental,null);//Auto travel option items
    AuT = new ChoiceGroup("Select Vehicle Type", ChoiceGroup.EXCLUSIVE, CT,null);//Choicegroup for Vehicle type
    AutC = new Command("Drive away", Command.SCREEN,2);//Adding drive away command to form

    CrL = new ChoiceGroup("Select Cruise Line Comp.", ChoiceGroup.POPUP,CL,null);//Cruise option Items, Cruise line choicegroup
    CcabT = new ChoiceGroup("Select Cabin Type", ChoiceGroup.EXCLUSIVE,Cabin,null);//Cabin type choice group
    CrC = new Command("Cruise", Command.SCREEN,2);//Cruise form command being added

    trainC = new Command("Track!", Command.SCREEN,2);//Train option items, Train form command
    Tseat = new ChoiceGroup("Seat Type", ChoiceGroup.EXCLUSIVE,tCAB,null);//Choicegroup for train seat type
    TOP = new ChoiceGroup("Extra Options", ChoiceGroup.POPUP,Toptions,null);//Train extra options choice group



    /* Appending Items to necessary Forms*/

    create.append(uName2);
    create.addCommand(createC);
    create.setCommandListener(this);

    home.addCommand(prev);
    home.addCommand(newTrip);
    home.setCommandListener(this);

    login.append(uName);
    login.addCommand(logC);
    login.addCommand(signC);
    login.setCommandListener(this);

    startForm.append(trans);
    startForm.addCommand(Exit);
    startForm.addCommand(Trip);
    startForm.setCommandListener(this);


    Pass.append(dDate);
    Pass.append(rDate);
    Pass.append(hCAP);
    Pass.append(passCNT);
    Pass.append(Eneed);
    Pass.addCommand(info);
    Pass.setCommandListener(this);

    airForm.append(airT);
    airForm.append(airC);
    airForm.addCommand(AiC);
    airForm.setCommandListener(this);

    autoForm.addCommand(AutC);
    autoForm.append(AuC);
    autoForm.append(AuT);
    autoForm.setCommandListener(this);

    cruiseForm.addCommand(CrC);
    cruiseForm.append(CrL);
    cruiseForm.append(CcabT);
    cruiseForm.setCommandListener(this);

    trainForm.addCommand(trainC);
    trainForm.append(Tseat);
    trainForm.append(TOP);
    trainForm.setCommandListener(this);


    Ext.addCommand(Exit);
    Ext.addCommand(Home);
    Ext.setCommandListener(this);
    }




    public void startApp() {
    Xdisplay= Display.getDisplay(this);
    Xdisplay.setCurrent(login);
      }

    public void pauseApp() {
      }

    public void destroyApp(boolean unconditional) {
    notifyDestroyed();
       }

    public void commandAction(Command c, Displayable displayable){

     try {
          usr = RecordStore.openRecordStore(USERS, false);
        } catch (Exception e) {

        Sucess = new Alert("Error","Could not open Record Strore",null,AlertType.INFO);
        Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
        Xdisplay.setCurrent(Sucess, login);

                }
    if(c==signC)
     {
       Xdisplay.setCurrent(create);
      }
      else if(c == newTrip)
      {
       Xdisplay.setCurrent(startForm);
       }
      else if(c == prev)
      {

     try {
     String record = "";
     for (int i = 1; i < usr.getNextRecordID(); i++) {
    record = new String(usr.getRecord(i));
       }
   home.append(record);
   } catch (Exception e) {
    home.append("Could not retrieve data");
    try {
    usr.closeRecordStore();
    RecordStore.deleteRecordStore(USERS);
    } catch (Exception x) {
     }
    }

   try {
  usr.closeRecordStore();
  } catch (Exception e) {
  }
   }


   else if(c==createC)
   {
        try {
            usr = RecordStore.openRecordStore(USERS, true);

        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }

         if(!"".equals(uName2.getString()))
      {

        writeRecord(uName2.getString());

      }

        Sucess = new Alert("Welcome to the mile high club","Hello:"+uName2.getString(),null,AlertType.INFO);
        Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
        Xdisplay.setCurrent(Sucess, login);
    }
     else if (c == logC)
     { 
      if(!"".equals(uName.getString()))
      {
        String name = uName.getString();
        byte[]  data = name.getBytes();

        Xdisplay.setCurrent(home);

      }
      else 
              {
         Sucess = new Alert("Please enter user name!","Invalid user name",null,AlertType.INFO);
        Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
        Xdisplay.setCurrent(Sucess, login);
              }
      }

   else  if(c==Trip)
      {
        tt +="Travel Mode: "+ trans.getString(trans.getSelectedIndex())+"\n";



       if(trans.isSelected(0))
       {
           TT="A"; //Sets the type of travel based on choicegroup user selection
           Xdisplay.setCurrent(Pass);   
       }
       else if(trans.isSelected(1))
               {
                   TT="B";
                   Xdisplay.setCurrent(Pass);
               }
       else if(trans.isSelected(2))
               {
                   TT="C";
                   Xdisplay.setCurrent(Pass);
               }
       else if(trans.isSelected(3))
       {
           TT="D";
           Xdisplay.setCurrent(Pass);
         }
       }
      else if (c == info)
      {

     for(int i = 0; i < hCAP.size(); i++) //Checks to see what items are selected in a ChoiceGrou
       {
           if(hCAP.isSelected(i))
           {
               details += hCAP.getString(i)+","; //If item is selected then it is appended to the string details
           }
       }
       Rdate = rDate.getDate().toString();
       Ddate = dDate.getDate().toString();
       tt+= "Departure Date: "+ Ddate.substring(0, 10)+"\n";
       tt+= "Return Date:  "+ Rdate.substring(0, 10)+"\n";
       Pcount = passCNT.getString(passCNT.getSelectedIndex()); //Gets passenger count from choicegroup of integers
       specialA = Eneed.getString();
       Final = new Alert("Your travel details: \n","Requested Devices:"+details+"\nPassenger Count: "+Pcount+
             "\nSpecific Request: "+specialA,null,AlertType.INFO); //Appends string for alert 
       Final.setTimeout(Alert.FOREVER); 
       if("A".equals(TT)){ //Directs user to form based on travel type choice
           Xdisplay.setCurrent(Final,airForm);
       }
       else if("B".equals(TT)){//Directs user to form based on travel type choice
           Xdisplay.setCurrent(Final, autoForm);
       }
       else if ("C".equals(TT)){//Directs user to form based on travel type choice
           Xdisplay.setCurrent(Final, cruiseForm);
       }
       else if ("D".equals(TT)){//Directs user to form based on travel type choice
           Xdisplay.setCurrent(Final, trainForm);
       }
   }
  else if(c==AiC)
  {
      AIR = airT.getString(airT.getSelectedIndex());//Retrieves selected item from choicegroup
      tt+="Company: "+AIR+"\n";
      AIR2 = airC.getString(airC.getSelectedIndex());//Retrieves selected item from choicegroup


        FinalT = new Alert("Flight Details: \n","Airline Company:"+AIR+"\nSeat Class: "+AIR2,null,AlertType.INFO);
        FinalT.setTimeout(Alert.FOREVER); //Append string for FinalT Alert

         Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
              "\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
      Ext.append(Trav);

        extraA ="Carrier Details\n"+"Airline Carrier: "+AIR+"\nSeat Type: "+AIR2; //Append string for final display of info to user
        Ext.append(extraA);

        try {
            usr = RecordStore.openRecordStore(USERS, true);

        } catch (RecordStoreException ex) {
        }
         writeRecord("\n"+tt);
        Xdisplay.setCurrent(FinalT,Ext);

  }
  else if (c == AutC)
  {
      AUTO = AuC.getString(AuC.getSelectedIndex());//Retrieves selected item from choicegroup
      tt += "Company: "+AUTO+"\n";
      AUTO2 = AuT.getString(AuT.getSelectedIndex());//Retrieves selected item from choicegroup

      FinalT = new Alert("Auto Details: \n","Car Rental Company:"+AUTO+"\nVehicle Class: "+AUTO2,null,AlertType.INFO);
      FinalT.setTimeout(Alert.FOREVER); 

     Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
              "\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
      Ext.append(Trav);

       extraA ="Carrier Details\n"+"Rental Company: "+AUTO+"\nVehicle Class: "+AUTO2; //Append string for final display of info to user
       Ext.append(extraA);

       try {
            usr = RecordStore.openRecordStore(USERS, true);

        } catch (RecordStoreException ex) {
        }
       writeRecord("\n"+tt);
      Xdisplay.setCurrent(FinalT, Ext);
  }
  else if (c == CrC)
  {
      CRUISE = CrL.getString(CrL.getSelectedIndex());
      tt += "Company: "+CRUISE+"\n";
      CRUISE2 = CcabT.getString(CcabT.getSelectedIndex());

      FinalT = new Alert("Cruise Details: \n","Cruise Line Company:"+CRUISE+"\nCabin Type:"+CRUISE2,null,AlertType.INFO);
      FinalT.setTimeout(Alert.FOREVER); 

      Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
              "\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
      Ext.append(Trav);

      extraA ="Carrier Details\n"+"Cruise Line Company: "+CRUISE+"\nCabin Type: "+CRUISE2; //Append string for final display of info to user
      Ext.append(extraA);
      try {
            usr = RecordStore.openRecordStore(USERS, true);

        } catch (RecordStoreException ex) {
        }
       writeRecord("\n"+tt);
      Xdisplay.setCurrent(FinalT, Ext);


      }
     else if (c == trainC)
     {
       TRAIN = Tseat.getString(Tseat.getSelectedIndex());
       TRAIN2 = TOP.getString(TOP.getSelectedIndex());

       FinalT = new Alert("Train Details: \n","Train Seat Type:"+TRAIN+"\nExtra Amenities:"+TRAIN2,null,AlertType.INFO);
      FinalT.setTimeout(Alert.FOREVER); 

      Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
              "\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
      Ext.append(Trav);

       extraA ="Carrier Details\n"+"Train Seat Type: "+TRAIN+"\nExtra Amenities: "+TRAIN2; //Append string for final display of info to user
        Ext.append(extraA);

         try {
            usr = RecordStore.openRecordStore(USERS, true);

         } catch (RecordStoreException ex) {
          }

        writeRecord("\n"+tt);
         Xdisplay.setCurrent(FinalT, Ext);



     }
    else if(c == Home)
    {
     home.deleteAll();

      Xdisplay.setCurrent(login);

     }
     else  if(c==Exit)
    {
     destroyApp(false);
     notifyDestroyed();
    }


    }


   }

0 个答案:

没有答案